]> git.saurik.com Git - wxWidgets.git/blob - src/unix/utilsunx.cpp
Whitespaces, tabs and fix to the lack of empty line at end.
[wxWidgets.git] / src / unix / utilsunx.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: unix/utilsunx.cpp
3 // Purpose: generic Unix implementation of many wx functions
4 // Author: Vadim Zeitlin
5 // Id: $Id$
6 // Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // ============================================================================
11 // declarations
12 // ============================================================================
13
14 // ----------------------------------------------------------------------------
15 // headers
16 // ----------------------------------------------------------------------------
17
18 #include <pwd.h>
19
20 // for compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #include "wx/defs.h"
24 #include "wx/string.h"
25
26 #include "wx/intl.h"
27 #include "wx/log.h"
28 #include "wx/app.h"
29 #include "wx/apptrait.h"
30
31 #include "wx/utils.h"
32 #include "wx/process.h"
33 #include "wx/thread.h"
34
35 #include "wx/wfstream.h"
36
37 #include "wx/unix/execute.h"
38
39 #if wxUSE_STREAMS
40
41 // define this to let wxexec.cpp know that we know what we're doing
42 #define _WX_USED_BY_WXEXECUTE_
43 #include "../common/execcmn.cpp"
44
45 #endif // wxUSE_STREAMS
46
47 #if wxUSE_BASE
48
49 #if defined(__MWERKS__) && defined(__MACH__)
50 #ifndef WXWIN_OS_DESCRIPTION
51 #define WXWIN_OS_DESCRIPTION "MacOS X"
52 #endif
53 #ifndef HAVE_NANOSLEEP
54 #define HAVE_NANOSLEEP
55 #endif
56 #ifndef HAVE_UNAME
57 #define HAVE_UNAME
58 #endif
59
60 // our configure test believes we can use sigaction() if the function is
61 // available but Metrowekrs with MSL run-time does have the function but
62 // doesn't have sigaction struct so finally we can't use it...
63 #ifdef __MSL__
64 #undef wxUSE_ON_FATAL_EXCEPTION
65 #define wxUSE_ON_FATAL_EXCEPTION 0
66 #endif
67 #endif
68
69 // not only the statfs syscall is called differently depending on platform, but
70 // one of its incarnations, statvfs(), takes different arguments under
71 // different platforms and even different versions of the same system (Solaris
72 // 7 and 8): if you want to test for this, don't forget that the problems only
73 // appear if the large files support is enabled
74 #ifdef HAVE_STATFS
75 #ifdef __BSD__
76 #include <sys/param.h>
77 #include <sys/mount.h>
78 #else // !__BSD__
79 #include <sys/vfs.h>
80 #endif // __BSD__/!__BSD__
81
82 #define wxStatfs statfs
83 #endif // HAVE_STATFS
84
85 #ifdef HAVE_STATVFS
86 #include <sys/statvfs.h>
87
88 #define wxStatfs statvfs
89 #endif // HAVE_STATVFS
90
91 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
92 // WX_STATFS_T is detected by configure
93 #define wxStatfs_t WX_STATFS_T
94 #endif
95
96 // SGI signal.h defines signal handler arguments differently depending on
97 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
98 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
99 #define _LANGUAGE_C_PLUS_PLUS 1
100 #endif // SGI hack
101
102 #include <stdarg.h>
103 #include <dirent.h>
104 #include <string.h>
105 #include <sys/stat.h>
106 #include <sys/types.h>
107 #include <sys/wait.h>
108 #include <unistd.h>
109 #include <errno.h>
110 #include <netdb.h>
111 #include <signal.h>
112 #include <fcntl.h> // for O_WRONLY and friends
113 #include <time.h> // nanosleep() and/or usleep()
114 #include <ctype.h> // isspace()
115 #include <sys/time.h> // needed for FD_SETSIZE
116
117 #ifdef HAVE_UNAME
118 #include <sys/utsname.h> // for uname()
119 #endif // HAVE_UNAME
120
121 // ----------------------------------------------------------------------------
122 // conditional compilation
123 // ----------------------------------------------------------------------------
124
125 // many versions of Unices have this function, but it is not defined in system
126 // headers - please add your system here if it is the case for your OS.
127 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
128 #if !defined(HAVE_USLEEP) && \
129 (defined(__SUN__) && !defined(__SunOs_5_6) && \
130 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
131 defined(__osf__) || defined(__EMX__)
132 extern "C"
133 {
134 #ifdef __SUN__
135 int usleep(unsigned int usec);
136 #else // !Sun
137 #ifdef __EMX__
138 /* I copied this from the XFree86 diffs. AV. */
139 #define INCL_DOSPROCESS
140 #include <os2.h>
141 inline void usleep(unsigned long delay)
142 {
143 DosSleep(delay ? (delay/1000l) : 1l);
144 }
145 #else // !Sun && !EMX
146 void usleep(unsigned long usec);
147 #endif
148 #endif // Sun/EMX/Something else
149 };
150
151 #define HAVE_USLEEP 1
152 #endif // Unices without usleep()
153
154 // ============================================================================
155 // implementation
156 // ============================================================================
157
158 // ----------------------------------------------------------------------------
159 // sleeping
160 // ----------------------------------------------------------------------------
161
162 void wxSleep(int nSecs)
163 {
164 sleep(nSecs);
165 }
166
167 void wxMicroSleep(unsigned long microseconds)
168 {
169 #if defined(HAVE_NANOSLEEP)
170 timespec tmReq;
171 tmReq.tv_sec = (time_t)(microseconds / 1000000);
172 tmReq.tv_nsec = (microseconds % 1000000) * 1000;
173
174 // we're not interested in remaining time nor in return value
175 (void)nanosleep(&tmReq, (timespec *)NULL);
176 #elif defined(HAVE_USLEEP)
177 // uncomment this if you feel brave or if you are sure that your version
178 // of Solaris has a safe usleep() function but please notice that usleep()
179 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
180 // documented as MT-Safe
181 #if defined(__SUN__) && wxUSE_THREADS
182 #error "usleep() cannot be used in MT programs under Solaris."
183 #endif // Sun
184
185 usleep(microseconds);
186 #elif defined(HAVE_SLEEP)
187 // under BeOS sleep() takes seconds (what about other platforms, if any?)
188 sleep(microseconds * 1000000);
189 #else // !sleep function
190 #error "usleep() or nanosleep() function required for wxMicroSleep"
191 #endif // sleep function
192 }
193
194 void wxMilliSleep(unsigned long milliseconds)
195 {
196 wxMicroSleep(milliseconds*1000);
197 }
198
199 // ----------------------------------------------------------------------------
200 // process management
201 // ----------------------------------------------------------------------------
202
203 int wxKill(long pid, wxSignal sig, wxKillError *rc)
204 {
205 int err = kill((pid_t)pid, (int)sig);
206 if ( rc )
207 {
208 switch ( errno )
209 {
210 case 0:
211 *rc = wxKILL_OK;
212 break;
213
214 case EINVAL:
215 *rc = wxKILL_BAD_SIGNAL;
216 break;
217
218 case EPERM:
219 *rc = wxKILL_ACCESS_DENIED;
220 break;
221
222 case ESRCH:
223 *rc = wxKILL_NO_PROCESS;
224 break;
225
226 default:
227 // this goes against Unix98 docs so log it
228 wxLogDebug(_T("unexpected kill(2) return value %d"), err);
229
230 // something else...
231 *rc = wxKILL_ERROR;
232 }
233 }
234
235 return err;
236 }
237
238 #define WXEXECUTE_NARGS 127
239
240 long wxExecute( const wxString& command, int flags, wxProcess *process )
241 {
242 wxCHECK_MSG( !command.IsEmpty(), 0, wxT("can't exec empty command") );
243
244 #if wxUSE_THREADS
245 // fork() doesn't mix well with POSIX threads: on many systems the program
246 // deadlocks or crashes for some reason. Probably our code is buggy and
247 // doesn't do something which must be done to allow this to work, but I
248 // don't know what yet, so for now just warn the user (this is the least we
249 // can do) about it
250 wxASSERT_MSG( wxThread::IsMain(),
251 _T("wxExecute() can be called only from the main thread") );
252 #endif // wxUSE_THREADS
253
254 int argc = 0;
255 wxChar *argv[WXEXECUTE_NARGS];
256 wxString argument;
257 const wxChar *cptr = command.c_str();
258 wxChar quotechar = wxT('\0'); // is arg quoted?
259 bool escaped = FALSE;
260
261 // split the command line in arguments
262 do
263 {
264 argument=wxT("");
265 quotechar = wxT('\0');
266
267 // eat leading whitespace:
268 while ( wxIsspace(*cptr) )
269 cptr++;
270
271 if ( *cptr == wxT('\'') || *cptr == wxT('"') )
272 quotechar = *cptr++;
273
274 do
275 {
276 if ( *cptr == wxT('\\') && ! escaped )
277 {
278 escaped = TRUE;
279 cptr++;
280 continue;
281 }
282
283 // all other characters:
284 argument += *cptr++;
285 escaped = FALSE;
286
287 // have we reached the end of the argument?
288 if ( (*cptr == quotechar && ! escaped)
289 || (quotechar == wxT('\0') && wxIsspace(*cptr))
290 || *cptr == wxT('\0') )
291 {
292 wxASSERT_MSG( argc < WXEXECUTE_NARGS,
293 wxT("too many arguments in wxExecute") );
294
295 argv[argc] = new wxChar[argument.length() + 1];
296 wxStrcpy(argv[argc], argument.c_str());
297 argc++;
298
299 // if not at end of buffer, swallow last character:
300 if(*cptr)
301 cptr++;
302
303 break; // done with this one, start over
304 }
305 } while(*cptr);
306 } while(*cptr);
307 argv[argc] = NULL;
308
309 // do execute the command
310 long lRc = wxExecute(argv, flags, process);
311
312 // clean up
313 argc = 0;
314 while( argv[argc] )
315 delete [] argv[argc++];
316
317 return lRc;
318 }
319
320 // ----------------------------------------------------------------------------
321 // wxShell
322 // ----------------------------------------------------------------------------
323
324 static wxString wxMakeShellCommand(const wxString& command)
325 {
326 wxString cmd;
327 if ( !command )
328 {
329 // just an interactive shell
330 cmd = _T("xterm");
331 }
332 else
333 {
334 // execute command in a shell
335 cmd << _T("/bin/sh -c '") << command << _T('\'');
336 }
337
338 return cmd;
339 }
340
341 bool wxShell(const wxString& command)
342 {
343 return wxExecute(wxMakeShellCommand(command), wxEXEC_SYNC) == 0;
344 }
345
346 bool wxShell(const wxString& command, wxArrayString& output)
347 {
348 wxCHECK_MSG( !!command, FALSE, _T("can't exec shell non interactively") );
349
350 return wxExecute(wxMakeShellCommand(command), output);
351 }
352
353 // Shutdown or reboot the PC
354 bool wxShutdown(wxShutdownFlags wFlags)
355 {
356 wxChar level;
357 switch ( wFlags )
358 {
359 case wxSHUTDOWN_POWEROFF:
360 level = _T('0');
361 break;
362
363 case wxSHUTDOWN_REBOOT:
364 level = _T('6');
365 break;
366
367 default:
368 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
369 return FALSE;
370 }
371
372 return system(wxString::Format(_T("init %c"), level).mb_str()) == 0;
373 }
374
375
376 // ----------------------------------------------------------------------------
377 // wxStream classes to support IO redirection in wxExecute
378 // ----------------------------------------------------------------------------
379
380 #if wxUSE_STREAMS
381
382 bool wxPipeInputStream::CanRead() const
383 {
384 if ( m_lasterror == wxSTREAM_EOF )
385 return FALSE;
386
387 // check if there is any input available
388 struct timeval tv;
389 tv.tv_sec = 0;
390 tv.tv_usec = 0;
391
392 const int fd = m_file->fd();
393
394 fd_set readfds;
395 FD_ZERO(&readfds);
396 FD_SET(fd, &readfds);
397 switch ( select(fd + 1, &readfds, NULL, NULL, &tv) )
398 {
399 case -1:
400 wxLogSysError(_("Impossible to get child process input"));
401 // fall through
402
403 case 0:
404 return FALSE;
405
406 default:
407 wxFAIL_MSG(_T("unexpected select() return value"));
408 // still fall through
409
410 case 1:
411 // input available -- or maybe not, as select() returns 1 when a
412 // read() will complete without delay, but it could still not read
413 // anything
414 return !Eof();
415 }
416 }
417
418 #endif // wxUSE_STREAMS
419
420 // ----------------------------------------------------------------------------
421 // wxExecute: the real worker function
422 // ----------------------------------------------------------------------------
423
424 #ifdef __VMS
425 #pragma message disable codeunreachable
426 #endif
427
428 long wxExecute(wxChar **argv,
429 int flags,
430 wxProcess *process)
431 {
432 // for the sync execution, we return -1 to indicate failure, but for async
433 // case we return 0 which is never a valid PID
434 //
435 // we define this as a macro, not a variable, to avoid compiler warnings
436 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
437 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
438
439 wxCHECK_MSG( *argv, ERROR_RETURN_CODE, wxT("can't exec empty command") );
440
441 #if wxUSE_UNICODE
442 int mb_argc = 0;
443 char *mb_argv[WXEXECUTE_NARGS];
444
445 while (argv[mb_argc])
446 {
447 wxWX2MBbuf mb_arg = wxConvertWX2MB(argv[mb_argc]);
448 mb_argv[mb_argc] = strdup(mb_arg);
449 mb_argc++;
450 }
451 mb_argv[mb_argc] = (char *) NULL;
452
453 // this macro will free memory we used above
454 #define ARGS_CLEANUP \
455 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
456 free(mb_argv[mb_argc])
457 #else // ANSI
458 // no need for cleanup
459 #define ARGS_CLEANUP
460
461 wxChar **mb_argv = argv;
462 #endif // Unicode/ANSI
463
464 // we want this function to work even if there is no wxApp so ensure that
465 // we have a valid traits pointer
466 wxConsoleAppTraits traitsConsole;
467 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
468 if ( !traits )
469 traits = &traitsConsole;
470
471 // this struct contains all information which we pass to and from
472 // wxAppTraits methods
473 wxExecuteData execData;
474 execData.flags = flags;
475 execData.process = process;
476
477 // create pipes
478 if ( !traits->CreateEndProcessPipe(execData) )
479 {
480 wxLogError( _("Failed to execute '%s'\n"), *argv );
481
482 ARGS_CLEANUP;
483
484 return ERROR_RETURN_CODE;
485 }
486
487 // pipes for inter process communication
488 wxPipe pipeIn, // stdin
489 pipeOut, // stdout
490 pipeErr; // stderr
491
492 if ( process && process->IsRedirected() )
493 {
494 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
495 {
496 wxLogError( _("Failed to execute '%s'\n"), *argv );
497
498 ARGS_CLEANUP;
499
500 return ERROR_RETURN_CODE;
501 }
502 }
503
504 // fork the process
505 //
506 // NB: do *not* use vfork() here, it completely breaks this code for some
507 // reason under Solaris (and maybe others, although not under Linux)
508 // But on OpenVMS we do not have fork so we have to use vfork and
509 // cross our fingers that it works.
510 #ifdef __VMS
511 pid_t pid = vfork();
512 #else
513 pid_t pid = fork();
514 #endif
515 if ( pid == -1 ) // error?
516 {
517 wxLogSysError( _("Fork failed") );
518
519 ARGS_CLEANUP;
520
521 return ERROR_RETURN_CODE;
522 }
523 else if ( pid == 0 ) // we're in child
524 {
525 // These lines close the open file descriptors to to avoid any
526 // input/output which might block the process or irritate the user. If
527 // one wants proper IO for the subprocess, the right thing to do is to
528 // start an xterm executing it.
529 if ( !(flags & wxEXEC_SYNC) )
530 {
531 // FD_SETSIZE is unsigned under BSD, signed under other platforms
532 // so we need a cast to avoid warnings on all platforms
533 for ( int fd = 0; fd < (int)FD_SETSIZE; fd++ )
534 {
535 if ( fd == pipeIn[wxPipe::Read]
536 || fd == pipeOut[wxPipe::Write]
537 || fd == pipeErr[wxPipe::Write]
538 || traits->IsWriteFDOfEndProcessPipe(execData, fd) )
539 {
540 // don't close this one, we still need it
541 continue;
542 }
543
544 // leave stderr opened too, it won't do any harm
545 if ( fd != STDERR_FILENO )
546 close(fd);
547 }
548 }
549
550 #if !defined(__VMS) && !defined(__EMX__)
551 if ( flags & wxEXEC_MAKE_GROUP_LEADER )
552 {
553 // Set process group to child process' pid. Then killing -pid
554 // of the parent will kill the process and all of its children.
555 setsid();
556 }
557 #endif // !__VMS
558
559 // reading side can be safely closed but we should keep the write one
560 // opened
561 traits->DetachWriteFDOfEndProcessPipe(execData);
562
563 // redirect stdin, stdout and stderr
564 if ( pipeIn.IsOk() )
565 {
566 if ( dup2(pipeIn[wxPipe::Read], STDIN_FILENO) == -1 ||
567 dup2(pipeOut[wxPipe::Write], STDOUT_FILENO) == -1 ||
568 dup2(pipeErr[wxPipe::Write], STDERR_FILENO) == -1 )
569 {
570 wxLogSysError(_("Failed to redirect child process input/output"));
571 }
572
573 pipeIn.Close();
574 pipeOut.Close();
575 pipeErr.Close();
576 }
577
578 execvp (*mb_argv, mb_argv);
579
580 fprintf(stderr, "execvp(");
581 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
582 for ( char **ppc_ = mb_argv; *ppc_; ppc_++ )
583 fprintf(stderr, "%s%s", ppc_ == mb_argv ? "" : ", ", *ppc_);
584 fprintf(stderr, ") failed with error %d!\n", errno);
585
586 // there is no return after successful exec()
587 _exit(-1);
588
589 // some compilers complain about missing return - of course, they
590 // should know that exit() doesn't return but what else can we do if
591 // they don't?
592 //
593 // and, sure enough, other compilers complain about unreachable code
594 // after exit() call, so we can just always have return here...
595 #if defined(__VMS) || defined(__INTEL_COMPILER)
596 return 0;
597 #endif
598 }
599 else // we're in parent
600 {
601 ARGS_CLEANUP;
602
603 // save it for WaitForChild() use
604 execData.pid = pid;
605
606 // prepare for IO redirection
607
608 #if wxUSE_STREAMS
609 // the input buffer bufOut is connected to stdout, this is why it is
610 // called bufOut and not bufIn
611 wxStreamTempInputBuffer bufOut,
612 bufErr;
613 #endif // wxUSE_STREAMS
614
615 if ( process && process->IsRedirected() )
616 {
617 #if wxUSE_STREAMS
618 wxOutputStream *inStream =
619 new wxFileOutputStream(pipeIn.Detach(wxPipe::Write));
620
621 wxPipeInputStream *outStream =
622 new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
623
624 wxPipeInputStream *errStream =
625 new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
626
627 process->SetPipeStreams(outStream, inStream, errStream);
628
629 bufOut.Init(outStream);
630 bufErr.Init(errStream);
631
632 execData.bufOut = &bufOut;
633 execData.bufErr = &bufErr;
634 #endif // wxUSE_STREAMS
635 }
636
637 if ( pipeIn.IsOk() )
638 {
639 pipeIn.Close();
640 pipeOut.Close();
641 pipeErr.Close();
642 }
643
644 return traits->WaitForChild(execData);
645 }
646
647 return ERROR_RETURN_CODE;
648 }
649
650 #ifdef __VMS
651 #pragma message enable codeunreachable
652 #endif
653
654 #undef ERROR_RETURN_CODE
655 #undef ARGS_CLEANUP
656
657 // ----------------------------------------------------------------------------
658 // file and directory functions
659 // ----------------------------------------------------------------------------
660
661 const wxChar* wxGetHomeDir( wxString *home )
662 {
663 *home = wxGetUserHome( wxString() );
664 wxString tmp;
665 if ( home->IsEmpty() )
666 *home = wxT("/");
667 #ifdef __VMS
668 tmp = *home;
669 if ( tmp.Last() != wxT(']'))
670 if ( tmp.Last() != wxT('/')) *home << wxT('/');
671 #endif
672 return home->c_str();
673 }
674
675 #if wxUSE_UNICODE
676 const wxMB2WXbuf wxGetUserHome( const wxString &user )
677 #else // just for binary compatibility -- there is no 'const' here
678 char *wxGetUserHome( const wxString &user )
679 #endif
680 {
681 struct passwd *who = (struct passwd *) NULL;
682
683 if ( !user )
684 {
685 wxChar *ptr;
686
687 if ((ptr = wxGetenv(wxT("HOME"))) != NULL)
688 {
689 #if wxUSE_UNICODE
690 wxWCharBuffer buffer( ptr );
691 return buffer;
692 #else
693 return ptr;
694 #endif
695 }
696 if ((ptr = wxGetenv(wxT("USER"))) != NULL || (ptr = wxGetenv(wxT("LOGNAME"))) != NULL)
697 {
698 who = getpwnam(wxConvertWX2MB(ptr));
699 }
700
701 // We now make sure the the user exists!
702 if (who == NULL)
703 {
704 who = getpwuid(getuid());
705 }
706 }
707 else
708 {
709 who = getpwnam (user.mb_str());
710 }
711
712 return wxConvertMB2WX(who ? who->pw_dir : 0);
713 }
714
715 // ----------------------------------------------------------------------------
716 // network and user id routines
717 // ----------------------------------------------------------------------------
718
719 // retrieve either the hostname or FQDN depending on platform (caller must
720 // check whether it's one or the other, this is why this function is for
721 // private use only)
722 static bool wxGetHostNameInternal(wxChar *buf, int sz)
723 {
724 wxCHECK_MSG( buf, FALSE, wxT("NULL pointer in wxGetHostNameInternal") );
725
726 *buf = wxT('\0');
727
728 // we're using uname() which is POSIX instead of less standard sysinfo()
729 #if defined(HAVE_UNAME)
730 struct utsname uts;
731 bool ok = uname(&uts) != -1;
732 if ( ok )
733 {
734 wxStrncpy(buf, wxConvertMB2WX(uts.nodename), sz - 1);
735 buf[sz] = wxT('\0');
736 }
737 #elif defined(HAVE_GETHOSTNAME)
738 bool ok = gethostname(buf, sz) != -1;
739 #else // no uname, no gethostname
740 wxFAIL_MSG(wxT("don't know host name for this machine"));
741
742 bool ok = FALSE;
743 #endif // uname/gethostname
744
745 if ( !ok )
746 {
747 wxLogSysError(_("Cannot get the hostname"));
748 }
749
750 return ok;
751 }
752
753 bool wxGetHostName(wxChar *buf, int sz)
754 {
755 bool ok = wxGetHostNameInternal(buf, sz);
756
757 if ( ok )
758 {
759 // BSD systems return the FQDN, we only want the hostname, so extract
760 // it (we consider that dots are domain separators)
761 wxChar *dot = wxStrchr(buf, wxT('.'));
762 if ( dot )
763 {
764 // nuke it
765 *dot = wxT('\0');
766 }
767 }
768
769 return ok;
770 }
771
772 bool wxGetFullHostName(wxChar *buf, int sz)
773 {
774 bool ok = wxGetHostNameInternal(buf, sz);
775
776 if ( ok )
777 {
778 if ( !wxStrchr(buf, wxT('.')) )
779 {
780 struct hostent *host = gethostbyname(wxConvertWX2MB(buf));
781 if ( !host )
782 {
783 wxLogSysError(_("Cannot get the official hostname"));
784
785 ok = FALSE;
786 }
787 else
788 {
789 // the canonical name
790 wxStrncpy(buf, wxConvertMB2WX(host->h_name), sz);
791 }
792 }
793 //else: it's already a FQDN (BSD behaves this way)
794 }
795
796 return ok;
797 }
798
799 bool wxGetUserId(wxChar *buf, int sz)
800 {
801 struct passwd *who;
802
803 *buf = wxT('\0');
804 if ((who = getpwuid(getuid ())) != NULL)
805 {
806 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
807 return TRUE;
808 }
809
810 return FALSE;
811 }
812
813 bool wxGetUserName(wxChar *buf, int sz)
814 {
815 struct passwd *who;
816
817 *buf = wxT('\0');
818 if ((who = getpwuid (getuid ())) != NULL)
819 {
820 // pw_gecos field in struct passwd is not standard
821 #ifdef HAVE_PW_GECOS
822 char *comma = strchr(who->pw_gecos, ',');
823 if (comma)
824 *comma = '\0'; // cut off non-name comment fields
825 wxStrncpy (buf, wxConvertMB2WX(who->pw_gecos), sz - 1);
826 #else // !HAVE_PW_GECOS
827 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
828 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
829 return TRUE;
830 }
831
832 return FALSE;
833 }
834
835 // this function is in mac/utils.cpp for wxMac
836 #ifndef __WXMAC__
837
838 wxString wxGetOsDescription()
839 {
840 #ifndef WXWIN_OS_DESCRIPTION
841 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
842 #else
843 return wxString::FromAscii( WXWIN_OS_DESCRIPTION );
844 #endif
845 }
846
847 #endif // !__WXMAC__
848
849 unsigned long wxGetProcessId()
850 {
851 return (unsigned long)getpid();
852 }
853
854 long wxGetFreeMemory()
855 {
856 #if defined(__LINUX__)
857 // get it from /proc/meminfo
858 FILE *fp = fopen("/proc/meminfo", "r");
859 if ( fp )
860 {
861 long memFree = -1;
862
863 char buf[1024];
864 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
865 {
866 long memTotal, memUsed;
867 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
868 }
869
870 fclose(fp);
871
872 return memFree;
873 }
874 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
875 return sysconf(_SC_AVPHYS_PAGES)*sysconf(_SC_PAGESIZE);
876 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
877 #endif
878
879 // can't find it out
880 return -1;
881 }
882
883 bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
884 {
885 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
886 // the case to "char *" is needed for AIX 4.3
887 wxStatfs_t fs;
888 if ( wxStatfs((char *)(const char*)path.fn_str(), &fs) != 0 )
889 {
890 wxLogSysError( wxT("Failed to get file system statistics") );
891
892 return FALSE;
893 }
894
895 // under Solaris we also have to use f_frsize field instead of f_bsize
896 // which is in general a multiple of f_frsize
897 #ifdef HAVE_STATVFS
898 wxLongLong blockSize = fs.f_frsize;
899 #else // HAVE_STATFS
900 wxLongLong blockSize = fs.f_bsize;
901 #endif // HAVE_STATVFS/HAVE_STATFS
902
903 if ( pTotal )
904 {
905 *pTotal = wxLongLong(fs.f_blocks) * blockSize;
906 }
907
908 if ( pFree )
909 {
910 *pFree = wxLongLong(fs.f_bavail) * blockSize;
911 }
912
913 return TRUE;
914 #else // !HAVE_STATFS && !HAVE_STATVFS
915 return FALSE;
916 #endif // HAVE_STATFS
917 }
918
919 // ----------------------------------------------------------------------------
920 // env vars
921 // ----------------------------------------------------------------------------
922
923 bool wxGetEnv(const wxString& var, wxString *value)
924 {
925 // wxGetenv is defined as getenv()
926 wxChar *p = wxGetenv(var);
927 if ( !p )
928 return FALSE;
929
930 if ( value )
931 {
932 *value = p;
933 }
934
935 return TRUE;
936 }
937
938 bool wxSetEnv(const wxString& variable, const wxChar *value)
939 {
940 #if defined(HAVE_SETENV)
941 return setenv(variable.mb_str(),
942 value ? (const char *)wxString(value).mb_str()
943 : NULL,
944 1 /* overwrite */) == 0;
945 #elif defined(HAVE_PUTENV)
946 wxString s = variable;
947 if ( value )
948 s << _T('=') << value;
949
950 // transform to ANSI
951 const wxWX2MBbuf p = s.mb_str();
952
953 // the string will be free()d by libc
954 char *buf = (char *)malloc(strlen(p) + 1);
955 strcpy(buf, p);
956
957 return putenv(buf) == 0;
958 #else // no way to set an env var
959 return false;
960 #endif
961 }
962
963 // ----------------------------------------------------------------------------
964 // signal handling
965 // ----------------------------------------------------------------------------
966
967 #if wxUSE_ON_FATAL_EXCEPTION
968
969 #include <signal.h>
970
971 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
972 {
973 if ( wxTheApp )
974 {
975 // give the user a chance to do something special about this
976 wxTheApp->OnFatalException();
977 }
978
979 abort();
980 }
981
982 bool wxHandleFatalExceptions(bool doit)
983 {
984 // old sig handlers
985 static bool s_savedHandlers = FALSE;
986 static struct sigaction s_handlerFPE,
987 s_handlerILL,
988 s_handlerBUS,
989 s_handlerSEGV;
990
991 bool ok = TRUE;
992 if ( doit && !s_savedHandlers )
993 {
994 // install the signal handler
995 struct sigaction act;
996
997 // some systems extend it with non std fields, so zero everything
998 memset(&act, 0, sizeof(act));
999
1000 act.sa_handler = wxFatalSignalHandler;
1001 sigemptyset(&act.sa_mask);
1002 act.sa_flags = 0;
1003
1004 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1005 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1006 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1007 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1008 if ( !ok )
1009 {
1010 wxLogDebug(_T("Failed to install our signal handler."));
1011 }
1012
1013 s_savedHandlers = TRUE;
1014 }
1015 else if ( s_savedHandlers )
1016 {
1017 // uninstall the signal handler
1018 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1019 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1020 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1021 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1022 if ( !ok )
1023 {
1024 wxLogDebug(_T("Failed to uninstall our signal handler."));
1025 }
1026
1027 s_savedHandlers = FALSE;
1028 }
1029 //else: nothing to do
1030
1031 return ok;
1032 }
1033
1034 #endif // wxUSE_ON_FATAL_EXCEPTION
1035
1036 // ----------------------------------------------------------------------------
1037 // error and debug output routines (deprecated, use wxLog)
1038 // ----------------------------------------------------------------------------
1039
1040 #if WXWIN_COMPATIBILITY_2_2
1041
1042 void wxDebugMsg( const char *format, ... )
1043 {
1044 va_list ap;
1045 va_start( ap, format );
1046 vfprintf( stderr, format, ap );
1047 fflush( stderr );
1048 va_end(ap);
1049 }
1050
1051 void wxError( const wxString &msg, const wxString &title )
1052 {
1053 wxFprintf( stderr, _("Error ") );
1054 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1055 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1056 wxFprintf( stderr, wxT(".\n") );
1057 }
1058
1059 void wxFatalError( const wxString &msg, const wxString &title )
1060 {
1061 wxFprintf( stderr, _("Error ") );
1062 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1063 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1064 wxFprintf( stderr, wxT(".\n") );
1065 exit(3); // the same exit code as for abort()
1066 }
1067
1068 #endif // WXWIN_COMPATIBILITY_2_2
1069
1070 #endif // wxUSE_BASE
1071
1072 #if wxUSE_GUI
1073
1074 // ----------------------------------------------------------------------------
1075 // wxExecute support
1076 // ----------------------------------------------------------------------------
1077
1078 // Darwin doesn't use the same process end detection mechanisms so we don't
1079 // need wxExecute-related helpers for it
1080 #if !(defined(__DARWIN__) && defined(__WXMAC__))
1081
1082 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData& execData)
1083 {
1084 return execData.pipeEndProcDetect.Create();
1085 }
1086
1087 bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData& execData, int fd)
1088 {
1089 return fd == (execData.pipeEndProcDetect)[wxPipe::Write];
1090 }
1091
1092 void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData& execData)
1093 {
1094 execData.pipeEndProcDetect.Detach(wxPipe::Write);
1095 execData.pipeEndProcDetect.Close();
1096 }
1097
1098 #else // !Darwin
1099
1100 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData& WXUNUSED(execData))
1101 {
1102 return true;
1103 }
1104
1105 bool
1106 wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData& WXUNUSED(execData),
1107 int WXUNUSED(fd))
1108 {
1109 return false;
1110 }
1111
1112 void
1113 wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData& WXUNUSED(execData))
1114 {
1115 // nothing to do here, we don't use the pipe
1116 }
1117
1118 #endif // !Darwin/Darwin
1119
1120 int wxGUIAppTraits::WaitForChild(wxExecuteData& execData)
1121 {
1122 wxEndProcessData *endProcData = new wxEndProcessData;
1123
1124 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1125 // callback function directly if the process terminates before
1126 // the callback can be added to the run loop. Set up the endProcData.
1127 if ( execData.flags & wxEXEC_SYNC )
1128 {
1129 // we may have process for capturing the program output, but it's
1130 // not used in wxEndProcessData in the case of sync execution
1131 endProcData->process = NULL;
1132
1133 // sync execution: indicate it by negating the pid
1134 endProcData->pid = -execData.pid;
1135 }
1136 else
1137 {
1138 // async execution, nothing special to do -- caller will be
1139 // notified about the process termination if process != NULL, endProcData
1140 // will be deleted in GTK_EndProcessDetector
1141 endProcData->process = execData.process;
1142 endProcData->pid = execData.pid;
1143 }
1144
1145
1146 #if defined(__DARWIN__)
1147 endProcData->tag = wxAddProcessCallbackForPid(endProcData, execData.pid);
1148 #else
1149 endProcData->tag = wxAddProcessCallback
1150 (
1151 endProcData,
1152 execData.pipeEndProcDetect.Detach(wxPipe::Read)
1153 );
1154
1155 execData.pipeEndProcDetect.Close();
1156 #endif // defined(__DARWIN__)
1157
1158 if ( execData.flags & wxEXEC_SYNC )
1159 {
1160 wxBusyCursor bc;
1161 wxWindowDisabler wd;
1162
1163 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1164 // process terminates
1165 while ( endProcData->pid != 0 )
1166 {
1167 bool idle = true;
1168
1169 #if wxUSE_STREAMS
1170 if ( execData.bufOut )
1171 {
1172 execData.bufOut->Update();
1173 idle = false;
1174 }
1175
1176 if ( execData.bufErr )
1177 {
1178 execData.bufErr->Update();
1179 idle = false;
1180 }
1181 #endif // wxUSE_STREAMS
1182
1183 // don't consume 100% of the CPU while we're sitting in this
1184 // loop
1185 if ( idle )
1186 wxMilliSleep(1);
1187
1188 // give GTK+ a chance to call GTK_EndProcessDetector here and
1189 // also repaint the GUI
1190 wxYield();
1191 }
1192
1193 int exitcode = endProcData->exitcode;
1194
1195 delete endProcData;
1196
1197 return exitcode;
1198 }
1199 else // async execution
1200 {
1201 return execData.pid;
1202 }
1203 }
1204
1205 #endif // wxUSE_GUI
1206 #if wxUSE_BASE
1207
1208 void wxHandleProcessTermination(wxEndProcessData *proc_data)
1209 {
1210 // notify user about termination if required
1211 if ( proc_data->process )
1212 {
1213 proc_data->process->OnTerminate(proc_data->pid, proc_data->exitcode);
1214 }
1215
1216 // clean up
1217 if ( proc_data->pid > 0 )
1218 {
1219 delete proc_data;
1220 }
1221 else
1222 {
1223 // let wxExecute() know that the process has terminated
1224 proc_data->pid = 0;
1225 }
1226 }
1227
1228 #endif // wxUSE_BASE