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 // Used by wxGetFreeMemory().
129 #include <sys/sysmp.h>
130 #include <sys/sysinfo.h> // for SAGET and MINFO structures
133 // ----------------------------------------------------------------------------
134 // conditional compilation
135 // ----------------------------------------------------------------------------
137 // many versions of Unices have this function, but it is not defined in system
138 // headers - please add your system here if it is the case for your OS.
139 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
140 #if !defined(HAVE_USLEEP) && \
141 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
142 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
143 defined(__osf__) || defined(__EMX__))
147 int usleep(unsigned int usec
);
150 /* I copied this from the XFree86 diffs. AV. */
151 #define INCL_DOSPROCESS
153 inline void usleep(unsigned long delay
)
155 DosSleep(delay
? (delay
/1000l) : 1l);
157 #else // !Sun && !EMX
158 void usleep(unsigned long usec
);
160 #endif // Sun/EMX/Something else
163 #define HAVE_USLEEP 1
164 #endif // Unices without usleep()
166 // ============================================================================
168 // ============================================================================
170 // ----------------------------------------------------------------------------
172 // ----------------------------------------------------------------------------
174 void wxSleep(int nSecs
)
179 void wxMicroSleep(unsigned long microseconds
)
181 #if defined(HAVE_NANOSLEEP)
183 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
184 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
186 // we're not interested in remaining time nor in return value
187 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
188 #elif defined(HAVE_USLEEP)
189 // uncomment this if you feel brave or if you are sure that your version
190 // of Solaris has a safe usleep() function but please notice that usleep()
191 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
192 // documented as MT-Safe
193 #if defined(__SUN__) && wxUSE_THREADS
194 #error "usleep() cannot be used in MT programs under Solaris."
197 usleep(microseconds
);
198 #elif defined(HAVE_SLEEP)
199 // under BeOS sleep() takes seconds (what about other platforms, if any?)
200 sleep(microseconds
* 1000000);
201 #else // !sleep function
202 #error "usleep() or nanosleep() function required for wxMicroSleep"
203 #endif // sleep function
206 void wxMilliSleep(unsigned long milliseconds
)
208 wxMicroSleep(milliseconds
*1000);
211 // ----------------------------------------------------------------------------
212 // process management
213 // ----------------------------------------------------------------------------
215 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
217 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
220 switch ( err
? errno
: 0 )
227 *rc
= wxKILL_BAD_SIGNAL
;
231 *rc
= wxKILL_ACCESS_DENIED
;
235 *rc
= wxKILL_NO_PROCESS
;
239 // this goes against Unix98 docs so log it
240 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
250 #define WXEXECUTE_NARGS 127
252 #if defined(__DARWIN__)
253 long wxMacExecute(wxChar
**argv
,
258 long wxExecute( const wxString
& command
, int flags
, wxProcess
*process
)
260 wxCHECK_MSG( !command
.empty(), 0, wxT("can't exec empty command") );
261 wxLogDebug(wxString(wxT("Launching: ")) + command
);
264 // fork() doesn't mix well with POSIX threads: on many systems the program
265 // deadlocks or crashes for some reason. Probably our code is buggy and
266 // doesn't do something which must be done to allow this to work, but I
267 // don't know what yet, so for now just warn the user (this is the least we
269 wxASSERT_MSG( wxThread::IsMain(),
270 _T("wxExecute() can be called only from the main thread") );
271 #endif // wxUSE_THREADS
274 wxChar
*argv
[WXEXECUTE_NARGS
];
276 const wxChar
*cptr
= command
.c_str();
277 wxChar quotechar
= wxT('\0'); // is arg quoted?
278 bool escaped
= false;
280 // split the command line in arguments
284 quotechar
= wxT('\0');
286 // eat leading whitespace:
287 while ( wxIsspace(*cptr
) )
290 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
295 if ( *cptr
== wxT('\\') && ! escaped
)
302 // all other characters:
306 // have we reached the end of the argument?
307 if ( (*cptr
== quotechar
&& ! escaped
)
308 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
309 || *cptr
== wxT('\0') )
311 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
312 wxT("too many arguments in wxExecute") );
314 argv
[argc
] = new wxChar
[argument
.length() + 1];
315 wxStrcpy(argv
[argc
], argument
.c_str());
318 // if not at end of buffer, swallow last character:
322 break; // done with this one, start over
329 #if defined(__DARWIN__)
330 // wxMacExecute only executes app bundles.
331 // It returns an error code if the target is not an app bundle, thus falling
332 // through to the regular wxExecute for non app bundles.
333 lRc
= wxMacExecute(argv
, flags
, process
);
334 if( lRc
!= ((flags
& wxEXEC_SYNC
) ? -1 : 0))
338 // do execute the command
339 lRc
= wxExecute(argv
, flags
, process
);
344 delete [] argv
[argc
++];
349 // ----------------------------------------------------------------------------
351 // ----------------------------------------------------------------------------
353 static wxString
wxMakeShellCommand(const wxString
& command
)
358 // just an interactive shell
363 // execute command in a shell
364 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
370 bool wxShell(const wxString
& command
)
372 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
375 bool wxShell(const wxString
& command
, wxArrayString
& output
)
377 wxCHECK_MSG( !command
.empty(), false, _T("can't exec shell non interactively") );
379 return wxExecute(wxMakeShellCommand(command
), output
);
382 // Shutdown or reboot the PC
383 bool wxShutdown(wxShutdownFlags wFlags
)
388 case wxSHUTDOWN_POWEROFF
:
392 case wxSHUTDOWN_REBOOT
:
397 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
401 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
404 wxPowerType
wxGetPowerType()
407 return wxPOWER_UNKNOWN
;
410 wxBatteryState
wxGetBatteryState()
413 return wxBATTERY_UNKNOWN_STATE
;
416 // ----------------------------------------------------------------------------
417 // wxStream classes to support IO redirection in wxExecute
418 // ----------------------------------------------------------------------------
422 bool wxPipeInputStream::CanRead() const
424 if ( m_lasterror
== wxSTREAM_EOF
)
427 // check if there is any input available
432 const int fd
= m_file
->fd();
437 wxFD_SET(fd
, &readfds
);
439 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
442 wxLogSysError(_("Impossible to get child process input"));
449 wxFAIL_MSG(_T("unexpected select() return value"));
450 // still fall through
453 // input available -- or maybe not, as select() returns 1 when a
454 // read() will complete without delay, but it could still not read
460 #endif // wxUSE_STREAMS
462 // ----------------------------------------------------------------------------
463 // wxExecute: the real worker function
464 // ----------------------------------------------------------------------------
466 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*process
)
468 // for the sync execution, we return -1 to indicate failure, but for async
469 // case we return 0 which is never a valid PID
471 // we define this as a macro, not a variable, to avoid compiler warnings
472 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
473 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
475 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
479 char *mb_argv
[WXEXECUTE_NARGS
];
481 while (argv
[mb_argc
])
483 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
484 mb_argv
[mb_argc
] = strdup(mb_arg
);
487 mb_argv
[mb_argc
] = (char *) NULL
;
489 // this macro will free memory we used above
490 #define ARGS_CLEANUP \
491 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
492 free(mb_argv[mb_argc])
494 // no need for cleanup
497 wxChar
**mb_argv
= argv
;
498 #endif // Unicode/ANSI
500 // we want this function to work even if there is no wxApp so ensure that
501 // we have a valid traits pointer
502 wxConsoleAppTraits traitsConsole
;
503 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
505 traits
= &traitsConsole
;
507 // this struct contains all information which we pass to and from
508 // wxAppTraits methods
509 wxExecuteData execData
;
510 execData
.flags
= flags
;
511 execData
.process
= process
;
514 if ( !traits
->CreateEndProcessPipe(execData
) )
516 wxLogError( _("Failed to execute '%s'\n"), *argv
);
520 return ERROR_RETURN_CODE
;
523 // pipes for inter process communication
524 wxPipe pipeIn
, // stdin
528 if ( process
&& process
->IsRedirected() )
530 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
532 wxLogError( _("Failed to execute '%s'\n"), *argv
);
536 return ERROR_RETURN_CODE
;
542 // NB: do *not* use vfork() here, it completely breaks this code for some
543 // reason under Solaris (and maybe others, although not under Linux)
544 // But on OpenVMS we do not have fork so we have to use vfork and
545 // cross our fingers that it works.
551 if ( pid
== -1 ) // error?
553 wxLogSysError( _("Fork failed") );
557 return ERROR_RETURN_CODE
;
559 else if ( pid
== 0 ) // we're in child
561 // These lines close the open file descriptors to to avoid any
562 // input/output which might block the process or irritate the user. If
563 // one wants proper IO for the subprocess, the right thing to do is to
564 // start an xterm executing it.
565 if ( !(flags
& wxEXEC_SYNC
) )
567 // FD_SETSIZE is unsigned under BSD, signed under other platforms
568 // so we need a cast to avoid warnings on all platforms
569 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
571 if ( fd
== pipeIn
[wxPipe::Read
]
572 || fd
== pipeOut
[wxPipe::Write
]
573 || fd
== pipeErr
[wxPipe::Write
]
574 || traits
->IsWriteFDOfEndProcessPipe(execData
, fd
) )
576 // don't close this one, we still need it
580 // leave stderr opened too, it won't do any harm
581 if ( fd
!= STDERR_FILENO
)
586 #if !defined(__VMS) && !defined(__EMX__)
587 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
589 // Set process group to child process' pid. Then killing -pid
590 // of the parent will kill the process and all of its children.
595 // reading side can be safely closed but we should keep the write one
597 traits
->DetachWriteFDOfEndProcessPipe(execData
);
599 // redirect stdin, stdout and stderr
602 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
603 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
604 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
606 wxLogSysError(_("Failed to redirect child process input/output"));
614 execvp (*mb_argv
, mb_argv
);
616 fprintf(stderr
, "execvp(");
617 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
618 for ( char **ppc_
= mb_argv
; *ppc_
; ppc_
++ )
619 fprintf(stderr
, "%s%s", ppc_
== mb_argv
? "" : ", ", *ppc_
);
620 fprintf(stderr
, ") failed with error %d!\n", errno
);
622 // there is no return after successful exec()
625 // some compilers complain about missing return - of course, they
626 // should know that exit() doesn't return but what else can we do if
629 // and, sure enough, other compilers complain about unreachable code
630 // after exit() call, so we can just always have return here...
631 #if defined(__VMS) || defined(__INTEL_COMPILER)
635 else // we're in parent
639 // save it for WaitForChild() use
642 // prepare for IO redirection
645 // the input buffer bufOut is connected to stdout, this is why it is
646 // called bufOut and not bufIn
647 wxStreamTempInputBuffer bufOut
,
649 #endif // wxUSE_STREAMS
651 if ( process
&& process
->IsRedirected() )
654 wxOutputStream
*inStream
=
655 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
657 wxPipeInputStream
*outStream
=
658 new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
660 wxPipeInputStream
*errStream
=
661 new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
663 process
->SetPipeStreams(outStream
, inStream
, errStream
);
665 bufOut
.Init(outStream
);
666 bufErr
.Init(errStream
);
668 execData
.bufOut
= &bufOut
;
669 execData
.bufErr
= &bufErr
;
670 #endif // wxUSE_STREAMS
680 return traits
->WaitForChild(execData
);
683 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
684 return ERROR_RETURN_CODE
;
688 #undef ERROR_RETURN_CODE
691 // ----------------------------------------------------------------------------
692 // file and directory functions
693 // ----------------------------------------------------------------------------
695 const wxChar
* wxGetHomeDir( wxString
*home
)
697 *home
= wxGetUserHome( wxEmptyString
);
703 if ( tmp
.Last() != wxT(']'))
704 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
706 return home
->c_str();
710 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
711 #else // just for binary compatibility -- there is no 'const' here
712 char *wxGetUserHome( const wxString
&user
)
715 struct passwd
*who
= (struct passwd
*) NULL
;
721 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
724 wxWCharBuffer
buffer( ptr
);
730 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
732 who
= getpwnam(wxConvertWX2MB(ptr
));
735 // We now make sure the the user exists!
738 who
= getpwuid(getuid());
743 who
= getpwnam (user
.mb_str());
746 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
749 // ----------------------------------------------------------------------------
750 // network and user id routines
751 // ----------------------------------------------------------------------------
753 // retrieve either the hostname or FQDN depending on platform (caller must
754 // check whether it's one or the other, this is why this function is for
756 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
758 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
762 // we're using uname() which is POSIX instead of less standard sysinfo()
763 #if defined(HAVE_UNAME)
765 bool ok
= uname(&uts
) != -1;
768 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
771 #elif defined(HAVE_GETHOSTNAME)
772 bool ok
= gethostname(buf
, sz
) != -1;
773 #else // no uname, no gethostname
774 wxFAIL_MSG(wxT("don't know host name for this machine"));
777 #endif // uname/gethostname
781 wxLogSysError(_("Cannot get the hostname"));
787 bool wxGetHostName(wxChar
*buf
, int sz
)
789 bool ok
= wxGetHostNameInternal(buf
, sz
);
793 // BSD systems return the FQDN, we only want the hostname, so extract
794 // it (we consider that dots are domain separators)
795 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
806 bool wxGetFullHostName(wxChar
*buf
, int sz
)
808 bool ok
= wxGetHostNameInternal(buf
, sz
);
812 if ( !wxStrchr(buf
, wxT('.')) )
814 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
817 wxLogSysError(_("Cannot get the official hostname"));
823 // the canonical name
824 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
827 //else: it's already a FQDN (BSD behaves this way)
833 bool wxGetUserId(wxChar
*buf
, int sz
)
838 if ((who
= getpwuid(getuid ())) != NULL
)
840 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
847 bool wxGetUserName(wxChar
*buf
, int sz
)
852 if ((who
= getpwuid (getuid ())) != NULL
)
854 // pw_gecos field in struct passwd is not standard
856 char *comma
= strchr(who
->pw_gecos
, ',');
858 *comma
= '\0'; // cut off non-name comment fields
859 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
860 #else // !HAVE_PW_GECOS
861 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
862 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
869 // this function is in mac/utils.cpp for wxMac
872 wxString
wxGetOsDescription()
874 FILE *f
= popen("uname -s -r -m", "r");
878 size_t c
= fread(buf
, 1, sizeof(buf
) - 1, f
);
880 // Trim newline from output.
881 if (c
&& buf
[c
- 1] == '\n')
884 return wxString::FromAscii( buf
);
886 wxFAIL_MSG( _T("uname failed") );
892 unsigned long wxGetProcessId()
894 return (unsigned long)getpid();
897 wxMemorySize
wxGetFreeMemory()
899 #if defined(__LINUX__)
900 // get it from /proc/meminfo
901 FILE *fp
= fopen("/proc/meminfo", "r");
907 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
909 long memTotal
, memUsed
;
910 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
915 return (wxMemorySize
)memFree
;
917 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
918 return (wxMemorySize
)(sysconf(_SC_AVPHYS_PAGES
)*sysconf(_SC_PAGESIZE
));
919 #elif defined(__SGI__)
920 struct rminfo realmem
;
921 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
922 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
923 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
930 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
932 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
933 // the case to "char *" is needed for AIX 4.3
935 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
937 wxLogSysError( wxT("Failed to get file system statistics") );
942 // under Solaris we also have to use f_frsize field instead of f_bsize
943 // which is in general a multiple of f_frsize
945 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
947 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
948 #endif // HAVE_STATVFS/HAVE_STATFS
952 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
957 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
961 #else // !HAVE_STATFS && !HAVE_STATVFS
963 #endif // HAVE_STATFS
966 // ----------------------------------------------------------------------------
968 // ----------------------------------------------------------------------------
970 bool wxGetEnv(const wxString
& var
, wxString
*value
)
972 // wxGetenv is defined as getenv()
973 wxChar
*p
= wxGetenv(var
);
985 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
987 #if defined(HAVE_SETENV)
988 return setenv(variable
.mb_str(),
989 value
? (const char *)wxString(value
).mb_str()
991 1 /* overwrite */) == 0;
992 #elif defined(HAVE_PUTENV)
993 wxString s
= variable
;
995 s
<< _T('=') << value
;
998 const wxWX2MBbuf p
= s
.mb_str();
1000 // the string will be free()d by libc
1001 char *buf
= (char *)malloc(strlen(p
) + 1);
1004 return putenv(buf
) == 0;
1005 #else // no way to set an env var
1010 // ----------------------------------------------------------------------------
1012 // ----------------------------------------------------------------------------
1014 #if wxUSE_ON_FATAL_EXCEPTION
1018 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1022 // give the user a chance to do something special about this
1023 wxTheApp
->OnFatalException();
1029 bool wxHandleFatalExceptions(bool doit
)
1032 static bool s_savedHandlers
= false;
1033 static struct sigaction s_handlerFPE
,
1039 if ( doit
&& !s_savedHandlers
)
1041 // install the signal handler
1042 struct sigaction act
;
1044 // some systems extend it with non std fields, so zero everything
1045 memset(&act
, 0, sizeof(act
));
1047 act
.sa_handler
= wxFatalSignalHandler
;
1048 sigemptyset(&act
.sa_mask
);
1051 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1052 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1053 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1054 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1057 wxLogDebug(_T("Failed to install our signal handler."));
1060 s_savedHandlers
= true;
1062 else if ( s_savedHandlers
)
1064 // uninstall the signal handler
1065 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1066 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1067 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1068 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1071 wxLogDebug(_T("Failed to uninstall our signal handler."));
1074 s_savedHandlers
= false;
1076 //else: nothing to do
1081 #endif // wxUSE_ON_FATAL_EXCEPTION
1083 #endif // wxUSE_BASE
1087 // ----------------------------------------------------------------------------
1088 // wxExecute support
1089 // ----------------------------------------------------------------------------
1091 // Darwin doesn't use the same process end detection mechanisms so we don't
1092 // need wxExecute-related helpers for it
1093 #if !(defined(__DARWIN__) && defined(__WXMAC__))
1095 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& execData
)
1097 return execData
.pipeEndProcDetect
.Create();
1100 bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& execData
, int fd
)
1102 return fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
];
1105 void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& execData
)
1107 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
1108 execData
.pipeEndProcDetect
.Close();
1113 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1119 wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
),
1126 wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1128 // nothing to do here, we don't use the pipe
1131 #endif // !Darwin/Darwin
1133 int wxGUIAppTraits::WaitForChild(wxExecuteData
& execData
)
1135 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1137 const int flags
= execData
.flags
;
1139 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1140 // callback function directly if the process terminates before
1141 // the callback can be added to the run loop. Set up the endProcData.
1142 if ( flags
& wxEXEC_SYNC
)
1144 // we may have process for capturing the program output, but it's
1145 // not used in wxEndProcessData in the case of sync execution
1146 endProcData
->process
= NULL
;
1148 // sync execution: indicate it by negating the pid
1149 endProcData
->pid
= -execData
.pid
;
1153 // async execution, nothing special to do -- caller will be
1154 // notified about the process termination if process != NULL, endProcData
1155 // will be deleted in GTK_EndProcessDetector
1156 endProcData
->process
= execData
.process
;
1157 endProcData
->pid
= execData
.pid
;
1161 #if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1162 endProcData
->tag
= wxAddProcessCallbackForPid(endProcData
, execData
.pid
);
1164 endProcData
->tag
= wxAddProcessCallback
1167 execData
.pipeEndProcDetect
.Detach(wxPipe::Read
)
1170 execData
.pipeEndProcDetect
.Close();
1171 #endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1173 if ( flags
& wxEXEC_SYNC
)
1176 wxWindowDisabler
*wd
= flags
& wxEXEC_NODISABLE
? NULL
1177 : new wxWindowDisabler
;
1179 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1180 // process terminates
1181 while ( endProcData
->pid
!= 0 )
1186 if ( execData
.bufOut
)
1188 execData
.bufOut
->Update();
1192 if ( execData
.bufErr
)
1194 execData
.bufErr
->Update();
1197 #endif // wxUSE_STREAMS
1199 // don't consume 100% of the CPU while we're sitting in this
1204 // give GTK+ a chance to call GTK_EndProcessDetector here and
1205 // also repaint the GUI
1209 int exitcode
= endProcData
->exitcode
;
1216 else // async execution
1218 return execData
.pid
;
1225 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
1227 // notify user about termination if required
1228 if ( proc_data
->process
)
1230 proc_data
->process
->OnTerminate(proc_data
->pid
, proc_data
->exitcode
);
1234 if ( proc_data
->pid
> 0 )
1240 // let wxExecute() know that the process has terminated
1245 #endif // wxUSE_BASE