1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/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"
24 #include "wx/string.h"
30 #include "wx/apptrait.h"
32 #include "wx/process.h"
33 #include "wx/thread.h"
35 #include "wx/wfstream.h"
37 #include "wx/unix/execute.h"
38 #include "wx/unix/private.h"
44 // define this to let wxexec.cpp know that we know what we're doing
45 #define _WX_USED_BY_WXEXECUTE_
46 #include "../common/execcmn.cpp"
48 #endif // wxUSE_STREAMS
52 #if defined(__MWERKS__) && defined(__MACH__)
53 #ifndef WXWIN_OS_DESCRIPTION
54 #define WXWIN_OS_DESCRIPTION "MacOS X"
56 #ifndef HAVE_NANOSLEEP
57 #define HAVE_NANOSLEEP
63 // our configure test believes we can use sigaction() if the function is
64 // available but Metrowekrs with MSL run-time does have the function but
65 // doesn't have sigaction struct so finally we can't use it...
67 #undef wxUSE_ON_FATAL_EXCEPTION
68 #define wxUSE_ON_FATAL_EXCEPTION 0
72 // not only the statfs syscall is called differently depending on platform, but
73 // one of its incarnations, statvfs(), takes different arguments under
74 // different platforms and even different versions of the same system (Solaris
75 // 7 and 8): if you want to test for this, don't forget that the problems only
76 // appear if the large files support is enabled
79 #include <sys/param.h>
80 #include <sys/mount.h>
83 #endif // __BSD__/!__BSD__
85 #define wxStatfs statfs
87 #ifndef HAVE_STATFS_DECL
88 // some systems lack statfs() prototype in the system headers (AIX 4)
89 extern "C" int statfs(const char *path
, struct statfs
*buf
);
94 #include <sys/statvfs.h>
96 #define wxStatfs statvfs
97 #endif // HAVE_STATVFS
99 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
100 // WX_STATFS_T is detected by configure
101 #define wxStatfs_t WX_STATFS_T
104 // SGI signal.h defines signal handler arguments differently depending on
105 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
106 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
107 #define _LANGUAGE_C_PLUS_PLUS 1
113 #include <sys/stat.h>
114 #include <sys/types.h>
115 #include <sys/wait.h>
120 #include <fcntl.h> // for O_WRONLY and friends
121 #include <time.h> // nanosleep() and/or usleep()
122 #include <ctype.h> // isspace()
123 #include <sys/time.h> // needed for FD_SETSIZE
126 #include <sys/utsname.h> // for uname()
129 // Used by wxGetFreeMemory().
131 #include <sys/sysmp.h>
132 #include <sys/sysinfo.h> // for SAGET and MINFO structures
135 // ----------------------------------------------------------------------------
136 // conditional compilation
137 // ----------------------------------------------------------------------------
139 // many versions of Unices have this function, but it is not defined in system
140 // headers - please add your system here if it is the case for your OS.
141 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
142 #if !defined(HAVE_USLEEP) && \
143 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
144 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
145 defined(__osf__) || defined(__EMX__))
149 int usleep(unsigned int usec
);
152 /* I copied this from the XFree86 diffs. AV. */
153 #define INCL_DOSPROCESS
155 inline void usleep(unsigned long delay
)
157 DosSleep(delay
? (delay
/1000l) : 1l);
159 #else // !Sun && !EMX
160 void usleep(unsigned long usec
);
162 #endif // Sun/EMX/Something else
165 #define HAVE_USLEEP 1
166 #endif // Unices without usleep()
168 // ============================================================================
170 // ============================================================================
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
176 void wxSleep(int nSecs
)
181 void wxMicroSleep(unsigned long microseconds
)
183 #if defined(HAVE_NANOSLEEP)
185 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
186 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
188 // we're not interested in remaining time nor in return value
189 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
190 #elif defined(HAVE_USLEEP)
191 // uncomment this if you feel brave or if you are sure that your version
192 // of Solaris has a safe usleep() function but please notice that usleep()
193 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
194 // documented as MT-Safe
195 #if defined(__SUN__) && wxUSE_THREADS
196 #error "usleep() cannot be used in MT programs under Solaris."
199 usleep(microseconds
);
200 #elif defined(HAVE_SLEEP)
201 // under BeOS sleep() takes seconds (what about other platforms, if any?)
202 sleep(microseconds
* 1000000);
203 #else // !sleep function
204 #error "usleep() or nanosleep() function required for wxMicroSleep"
205 #endif // sleep function
208 void wxMilliSleep(unsigned long milliseconds
)
210 wxMicroSleep(milliseconds
*1000);
213 // ----------------------------------------------------------------------------
214 // process management
215 // ----------------------------------------------------------------------------
217 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
219 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
222 switch ( err
? errno
: 0 )
229 *rc
= wxKILL_BAD_SIGNAL
;
233 *rc
= wxKILL_ACCESS_DENIED
;
237 *rc
= wxKILL_NO_PROCESS
;
241 // this goes against Unix98 docs so log it
242 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
252 #define WXEXECUTE_NARGS 127
254 #if defined(__DARWIN__)
255 long wxMacExecute(wxChar
**argv
,
260 long wxExecute( const wxString
& command
, int flags
, wxProcess
*process
)
262 wxCHECK_MSG( !command
.empty(), 0, wxT("can't exec empty command") );
263 wxLogDebug(wxString(wxT("Launching: ")) + command
);
266 // fork() doesn't mix well with POSIX threads: on many systems the program
267 // deadlocks or crashes for some reason. Probably our code is buggy and
268 // doesn't do something which must be done to allow this to work, but I
269 // don't know what yet, so for now just warn the user (this is the least we
271 wxASSERT_MSG( wxThread::IsMain(),
272 _T("wxExecute() can be called only from the main thread") );
273 #endif // wxUSE_THREADS
276 wxChar
*argv
[WXEXECUTE_NARGS
];
278 const wxChar
*cptr
= command
.c_str();
279 wxChar quotechar
= wxT('\0'); // is arg quoted?
280 bool escaped
= false;
282 // split the command line in arguments
285 argument
= wxEmptyString
;
286 quotechar
= wxT('\0');
288 // eat leading whitespace:
289 while ( wxIsspace(*cptr
) )
292 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
297 if ( *cptr
== wxT('\\') && ! escaped
)
304 // all other characters:
308 // have we reached the end of the argument?
309 if ( (*cptr
== quotechar
&& ! escaped
)
310 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
311 || *cptr
== wxT('\0') )
313 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
314 wxT("too many arguments in wxExecute") );
316 argv
[argc
] = new wxChar
[argument
.length() + 1];
317 wxStrcpy(argv
[argc
], argument
.c_str());
320 // if not at end of buffer, swallow last character:
324 break; // done with this one, start over
331 #if defined(__DARWIN__)
332 // wxMacExecute only executes app bundles.
333 // It returns an error code if the target is not an app bundle, thus falling
334 // through to the regular wxExecute for non app bundles.
335 lRc
= wxMacExecute(argv
, flags
, process
);
336 if( lRc
!= ((flags
& wxEXEC_SYNC
) ? -1 : 0))
340 // do execute the command
341 lRc
= wxExecute(argv
, flags
, process
);
346 delete [] argv
[argc
++];
351 // ----------------------------------------------------------------------------
353 // ----------------------------------------------------------------------------
355 static wxString
wxMakeShellCommand(const wxString
& command
)
360 // just an interactive shell
365 // execute command in a shell
366 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
372 bool wxShell(const wxString
& command
)
374 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
377 bool wxShell(const wxString
& command
, wxArrayString
& output
)
379 wxCHECK_MSG( !command
.empty(), false, _T("can't exec shell non interactively") );
381 return wxExecute(wxMakeShellCommand(command
), output
);
384 // Shutdown or reboot the PC
385 bool wxShutdown(wxShutdownFlags wFlags
)
390 case wxSHUTDOWN_POWEROFF
:
394 case wxSHUTDOWN_REBOOT
:
399 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
403 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
406 wxPowerType
wxGetPowerType()
409 return wxPOWER_UNKNOWN
;
412 wxBatteryState
wxGetBatteryState()
415 return wxBATTERY_UNKNOWN_STATE
;
418 // ----------------------------------------------------------------------------
419 // wxStream classes to support IO redirection in wxExecute
420 // ----------------------------------------------------------------------------
424 bool wxPipeInputStream::CanRead() const
426 if ( m_lasterror
== wxSTREAM_EOF
)
429 // check if there is any input available
434 const int fd
= m_file
->fd();
439 wxFD_SET(fd
, &readfds
);
441 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
444 wxLogSysError(_("Impossible to get child process input"));
451 wxFAIL_MSG(_T("unexpected select() return value"));
452 // still fall through
455 // input available -- or maybe not, as select() returns 1 when a
456 // read() will complete without delay, but it could still not read
462 #endif // wxUSE_STREAMS
464 // ----------------------------------------------------------------------------
465 // wxExecute: the real worker function
466 // ----------------------------------------------------------------------------
468 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*process
)
470 // for the sync execution, we return -1 to indicate failure, but for async
471 // case we return 0 which is never a valid PID
473 // we define this as a macro, not a variable, to avoid compiler warnings
474 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
475 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
477 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
481 char *mb_argv
[WXEXECUTE_NARGS
];
483 while (argv
[mb_argc
])
485 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
486 mb_argv
[mb_argc
] = strdup(mb_arg
);
489 mb_argv
[mb_argc
] = (char *) NULL
;
491 // this macro will free memory we used above
492 #define ARGS_CLEANUP \
493 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
494 free(mb_argv[mb_argc])
496 // no need for cleanup
499 wxChar
**mb_argv
= argv
;
500 #endif // Unicode/ANSI
502 // we want this function to work even if there is no wxApp so ensure that
503 // we have a valid traits pointer
504 wxConsoleAppTraits traitsConsole
;
505 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
507 traits
= &traitsConsole
;
509 // this struct contains all information which we pass to and from
510 // wxAppTraits methods
511 wxExecuteData execData
;
512 execData
.flags
= flags
;
513 execData
.process
= process
;
516 if ( !traits
->CreateEndProcessPipe(execData
) )
518 wxLogError( _("Failed to execute '%s'\n"), *argv
);
522 return ERROR_RETURN_CODE
;
525 // pipes for inter process communication
526 wxPipe pipeIn
, // stdin
530 if ( process
&& process
->IsRedirected() )
532 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
534 wxLogError( _("Failed to execute '%s'\n"), *argv
);
538 return ERROR_RETURN_CODE
;
544 // NB: do *not* use vfork() here, it completely breaks this code for some
545 // reason under Solaris (and maybe others, although not under Linux)
546 // But on OpenVMS we do not have fork so we have to use vfork and
547 // cross our fingers that it works.
553 if ( pid
== -1 ) // error?
555 wxLogSysError( _("Fork failed") );
559 return ERROR_RETURN_CODE
;
561 else if ( pid
== 0 ) // we're in child
563 // These lines close the open file descriptors to to avoid any
564 // input/output which might block the process or irritate the user. If
565 // one wants proper IO for the subprocess, the right thing to do is to
566 // start an xterm executing it.
567 if ( !(flags
& wxEXEC_SYNC
) )
569 // FD_SETSIZE is unsigned under BSD, signed under other platforms
570 // so we need a cast to avoid warnings on all platforms
571 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
573 if ( fd
== pipeIn
[wxPipe::Read
]
574 || fd
== pipeOut
[wxPipe::Write
]
575 || fd
== pipeErr
[wxPipe::Write
]
576 || traits
->IsWriteFDOfEndProcessPipe(execData
, fd
) )
578 // don't close this one, we still need it
582 // leave stderr opened too, it won't do any harm
583 if ( fd
!= STDERR_FILENO
)
588 #if !defined(__VMS) && !defined(__EMX__)
589 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
591 // Set process group to child process' pid. Then killing -pid
592 // of the parent will kill the process and all of its children.
597 // reading side can be safely closed but we should keep the write one
599 traits
->DetachWriteFDOfEndProcessPipe(execData
);
601 // redirect stdin, stdout and stderr
604 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
605 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
606 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
608 wxLogSysError(_("Failed to redirect child process input/output"));
616 execvp (*mb_argv
, mb_argv
);
618 fprintf(stderr
, "execvp(");
619 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
620 for ( char **ppc_
= mb_argv
; *ppc_
; ppc_
++ )
621 fprintf(stderr
, "%s%s", ppc_
== mb_argv
? "" : ", ", *ppc_
);
622 fprintf(stderr
, ") failed with error %d!\n", errno
);
624 // there is no return after successful exec()
627 // some compilers complain about missing return - of course, they
628 // should know that exit() doesn't return but what else can we do if
631 // and, sure enough, other compilers complain about unreachable code
632 // after exit() call, so we can just always have return here...
633 #if defined(__VMS) || defined(__INTEL_COMPILER)
637 else // we're in parent
641 // save it for WaitForChild() use
644 // prepare for IO redirection
647 // the input buffer bufOut is connected to stdout, this is why it is
648 // called bufOut and not bufIn
649 wxStreamTempInputBuffer bufOut
,
651 #endif // wxUSE_STREAMS
653 if ( process
&& process
->IsRedirected() )
656 wxOutputStream
*inStream
=
657 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
659 wxPipeInputStream
*outStream
=
660 new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
662 wxPipeInputStream
*errStream
=
663 new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
665 process
->SetPipeStreams(outStream
, inStream
, errStream
);
667 bufOut
.Init(outStream
);
668 bufErr
.Init(errStream
);
670 execData
.bufOut
= &bufOut
;
671 execData
.bufErr
= &bufErr
;
672 #endif // wxUSE_STREAMS
682 return traits
->WaitForChild(execData
);
685 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
686 return ERROR_RETURN_CODE
;
690 #undef ERROR_RETURN_CODE
693 // ----------------------------------------------------------------------------
694 // file and directory functions
695 // ----------------------------------------------------------------------------
697 const wxChar
* wxGetHomeDir( wxString
*home
)
699 *home
= wxGetUserHome( wxEmptyString
);
705 if ( tmp
.Last() != wxT(']'))
706 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
708 return home
->c_str();
712 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
713 #else // just for binary compatibility -- there is no 'const' here
714 char *wxGetUserHome( const wxString
&user
)
717 struct passwd
*who
= (struct passwd
*) NULL
;
723 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
726 wxWCharBuffer
buffer( ptr
);
732 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
734 who
= getpwnam(wxConvertWX2MB(ptr
));
737 // We now make sure the the user exists!
740 who
= getpwuid(getuid());
745 who
= getpwnam (user
.mb_str());
748 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
751 // ----------------------------------------------------------------------------
752 // network and user id routines
753 // ----------------------------------------------------------------------------
755 // retrieve either the hostname or FQDN depending on platform (caller must
756 // check whether it's one or the other, this is why this function is for
758 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
760 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
764 // we're using uname() which is POSIX instead of less standard sysinfo()
765 #if defined(HAVE_UNAME)
767 bool ok
= uname(&uts
) != -1;
770 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
773 #elif defined(HAVE_GETHOSTNAME)
774 bool ok
= gethostname(buf
, sz
) != -1;
775 #else // no uname, no gethostname
776 wxFAIL_MSG(wxT("don't know host name for this machine"));
779 #endif // uname/gethostname
783 wxLogSysError(_("Cannot get the hostname"));
789 bool wxGetHostName(wxChar
*buf
, int sz
)
791 bool ok
= wxGetHostNameInternal(buf
, sz
);
795 // BSD systems return the FQDN, we only want the hostname, so extract
796 // it (we consider that dots are domain separators)
797 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
808 bool wxGetFullHostName(wxChar
*buf
, int sz
)
810 bool ok
= wxGetHostNameInternal(buf
, sz
);
814 if ( !wxStrchr(buf
, wxT('.')) )
816 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
819 wxLogSysError(_("Cannot get the official hostname"));
825 // the canonical name
826 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
829 //else: it's already a FQDN (BSD behaves this way)
835 bool wxGetUserId(wxChar
*buf
, int sz
)
840 if ((who
= getpwuid(getuid ())) != NULL
)
842 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
849 bool wxGetUserName(wxChar
*buf
, int sz
)
854 if ((who
= getpwuid (getuid ())) != NULL
)
856 // pw_gecos field in struct passwd is not standard
858 char *comma
= strchr(who
->pw_gecos
, ',');
860 *comma
= '\0'; // cut off non-name comment fields
861 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
862 #else // !HAVE_PW_GECOS
863 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
864 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
871 // this function is in mac/utils.cpp for wxMac
874 wxString
wxGetOsDescription()
876 FILE *f
= popen("uname -s -r -m", "r");
880 size_t c
= fread(buf
, 1, sizeof(buf
) - 1, f
);
882 // Trim newline from output.
883 if (c
&& buf
[c
- 1] == '\n')
886 return wxString::FromAscii( buf
);
888 wxFAIL_MSG( _T("uname failed") );
889 return wxEmptyString
;
894 unsigned long wxGetProcessId()
896 return (unsigned long)getpid();
899 wxMemorySize
wxGetFreeMemory()
901 #if defined(__LINUX__)
902 // get it from /proc/meminfo
903 FILE *fp
= fopen("/proc/meminfo", "r");
909 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
911 long memTotal
, memUsed
;
912 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
917 return (wxMemorySize
)memFree
;
919 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
920 return (wxMemorySize
)(sysconf(_SC_AVPHYS_PAGES
)*sysconf(_SC_PAGESIZE
));
921 #elif defined(__SGI__)
922 struct rminfo realmem
;
923 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
924 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
925 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
932 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
934 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
935 // the case to "char *" is needed for AIX 4.3
937 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
939 wxLogSysError( wxT("Failed to get file system statistics") );
944 // under Solaris we also have to use f_frsize field instead of f_bsize
945 // which is in general a multiple of f_frsize
947 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
949 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
950 #endif // HAVE_STATVFS/HAVE_STATFS
954 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
959 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
963 #else // !HAVE_STATFS && !HAVE_STATVFS
965 #endif // HAVE_STATFS
968 // ----------------------------------------------------------------------------
970 // ----------------------------------------------------------------------------
972 bool wxGetEnv(const wxString
& var
, wxString
*value
)
974 // wxGetenv is defined as getenv()
975 wxChar
*p
= wxGetenv(var
);
987 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
989 #if defined(HAVE_SETENV)
990 return setenv(variable
.mb_str(),
991 value
? (const char *)wxString(value
).mb_str()
993 1 /* overwrite */) == 0;
994 #elif defined(HAVE_PUTENV)
995 wxString s
= variable
;
997 s
<< _T('=') << value
;
1000 const wxWX2MBbuf p
= s
.mb_str();
1002 // the string will be free()d by libc
1003 char *buf
= (char *)malloc(strlen(p
) + 1);
1006 return putenv(buf
) == 0;
1007 #else // no way to set an env var
1012 // ----------------------------------------------------------------------------
1014 // ----------------------------------------------------------------------------
1016 #if wxUSE_ON_FATAL_EXCEPTION
1020 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1024 // give the user a chance to do something special about this
1025 wxTheApp
->OnFatalException();
1031 bool wxHandleFatalExceptions(bool doit
)
1034 static bool s_savedHandlers
= false;
1035 static struct sigaction s_handlerFPE
,
1041 if ( doit
&& !s_savedHandlers
)
1043 // install the signal handler
1044 struct sigaction act
;
1046 // some systems extend it with non std fields, so zero everything
1047 memset(&act
, 0, sizeof(act
));
1049 act
.sa_handler
= wxFatalSignalHandler
;
1050 sigemptyset(&act
.sa_mask
);
1053 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1054 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1055 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1056 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1059 wxLogDebug(_T("Failed to install our signal handler."));
1062 s_savedHandlers
= true;
1064 else if ( s_savedHandlers
)
1066 // uninstall the signal handler
1067 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1068 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1069 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1070 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1073 wxLogDebug(_T("Failed to uninstall our signal handler."));
1076 s_savedHandlers
= false;
1078 //else: nothing to do
1083 #endif // wxUSE_ON_FATAL_EXCEPTION
1085 #endif // wxUSE_BASE
1089 // ----------------------------------------------------------------------------
1090 // wxExecute support
1091 // ----------------------------------------------------------------------------
1093 // Darwin doesn't use the same process end detection mechanisms so we don't
1094 // need wxExecute-related helpers for it
1095 #if !(defined(__DARWIN__) && defined(__WXMAC__))
1097 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& execData
)
1099 return execData
.pipeEndProcDetect
.Create();
1102 bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& execData
, int fd
)
1104 return fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
];
1107 void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& execData
)
1109 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
1110 execData
.pipeEndProcDetect
.Close();
1115 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1121 wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
),
1128 wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1130 // nothing to do here, we don't use the pipe
1133 #endif // !Darwin/Darwin
1135 int wxGUIAppTraits::WaitForChild(wxExecuteData
& execData
)
1137 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1139 const int flags
= execData
.flags
;
1141 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1142 // callback function directly if the process terminates before
1143 // the callback can be added to the run loop. Set up the endProcData.
1144 if ( flags
& wxEXEC_SYNC
)
1146 // we may have process for capturing the program output, but it's
1147 // not used in wxEndProcessData in the case of sync execution
1148 endProcData
->process
= NULL
;
1150 // sync execution: indicate it by negating the pid
1151 endProcData
->pid
= -execData
.pid
;
1155 // async execution, nothing special to do -- caller will be
1156 // notified about the process termination if process != NULL, endProcData
1157 // will be deleted in GTK_EndProcessDetector
1158 endProcData
->process
= execData
.process
;
1159 endProcData
->pid
= execData
.pid
;
1163 #if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1164 endProcData
->tag
= wxAddProcessCallbackForPid(endProcData
, execData
.pid
);
1166 endProcData
->tag
= wxAddProcessCallback
1169 execData
.pipeEndProcDetect
.Detach(wxPipe::Read
)
1172 execData
.pipeEndProcDetect
.Close();
1173 #endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1175 if ( flags
& wxEXEC_SYNC
)
1178 wxWindowDisabler
*wd
= flags
& wxEXEC_NODISABLE
? NULL
1179 : new wxWindowDisabler
;
1181 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1182 // process terminates
1183 while ( endProcData
->pid
!= 0 )
1188 if ( execData
.bufOut
)
1190 execData
.bufOut
->Update();
1194 if ( execData
.bufErr
)
1196 execData
.bufErr
->Update();
1199 #endif // wxUSE_STREAMS
1201 // don't consume 100% of the CPU while we're sitting in this
1206 // give GTK+ a chance to call GTK_EndProcessDetector here and
1207 // also repaint the GUI
1211 int exitcode
= endProcData
->exitcode
;
1218 else // async execution
1220 return execData
.pid
;
1227 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
1229 // notify user about termination if required
1230 if ( proc_data
->process
)
1232 proc_data
->process
->OnTerminate(proc_data
->pid
, proc_data
->exitcode
);
1236 if ( proc_data
->pid
> 0 )
1242 // let wxExecute() know that the process has terminated
1247 #endif // wxUSE_BASE