1 /////////////////////////////////////////////////////////////////////////////
2 // Name: unix/utilsunx.cpp
3 // Purpose: generic Unix implementation of many wx functions
4 // Author: Vadim Zeitlin
6 // Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 // ============================================================================
12 // ============================================================================
14 // ----------------------------------------------------------------------------
16 // ----------------------------------------------------------------------------
18 // for compilers that support precompilation, includes "wx.h".
19 #include "wx/wxprec.h"
22 #include "wx/string.h"
27 #include "wx/apptrait.h"
30 #include "wx/process.h"
31 #include "wx/thread.h"
33 #include "wx/wfstream.h"
35 #include "wx/unix/execute.h"
36 #include "wx/unix/private.h"
42 // define this to let wxexec.cpp know that we know what we're doing
43 #define _WX_USED_BY_WXEXECUTE_
44 #include "../common/execcmn.cpp"
46 #endif // wxUSE_STREAMS
50 #if defined(__MWERKS__) && defined(__MACH__)
51 #ifndef WXWIN_OS_DESCRIPTION
52 #define WXWIN_OS_DESCRIPTION "MacOS X"
54 #ifndef HAVE_NANOSLEEP
55 #define HAVE_NANOSLEEP
61 // our configure test believes we can use sigaction() if the function is
62 // available but Metrowekrs with MSL run-time does have the function but
63 // doesn't have sigaction struct so finally we can't use it...
65 #undef wxUSE_ON_FATAL_EXCEPTION
66 #define wxUSE_ON_FATAL_EXCEPTION 0
70 // not only the statfs syscall is called differently depending on platform, but
71 // one of its incarnations, statvfs(), takes different arguments under
72 // different platforms and even different versions of the same system (Solaris
73 // 7 and 8): if you want to test for this, don't forget that the problems only
74 // appear if the large files support is enabled
77 #include <sys/param.h>
78 #include <sys/mount.h>
81 #endif // __BSD__/!__BSD__
83 #define wxStatfs statfs
85 #ifndef HAVE_STATFS_DECL
86 // some systems lack statfs() prototype in the system headers (AIX 4)
87 extern "C" int statfs(const char *path
, struct statfs
*buf
);
92 #include <sys/statvfs.h>
94 #define wxStatfs statvfs
95 #endif // HAVE_STATVFS
97 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
98 // WX_STATFS_T is detected by configure
99 #define wxStatfs_t WX_STATFS_T
102 // SGI signal.h defines signal handler arguments differently depending on
103 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
104 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
105 #define _LANGUAGE_C_PLUS_PLUS 1
111 #include <sys/stat.h>
112 #include <sys/types.h>
113 #include <sys/wait.h>
118 #include <fcntl.h> // for O_WRONLY and friends
119 #include <time.h> // nanosleep() and/or usleep()
120 #include <ctype.h> // isspace()
121 #include <sys/time.h> // needed for FD_SETSIZE
124 #include <sys/utsname.h> // for uname()
127 // ----------------------------------------------------------------------------
128 // conditional compilation
129 // ----------------------------------------------------------------------------
131 // many versions of Unices have this function, but it is not defined in system
132 // headers - please add your system here if it is the case for your OS.
133 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
134 #if !defined(HAVE_USLEEP) && \
135 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
136 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
137 defined(__osf__) || defined(__EMX__))
141 int usleep(unsigned int usec
);
144 /* I copied this from the XFree86 diffs. AV. */
145 #define INCL_DOSPROCESS
147 inline void usleep(unsigned long delay
)
149 DosSleep(delay
? (delay
/1000l) : 1l);
151 #else // !Sun && !EMX
152 void usleep(unsigned long usec
);
154 #endif // Sun/EMX/Something else
157 #define HAVE_USLEEP 1
158 #endif // Unices without usleep()
160 // ============================================================================
162 // ============================================================================
164 // ----------------------------------------------------------------------------
166 // ----------------------------------------------------------------------------
168 void wxSleep(int nSecs
)
173 void wxMicroSleep(unsigned long microseconds
)
175 #if defined(HAVE_NANOSLEEP)
177 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
178 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
180 // we're not interested in remaining time nor in return value
181 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
182 #elif defined(HAVE_USLEEP)
183 // uncomment this if you feel brave or if you are sure that your version
184 // of Solaris has a safe usleep() function but please notice that usleep()
185 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
186 // documented as MT-Safe
187 #if defined(__SUN__) && wxUSE_THREADS
188 #error "usleep() cannot be used in MT programs under Solaris."
191 usleep(microseconds
);
192 #elif defined(HAVE_SLEEP)
193 // under BeOS sleep() takes seconds (what about other platforms, if any?)
194 sleep(microseconds
* 1000000);
195 #else // !sleep function
196 #error "usleep() or nanosleep() function required for wxMicroSleep"
197 #endif // sleep function
200 void wxMilliSleep(unsigned long milliseconds
)
202 wxMicroSleep(milliseconds
*1000);
205 // ----------------------------------------------------------------------------
206 // process management
207 // ----------------------------------------------------------------------------
209 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
211 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
214 switch ( err
? errno
: 0 )
221 *rc
= wxKILL_BAD_SIGNAL
;
225 *rc
= wxKILL_ACCESS_DENIED
;
229 *rc
= wxKILL_NO_PROCESS
;
233 // this goes against Unix98 docs so log it
234 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
244 #define WXEXECUTE_NARGS 127
246 #if defined(__DARWIN__)
247 long wxMacExecute(wxChar
**argv
,
252 long wxExecute( const wxString
& command
, int flags
, wxProcess
*process
)
254 wxCHECK_MSG( !command
.empty(), 0, wxT("can't exec empty command") );
255 wxLogDebug(wxString(wxT("Launching: ")) + command
);
258 // fork() doesn't mix well with POSIX threads: on many systems the program
259 // deadlocks or crashes for some reason. Probably our code is buggy and
260 // doesn't do something which must be done to allow this to work, but I
261 // don't know what yet, so for now just warn the user (this is the least we
263 wxASSERT_MSG( wxThread::IsMain(),
264 _T("wxExecute() can be called only from the main thread") );
265 #endif // wxUSE_THREADS
268 wxChar
*argv
[WXEXECUTE_NARGS
];
270 const wxChar
*cptr
= command
.c_str();
271 wxChar quotechar
= wxT('\0'); // is arg quoted?
272 bool escaped
= false;
274 // split the command line in arguments
278 quotechar
= wxT('\0');
280 // eat leading whitespace:
281 while ( wxIsspace(*cptr
) )
284 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
289 if ( *cptr
== wxT('\\') && ! escaped
)
296 // all other characters:
300 // have we reached the end of the argument?
301 if ( (*cptr
== quotechar
&& ! escaped
)
302 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
303 || *cptr
== wxT('\0') )
305 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
306 wxT("too many arguments in wxExecute") );
308 argv
[argc
] = new wxChar
[argument
.length() + 1];
309 wxStrcpy(argv
[argc
], argument
.c_str());
312 // if not at end of buffer, swallow last character:
316 break; // done with this one, start over
323 #if defined(__DARWIN__)
324 // wxMacExecute only executes app bundles.
325 // It returns an error code if the target is not an app bundle, thus falling
326 // through to the regular wxExecute for non app bundles.
327 lRc
= wxMacExecute(argv
, flags
, process
);
328 if( lRc
!= ((flags
& wxEXEC_SYNC
) ? -1 : 0))
332 // do execute the command
333 lRc
= wxExecute(argv
, flags
, process
);
338 delete [] argv
[argc
++];
343 // ----------------------------------------------------------------------------
345 // ----------------------------------------------------------------------------
347 static wxString
wxMakeShellCommand(const wxString
& command
)
352 // just an interactive shell
357 // execute command in a shell
358 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
364 bool wxShell(const wxString
& command
)
366 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
369 bool wxShell(const wxString
& command
, wxArrayString
& output
)
371 wxCHECK_MSG( !command
.empty(), false, _T("can't exec shell non interactively") );
373 return wxExecute(wxMakeShellCommand(command
), output
);
376 // Shutdown or reboot the PC
377 bool wxShutdown(wxShutdownFlags wFlags
)
382 case wxSHUTDOWN_POWEROFF
:
386 case wxSHUTDOWN_REBOOT
:
391 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
395 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
398 wxPowerType
wxGetPowerType()
401 return wxPOWER_UNKNOWN
;
404 wxBatteryState
wxGetBatteryState()
407 return wxBATTERY_UNKNOWN_STATE
;
410 // ----------------------------------------------------------------------------
411 // wxStream classes to support IO redirection in wxExecute
412 // ----------------------------------------------------------------------------
416 bool wxPipeInputStream::CanRead() const
418 if ( m_lasterror
== wxSTREAM_EOF
)
421 // check if there is any input available
426 const int fd
= m_file
->fd();
431 wxFD_SET(fd
, &readfds
);
433 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
436 wxLogSysError(_("Impossible to get child process input"));
443 wxFAIL_MSG(_T("unexpected select() return value"));
444 // still fall through
447 // input available -- or maybe not, as select() returns 1 when a
448 // read() will complete without delay, but it could still not read
454 #endif // wxUSE_STREAMS
456 // ----------------------------------------------------------------------------
457 // wxExecute: the real worker function
458 // ----------------------------------------------------------------------------
460 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*process
)
462 // for the sync execution, we return -1 to indicate failure, but for async
463 // case we return 0 which is never a valid PID
465 // we define this as a macro, not a variable, to avoid compiler warnings
466 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
467 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
469 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
473 char *mb_argv
[WXEXECUTE_NARGS
];
475 while (argv
[mb_argc
])
477 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
478 mb_argv
[mb_argc
] = strdup(mb_arg
);
481 mb_argv
[mb_argc
] = (char *) NULL
;
483 // this macro will free memory we used above
484 #define ARGS_CLEANUP \
485 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
486 free(mb_argv[mb_argc])
488 // no need for cleanup
491 wxChar
**mb_argv
= argv
;
492 #endif // Unicode/ANSI
494 // we want this function to work even if there is no wxApp so ensure that
495 // we have a valid traits pointer
496 wxConsoleAppTraits traitsConsole
;
497 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
499 traits
= &traitsConsole
;
501 // this struct contains all information which we pass to and from
502 // wxAppTraits methods
503 wxExecuteData execData
;
504 execData
.flags
= flags
;
505 execData
.process
= process
;
508 if ( !traits
->CreateEndProcessPipe(execData
) )
510 wxLogError( _("Failed to execute '%s'\n"), *argv
);
514 return ERROR_RETURN_CODE
;
517 // pipes for inter process communication
518 wxPipe pipeIn
, // stdin
522 if ( process
&& process
->IsRedirected() )
524 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
526 wxLogError( _("Failed to execute '%s'\n"), *argv
);
530 return ERROR_RETURN_CODE
;
536 // NB: do *not* use vfork() here, it completely breaks this code for some
537 // reason under Solaris (and maybe others, although not under Linux)
538 // But on OpenVMS we do not have fork so we have to use vfork and
539 // cross our fingers that it works.
545 if ( pid
== -1 ) // error?
547 wxLogSysError( _("Fork failed") );
551 return ERROR_RETURN_CODE
;
553 else if ( pid
== 0 ) // we're in child
555 // These lines close the open file descriptors to to avoid any
556 // input/output which might block the process or irritate the user. If
557 // one wants proper IO for the subprocess, the right thing to do is to
558 // start an xterm executing it.
559 if ( !(flags
& wxEXEC_SYNC
) )
561 // FD_SETSIZE is unsigned under BSD, signed under other platforms
562 // so we need a cast to avoid warnings on all platforms
563 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
565 if ( fd
== pipeIn
[wxPipe::Read
]
566 || fd
== pipeOut
[wxPipe::Write
]
567 || fd
== pipeErr
[wxPipe::Write
]
568 || traits
->IsWriteFDOfEndProcessPipe(execData
, fd
) )
570 // don't close this one, we still need it
574 // leave stderr opened too, it won't do any harm
575 if ( fd
!= STDERR_FILENO
)
580 #if !defined(__VMS) && !defined(__EMX__)
581 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
583 // Set process group to child process' pid. Then killing -pid
584 // of the parent will kill the process and all of its children.
589 // reading side can be safely closed but we should keep the write one
591 traits
->DetachWriteFDOfEndProcessPipe(execData
);
593 // redirect stdin, stdout and stderr
596 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
597 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
598 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
600 wxLogSysError(_("Failed to redirect child process input/output"));
608 execvp (*mb_argv
, mb_argv
);
610 fprintf(stderr
, "execvp(");
611 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
612 for ( char **ppc_
= mb_argv
; *ppc_
; ppc_
++ )
613 fprintf(stderr
, "%s%s", ppc_
== mb_argv
? "" : ", ", *ppc_
);
614 fprintf(stderr
, ") failed with error %d!\n", errno
);
616 // there is no return after successful exec()
619 // some compilers complain about missing return - of course, they
620 // should know that exit() doesn't return but what else can we do if
623 // and, sure enough, other compilers complain about unreachable code
624 // after exit() call, so we can just always have return here...
625 #if defined(__VMS) || defined(__INTEL_COMPILER)
629 else // we're in parent
633 // save it for WaitForChild() use
636 // prepare for IO redirection
639 // the input buffer bufOut is connected to stdout, this is why it is
640 // called bufOut and not bufIn
641 wxStreamTempInputBuffer bufOut
,
643 #endif // wxUSE_STREAMS
645 if ( process
&& process
->IsRedirected() )
648 wxOutputStream
*inStream
=
649 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
651 wxPipeInputStream
*outStream
=
652 new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
654 wxPipeInputStream
*errStream
=
655 new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
657 process
->SetPipeStreams(outStream
, inStream
, errStream
);
659 bufOut
.Init(outStream
);
660 bufErr
.Init(errStream
);
662 execData
.bufOut
= &bufOut
;
663 execData
.bufErr
= &bufErr
;
664 #endif // wxUSE_STREAMS
674 return traits
->WaitForChild(execData
);
677 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
678 return ERROR_RETURN_CODE
;
682 #undef ERROR_RETURN_CODE
685 // ----------------------------------------------------------------------------
686 // file and directory functions
687 // ----------------------------------------------------------------------------
689 const wxChar
* wxGetHomeDir( wxString
*home
)
691 *home
= wxGetUserHome( wxEmptyString
);
697 if ( tmp
.Last() != wxT(']'))
698 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
700 return home
->c_str();
704 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
705 #else // just for binary compatibility -- there is no 'const' here
706 char *wxGetUserHome( const wxString
&user
)
709 struct passwd
*who
= (struct passwd
*) NULL
;
715 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
718 wxWCharBuffer
buffer( ptr
);
724 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
726 who
= getpwnam(wxConvertWX2MB(ptr
));
729 // We now make sure the the user exists!
732 who
= getpwuid(getuid());
737 who
= getpwnam (user
.mb_str());
740 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
743 // ----------------------------------------------------------------------------
744 // network and user id routines
745 // ----------------------------------------------------------------------------
747 // retrieve either the hostname or FQDN depending on platform (caller must
748 // check whether it's one or the other, this is why this function is for
750 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
752 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
756 // we're using uname() which is POSIX instead of less standard sysinfo()
757 #if defined(HAVE_UNAME)
759 bool ok
= uname(&uts
) != -1;
762 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
765 #elif defined(HAVE_GETHOSTNAME)
766 bool ok
= gethostname(buf
, sz
) != -1;
767 #else // no uname, no gethostname
768 wxFAIL_MSG(wxT("don't know host name for this machine"));
771 #endif // uname/gethostname
775 wxLogSysError(_("Cannot get the hostname"));
781 bool wxGetHostName(wxChar
*buf
, int sz
)
783 bool ok
= wxGetHostNameInternal(buf
, sz
);
787 // BSD systems return the FQDN, we only want the hostname, so extract
788 // it (we consider that dots are domain separators)
789 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
800 bool wxGetFullHostName(wxChar
*buf
, int sz
)
802 bool ok
= wxGetHostNameInternal(buf
, sz
);
806 if ( !wxStrchr(buf
, wxT('.')) )
808 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
811 wxLogSysError(_("Cannot get the official hostname"));
817 // the canonical name
818 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
821 //else: it's already a FQDN (BSD behaves this way)
827 bool wxGetUserId(wxChar
*buf
, int sz
)
832 if ((who
= getpwuid(getuid ())) != NULL
)
834 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
841 bool wxGetUserName(wxChar
*buf
, int sz
)
846 if ((who
= getpwuid (getuid ())) != NULL
)
848 // pw_gecos field in struct passwd is not standard
850 char *comma
= strchr(who
->pw_gecos
, ',');
852 *comma
= '\0'; // cut off non-name comment fields
853 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
854 #else // !HAVE_PW_GECOS
855 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
856 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
863 // this function is in mac/utils.cpp for wxMac
866 wxString
wxGetOsDescription()
868 FILE *f
= popen("uname -s -r -m", "r");
872 size_t c
= fread(buf
, 1, sizeof(buf
) - 1, f
);
874 // Trim newline from output.
875 if (c
&& buf
[c
- 1] == '\n')
878 return wxString::FromAscii( buf
);
880 wxFAIL_MSG( _T("uname failed") );
886 unsigned long wxGetProcessId()
888 return (unsigned long)getpid();
891 wxMemorySize
wxGetFreeMemory()
893 #if defined(__LINUX__)
894 // get it from /proc/meminfo
895 FILE *fp
= fopen("/proc/meminfo", "r");
901 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
903 long memTotal
, memUsed
;
904 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
909 return (wxMemorySize
)memFree
;
911 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
912 return (wxMemorySize
)(sysconf(_SC_AVPHYS_PAGES
)*sysconf(_SC_PAGESIZE
));
913 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
920 bool wxGetDiskSpace(const wxString
& path
, wxLongLong
*pTotal
, wxLongLong
*pFree
)
922 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
923 // the case to "char *" is needed for AIX 4.3
925 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
927 wxLogSysError( wxT("Failed to get file system statistics") );
932 // under Solaris we also have to use f_frsize field instead of f_bsize
933 // which is in general a multiple of f_frsize
935 wxLongLong blockSize
= fs
.f_frsize
;
937 wxLongLong blockSize
= fs
.f_bsize
;
938 #endif // HAVE_STATVFS/HAVE_STATFS
942 *pTotal
= wxLongLong(fs
.f_blocks
) * blockSize
;
947 *pFree
= wxLongLong(fs
.f_bavail
) * blockSize
;
951 #else // !HAVE_STATFS && !HAVE_STATVFS
953 #endif // HAVE_STATFS
956 // ----------------------------------------------------------------------------
958 // ----------------------------------------------------------------------------
960 bool wxGetEnv(const wxString
& var
, wxString
*value
)
962 // wxGetenv is defined as getenv()
963 wxChar
*p
= wxGetenv(var
);
975 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
977 #if defined(HAVE_SETENV)
978 return setenv(variable
.mb_str(),
979 value
? (const char *)wxString(value
).mb_str()
981 1 /* overwrite */) == 0;
982 #elif defined(HAVE_PUTENV)
983 wxString s
= variable
;
985 s
<< _T('=') << value
;
988 const wxWX2MBbuf p
= s
.mb_str();
990 // the string will be free()d by libc
991 char *buf
= (char *)malloc(strlen(p
) + 1);
994 return putenv(buf
) == 0;
995 #else // no way to set an env var
1000 // ----------------------------------------------------------------------------
1002 // ----------------------------------------------------------------------------
1004 #if wxUSE_ON_FATAL_EXCEPTION
1008 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1012 // give the user a chance to do something special about this
1013 wxTheApp
->OnFatalException();
1019 bool wxHandleFatalExceptions(bool doit
)
1022 static bool s_savedHandlers
= false;
1023 static struct sigaction s_handlerFPE
,
1029 if ( doit
&& !s_savedHandlers
)
1031 // install the signal handler
1032 struct sigaction act
;
1034 // some systems extend it with non std fields, so zero everything
1035 memset(&act
, 0, sizeof(act
));
1037 act
.sa_handler
= wxFatalSignalHandler
;
1038 sigemptyset(&act
.sa_mask
);
1041 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1042 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1043 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1044 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1047 wxLogDebug(_T("Failed to install our signal handler."));
1050 s_savedHandlers
= true;
1052 else if ( s_savedHandlers
)
1054 // uninstall the signal handler
1055 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1056 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1057 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1058 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1061 wxLogDebug(_T("Failed to uninstall our signal handler."));
1064 s_savedHandlers
= false;
1066 //else: nothing to do
1071 #endif // wxUSE_ON_FATAL_EXCEPTION
1073 #endif // wxUSE_BASE
1077 // ----------------------------------------------------------------------------
1078 // wxExecute support
1079 // ----------------------------------------------------------------------------
1081 // Darwin doesn't use the same process end detection mechanisms so we don't
1082 // need wxExecute-related helpers for it
1083 #if !(defined(__DARWIN__) && defined(__WXMAC__))
1085 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& execData
)
1087 return execData
.pipeEndProcDetect
.Create();
1090 bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& execData
, int fd
)
1092 return fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
];
1095 void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& execData
)
1097 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
1098 execData
.pipeEndProcDetect
.Close();
1103 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1109 wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
),
1116 wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1118 // nothing to do here, we don't use the pipe
1121 #endif // !Darwin/Darwin
1123 int wxGUIAppTraits::WaitForChild(wxExecuteData
& execData
)
1125 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1127 const int flags
= execData
.flags
;
1129 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1130 // callback function directly if the process terminates before
1131 // the callback can be added to the run loop. Set up the endProcData.
1132 if ( flags
& wxEXEC_SYNC
)
1134 // we may have process for capturing the program output, but it's
1135 // not used in wxEndProcessData in the case of sync execution
1136 endProcData
->process
= NULL
;
1138 // sync execution: indicate it by negating the pid
1139 endProcData
->pid
= -execData
.pid
;
1143 // async execution, nothing special to do -- caller will be
1144 // notified about the process termination if process != NULL, endProcData
1145 // will be deleted in GTK_EndProcessDetector
1146 endProcData
->process
= execData
.process
;
1147 endProcData
->pid
= execData
.pid
;
1151 #if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1152 endProcData
->tag
= wxAddProcessCallbackForPid(endProcData
, execData
.pid
);
1154 endProcData
->tag
= wxAddProcessCallback
1157 execData
.pipeEndProcDetect
.Detach(wxPipe::Read
)
1160 execData
.pipeEndProcDetect
.Close();
1161 #endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1163 if ( flags
& wxEXEC_SYNC
)
1166 wxWindowDisabler
*wd
= flags
& wxEXEC_NODISABLE
? NULL
1167 : new wxWindowDisabler
;
1169 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1170 // process terminates
1171 while ( endProcData
->pid
!= 0 )
1176 if ( execData
.bufOut
)
1178 execData
.bufOut
->Update();
1182 if ( execData
.bufErr
)
1184 execData
.bufErr
->Update();
1187 #endif // wxUSE_STREAMS
1189 // don't consume 100% of the CPU while we're sitting in this
1194 // give GTK+ a chance to call GTK_EndProcessDetector here and
1195 // also repaint the GUI
1199 int exitcode
= endProcData
->exitcode
;
1206 else // async execution
1208 return execData
.pid
;
1215 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
1217 // notify user about termination if required
1218 if ( proc_data
->process
)
1220 proc_data
->process
->OnTerminate(proc_data
->pid
, proc_data
->exitcode
);
1224 if ( proc_data
->pid
> 0 )
1230 // let wxExecute() know that the process has terminated
1235 #endif // wxUSE_BASE