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"
22 #include "wx/string.h"
28 #include "wx/apptrait.h"
31 #include "wx/process.h"
32 #include "wx/thread.h"
34 #include "wx/wfstream.h"
36 #include "wx/unix/execute.h"
37 #include "wx/unix/private.h"
43 // define this to let wxexec.cpp know that we know what we're doing
44 #define _WX_USED_BY_WXEXECUTE_
45 #include "../common/execcmn.cpp"
47 #endif // wxUSE_STREAMS
51 #if defined(__MWERKS__) && defined(__MACH__)
52 #ifndef WXWIN_OS_DESCRIPTION
53 #define WXWIN_OS_DESCRIPTION "MacOS X"
55 #ifndef HAVE_NANOSLEEP
56 #define HAVE_NANOSLEEP
62 // our configure test believes we can use sigaction() if the function is
63 // available but Metrowekrs with MSL run-time does have the function but
64 // doesn't have sigaction struct so finally we can't use it...
66 #undef wxUSE_ON_FATAL_EXCEPTION
67 #define wxUSE_ON_FATAL_EXCEPTION 0
71 // not only the statfs syscall is called differently depending on platform, but
72 // one of its incarnations, statvfs(), takes different arguments under
73 // different platforms and even different versions of the same system (Solaris
74 // 7 and 8): if you want to test for this, don't forget that the problems only
75 // appear if the large files support is enabled
78 #include <sys/param.h>
79 #include <sys/mount.h>
82 #endif // __BSD__/!__BSD__
84 #define wxStatfs statfs
86 #ifndef HAVE_STATFS_DECL
87 // some systems lack statfs() prototype in the system headers (AIX 4)
88 extern "C" int statfs(const char *path
, struct statfs
*buf
);
93 #include <sys/statvfs.h>
95 #define wxStatfs statvfs
96 #endif // HAVE_STATVFS
98 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
99 // WX_STATFS_T is detected by configure
100 #define wxStatfs_t WX_STATFS_T
103 // SGI signal.h defines signal handler arguments differently depending on
104 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
105 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
106 #define _LANGUAGE_C_PLUS_PLUS 1
112 #include <sys/stat.h>
113 #include <sys/types.h>
114 #include <sys/wait.h>
119 #include <fcntl.h> // for O_WRONLY and friends
120 #include <time.h> // nanosleep() and/or usleep()
121 #include <ctype.h> // isspace()
122 #include <sys/time.h> // needed for FD_SETSIZE
125 #include <sys/utsname.h> // for uname()
128 // Used by wxGetFreeMemory().
130 #include <sys/sysmp.h>
131 #include <sys/sysinfo.h> // for SAGET and MINFO structures
134 // ----------------------------------------------------------------------------
135 // conditional compilation
136 // ----------------------------------------------------------------------------
138 // many versions of Unices have this function, but it is not defined in system
139 // headers - please add your system here if it is the case for your OS.
140 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
141 #if !defined(HAVE_USLEEP) && \
142 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
143 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
144 defined(__osf__) || defined(__EMX__))
148 int usleep(unsigned int usec
);
151 /* I copied this from the XFree86 diffs. AV. */
152 #define INCL_DOSPROCESS
154 inline void usleep(unsigned long delay
)
156 DosSleep(delay
? (delay
/1000l) : 1l);
158 #else // !Sun && !EMX
159 void usleep(unsigned long usec
);
161 #endif // Sun/EMX/Something else
164 #define HAVE_USLEEP 1
165 #endif // Unices without usleep()
167 // ============================================================================
169 // ============================================================================
171 // ----------------------------------------------------------------------------
173 // ----------------------------------------------------------------------------
175 void wxSleep(int nSecs
)
180 void wxMicroSleep(unsigned long microseconds
)
182 #if defined(HAVE_NANOSLEEP)
184 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
185 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
187 // we're not interested in remaining time nor in return value
188 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
189 #elif defined(HAVE_USLEEP)
190 // uncomment this if you feel brave or if you are sure that your version
191 // of Solaris has a safe usleep() function but please notice that usleep()
192 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
193 // documented as MT-Safe
194 #if defined(__SUN__) && wxUSE_THREADS
195 #error "usleep() cannot be used in MT programs under Solaris."
198 usleep(microseconds
);
199 #elif defined(HAVE_SLEEP)
200 // under BeOS sleep() takes seconds (what about other platforms, if any?)
201 sleep(microseconds
* 1000000);
202 #else // !sleep function
203 #error "usleep() or nanosleep() function required for wxMicroSleep"
204 #endif // sleep function
207 void wxMilliSleep(unsigned long milliseconds
)
209 wxMicroSleep(milliseconds
*1000);
212 // ----------------------------------------------------------------------------
213 // process management
214 // ----------------------------------------------------------------------------
216 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
218 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
221 switch ( err
? errno
: 0 )
228 *rc
= wxKILL_BAD_SIGNAL
;
232 *rc
= wxKILL_ACCESS_DENIED
;
236 *rc
= wxKILL_NO_PROCESS
;
240 // this goes against Unix98 docs so log it
241 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
251 #define WXEXECUTE_NARGS 127
253 #if defined(__DARWIN__)
254 long wxMacExecute(wxChar
**argv
,
259 long wxExecute( const wxString
& command
, int flags
, wxProcess
*process
)
261 wxCHECK_MSG( !command
.empty(), 0, wxT("can't exec empty command") );
262 wxLogDebug(wxString(wxT("Launching: ")) + command
);
265 // fork() doesn't mix well with POSIX threads: on many systems the program
266 // deadlocks or crashes for some reason. Probably our code is buggy and
267 // doesn't do something which must be done to allow this to work, but I
268 // don't know what yet, so for now just warn the user (this is the least we
270 wxASSERT_MSG( wxThread::IsMain(),
271 _T("wxExecute() can be called only from the main thread") );
272 #endif // wxUSE_THREADS
275 wxChar
*argv
[WXEXECUTE_NARGS
];
277 const wxChar
*cptr
= command
.c_str();
278 wxChar quotechar
= wxT('\0'); // is arg quoted?
279 bool escaped
= false;
281 // split the command line in arguments
284 argument
= wxEmptyString
;
285 quotechar
= wxT('\0');
287 // eat leading whitespace:
288 while ( wxIsspace(*cptr
) )
291 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
296 if ( *cptr
== wxT('\\') && ! escaped
)
303 // all other characters:
307 // have we reached the end of the argument?
308 if ( (*cptr
== quotechar
&& ! escaped
)
309 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
310 || *cptr
== wxT('\0') )
312 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
313 wxT("too many arguments in wxExecute") );
315 argv
[argc
] = new wxChar
[argument
.length() + 1];
316 wxStrcpy(argv
[argc
], argument
.c_str());
319 // if not at end of buffer, swallow last character:
323 break; // done with this one, start over
330 #if defined(__DARWIN__)
331 // wxMacExecute only executes app bundles.
332 // It returns an error code if the target is not an app bundle, thus falling
333 // through to the regular wxExecute for non app bundles.
334 lRc
= wxMacExecute(argv
, flags
, process
);
335 if( lRc
!= ((flags
& wxEXEC_SYNC
) ? -1 : 0))
339 // do execute the command
340 lRc
= wxExecute(argv
, flags
, process
);
345 delete [] argv
[argc
++];
350 // ----------------------------------------------------------------------------
352 // ----------------------------------------------------------------------------
354 static wxString
wxMakeShellCommand(const wxString
& command
)
359 // just an interactive shell
364 // execute command in a shell
365 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
371 bool wxShell(const wxString
& command
)
373 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
376 bool wxShell(const wxString
& command
, wxArrayString
& output
)
378 wxCHECK_MSG( !command
.empty(), false, _T("can't exec shell non interactively") );
380 return wxExecute(wxMakeShellCommand(command
), output
);
383 // Shutdown or reboot the PC
384 bool wxShutdown(wxShutdownFlags wFlags
)
389 case wxSHUTDOWN_POWEROFF
:
393 case wxSHUTDOWN_REBOOT
:
398 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
402 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
405 wxPowerType
wxGetPowerType()
408 return wxPOWER_UNKNOWN
;
411 wxBatteryState
wxGetBatteryState()
414 return wxBATTERY_UNKNOWN_STATE
;
417 // ----------------------------------------------------------------------------
418 // wxStream classes to support IO redirection in wxExecute
419 // ----------------------------------------------------------------------------
423 bool wxPipeInputStream::CanRead() const
425 if ( m_lasterror
== wxSTREAM_EOF
)
428 // check if there is any input available
433 const int fd
= m_file
->fd();
438 wxFD_SET(fd
, &readfds
);
440 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
443 wxLogSysError(_("Impossible to get child process input"));
450 wxFAIL_MSG(_T("unexpected select() return value"));
451 // still fall through
454 // input available -- or maybe not, as select() returns 1 when a
455 // read() will complete without delay, but it could still not read
461 #endif // wxUSE_STREAMS
463 // ----------------------------------------------------------------------------
464 // wxExecute: the real worker function
465 // ----------------------------------------------------------------------------
467 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*process
)
469 // for the sync execution, we return -1 to indicate failure, but for async
470 // case we return 0 which is never a valid PID
472 // we define this as a macro, not a variable, to avoid compiler warnings
473 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
474 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
476 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
480 char *mb_argv
[WXEXECUTE_NARGS
];
482 while (argv
[mb_argc
])
484 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
485 mb_argv
[mb_argc
] = strdup(mb_arg
);
488 mb_argv
[mb_argc
] = (char *) NULL
;
490 // this macro will free memory we used above
491 #define ARGS_CLEANUP \
492 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
493 free(mb_argv[mb_argc])
495 // no need for cleanup
498 wxChar
**mb_argv
= argv
;
499 #endif // Unicode/ANSI
501 // we want this function to work even if there is no wxApp so ensure that
502 // we have a valid traits pointer
503 wxConsoleAppTraits traitsConsole
;
504 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
506 traits
= &traitsConsole
;
508 // this struct contains all information which we pass to and from
509 // wxAppTraits methods
510 wxExecuteData execData
;
511 execData
.flags
= flags
;
512 execData
.process
= process
;
515 if ( !traits
->CreateEndProcessPipe(execData
) )
517 wxLogError( _("Failed to execute '%s'\n"), *argv
);
521 return ERROR_RETURN_CODE
;
524 // pipes for inter process communication
525 wxPipe pipeIn
, // stdin
529 if ( process
&& process
->IsRedirected() )
531 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
533 wxLogError( _("Failed to execute '%s'\n"), *argv
);
537 return ERROR_RETURN_CODE
;
543 // NB: do *not* use vfork() here, it completely breaks this code for some
544 // reason under Solaris (and maybe others, although not under Linux)
545 // But on OpenVMS we do not have fork so we have to use vfork and
546 // cross our fingers that it works.
552 if ( pid
== -1 ) // error?
554 wxLogSysError( _("Fork failed") );
558 return ERROR_RETURN_CODE
;
560 else if ( pid
== 0 ) // we're in child
562 // These lines close the open file descriptors to to avoid any
563 // input/output which might block the process or irritate the user. If
564 // one wants proper IO for the subprocess, the right thing to do is to
565 // start an xterm executing it.
566 if ( !(flags
& wxEXEC_SYNC
) )
568 // FD_SETSIZE is unsigned under BSD, signed under other platforms
569 // so we need a cast to avoid warnings on all platforms
570 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
572 if ( fd
== pipeIn
[wxPipe::Read
]
573 || fd
== pipeOut
[wxPipe::Write
]
574 || fd
== pipeErr
[wxPipe::Write
]
575 || traits
->IsWriteFDOfEndProcessPipe(execData
, fd
) )
577 // don't close this one, we still need it
581 // leave stderr opened too, it won't do any harm
582 if ( fd
!= STDERR_FILENO
)
587 #if !defined(__VMS) && !defined(__EMX__)
588 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
590 // Set process group to child process' pid. Then killing -pid
591 // of the parent will kill the process and all of its children.
596 // reading side can be safely closed but we should keep the write one
598 traits
->DetachWriteFDOfEndProcessPipe(execData
);
600 // redirect stdin, stdout and stderr
603 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
604 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
605 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
607 wxLogSysError(_("Failed to redirect child process input/output"));
615 execvp (*mb_argv
, mb_argv
);
617 fprintf(stderr
, "execvp(");
618 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
619 for ( char **ppc_
= mb_argv
; *ppc_
; ppc_
++ )
620 fprintf(stderr
, "%s%s", ppc_
== mb_argv
? "" : ", ", *ppc_
);
621 fprintf(stderr
, ") failed with error %d!\n", errno
);
623 // there is no return after successful exec()
626 // some compilers complain about missing return - of course, they
627 // should know that exit() doesn't return but what else can we do if
630 // and, sure enough, other compilers complain about unreachable code
631 // after exit() call, so we can just always have return here...
632 #if defined(__VMS) || defined(__INTEL_COMPILER)
636 else // we're in parent
640 // save it for WaitForChild() use
643 // prepare for IO redirection
646 // the input buffer bufOut is connected to stdout, this is why it is
647 // called bufOut and not bufIn
648 wxStreamTempInputBuffer bufOut
,
650 #endif // wxUSE_STREAMS
652 if ( process
&& process
->IsRedirected() )
655 wxOutputStream
*inStream
=
656 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
658 wxPipeInputStream
*outStream
=
659 new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
661 wxPipeInputStream
*errStream
=
662 new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
664 process
->SetPipeStreams(outStream
, inStream
, errStream
);
666 bufOut
.Init(outStream
);
667 bufErr
.Init(errStream
);
669 execData
.bufOut
= &bufOut
;
670 execData
.bufErr
= &bufErr
;
671 #endif // wxUSE_STREAMS
681 return traits
->WaitForChild(execData
);
684 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
685 return ERROR_RETURN_CODE
;
689 #undef ERROR_RETURN_CODE
692 // ----------------------------------------------------------------------------
693 // file and directory functions
694 // ----------------------------------------------------------------------------
696 const wxChar
* wxGetHomeDir( wxString
*home
)
698 *home
= wxGetUserHome( wxEmptyString
);
704 if ( tmp
.Last() != wxT(']'))
705 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
707 return home
->c_str();
711 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
712 #else // just for binary compatibility -- there is no 'const' here
713 char *wxGetUserHome( const wxString
&user
)
716 struct passwd
*who
= (struct passwd
*) NULL
;
722 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
725 wxWCharBuffer
buffer( ptr
);
731 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
733 who
= getpwnam(wxConvertWX2MB(ptr
));
736 // We now make sure the the user exists!
739 who
= getpwuid(getuid());
744 who
= getpwnam (user
.mb_str());
747 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
750 // ----------------------------------------------------------------------------
751 // network and user id routines
752 // ----------------------------------------------------------------------------
754 // retrieve either the hostname or FQDN depending on platform (caller must
755 // check whether it's one or the other, this is why this function is for
757 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
759 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
763 // we're using uname() which is POSIX instead of less standard sysinfo()
764 #if defined(HAVE_UNAME)
766 bool ok
= uname(&uts
) != -1;
769 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
772 #elif defined(HAVE_GETHOSTNAME)
773 bool ok
= gethostname(buf
, sz
) != -1;
774 #else // no uname, no gethostname
775 wxFAIL_MSG(wxT("don't know host name for this machine"));
778 #endif // uname/gethostname
782 wxLogSysError(_("Cannot get the hostname"));
788 bool wxGetHostName(wxChar
*buf
, int sz
)
790 bool ok
= wxGetHostNameInternal(buf
, sz
);
794 // BSD systems return the FQDN, we only want the hostname, so extract
795 // it (we consider that dots are domain separators)
796 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
807 bool wxGetFullHostName(wxChar
*buf
, int sz
)
809 bool ok
= wxGetHostNameInternal(buf
, sz
);
813 if ( !wxStrchr(buf
, wxT('.')) )
815 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
818 wxLogSysError(_("Cannot get the official hostname"));
824 // the canonical name
825 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
828 //else: it's already a FQDN (BSD behaves this way)
834 bool wxGetUserId(wxChar
*buf
, int sz
)
839 if ((who
= getpwuid(getuid ())) != NULL
)
841 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
848 bool wxGetUserName(wxChar
*buf
, int sz
)
853 if ((who
= getpwuid (getuid ())) != NULL
)
855 // pw_gecos field in struct passwd is not standard
857 char *comma
= strchr(who
->pw_gecos
, ',');
859 *comma
= '\0'; // cut off non-name comment fields
860 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
861 #else // !HAVE_PW_GECOS
862 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
863 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
870 // this function is in mac/utils.cpp for wxMac
873 wxString
wxGetOsDescription()
875 FILE *f
= popen("uname -s -r -m", "r");
879 size_t c
= fread(buf
, 1, sizeof(buf
) - 1, f
);
881 // Trim newline from output.
882 if (c
&& buf
[c
- 1] == '\n')
885 return wxString::FromAscii( buf
);
887 wxFAIL_MSG( _T("uname failed") );
888 return wxEmptyString
;
893 unsigned long wxGetProcessId()
895 return (unsigned long)getpid();
898 wxMemorySize
wxGetFreeMemory()
900 #if defined(__LINUX__)
901 // get it from /proc/meminfo
902 FILE *fp
= fopen("/proc/meminfo", "r");
908 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
910 long memTotal
, memUsed
;
911 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
916 return (wxMemorySize
)memFree
;
918 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
919 return (wxMemorySize
)(sysconf(_SC_AVPHYS_PAGES
)*sysconf(_SC_PAGESIZE
));
920 #elif defined(__SGI__)
921 struct rminfo realmem
;
922 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
923 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
924 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
931 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
933 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
934 // the case to "char *" is needed for AIX 4.3
936 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
938 wxLogSysError( wxT("Failed to get file system statistics") );
943 // under Solaris we also have to use f_frsize field instead of f_bsize
944 // which is in general a multiple of f_frsize
946 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
948 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
949 #endif // HAVE_STATVFS/HAVE_STATFS
953 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
958 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
962 #else // !HAVE_STATFS && !HAVE_STATVFS
964 #endif // HAVE_STATFS
967 // ----------------------------------------------------------------------------
969 // ----------------------------------------------------------------------------
971 bool wxGetEnv(const wxString
& var
, wxString
*value
)
973 // wxGetenv is defined as getenv()
974 wxChar
*p
= wxGetenv(var
);
986 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
988 #if defined(HAVE_SETENV)
989 return setenv(variable
.mb_str(),
990 value
? (const char *)wxString(value
).mb_str()
992 1 /* overwrite */) == 0;
993 #elif defined(HAVE_PUTENV)
994 wxString s
= variable
;
996 s
<< _T('=') << value
;
999 const wxWX2MBbuf p
= s
.mb_str();
1001 // the string will be free()d by libc
1002 char *buf
= (char *)malloc(strlen(p
) + 1);
1005 return putenv(buf
) == 0;
1006 #else // no way to set an env var
1011 // ----------------------------------------------------------------------------
1013 // ----------------------------------------------------------------------------
1015 #if wxUSE_ON_FATAL_EXCEPTION
1019 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1023 // give the user a chance to do something special about this
1024 wxTheApp
->OnFatalException();
1030 bool wxHandleFatalExceptions(bool doit
)
1033 static bool s_savedHandlers
= false;
1034 static struct sigaction s_handlerFPE
,
1040 if ( doit
&& !s_savedHandlers
)
1042 // install the signal handler
1043 struct sigaction act
;
1045 // some systems extend it with non std fields, so zero everything
1046 memset(&act
, 0, sizeof(act
));
1048 act
.sa_handler
= wxFatalSignalHandler
;
1049 sigemptyset(&act
.sa_mask
);
1052 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1053 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1054 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1055 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1058 wxLogDebug(_T("Failed to install our signal handler."));
1061 s_savedHandlers
= true;
1063 else if ( s_savedHandlers
)
1065 // uninstall the signal handler
1066 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1067 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1068 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1069 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1072 wxLogDebug(_T("Failed to uninstall our signal handler."));
1075 s_savedHandlers
= false;
1077 //else: nothing to do
1082 #endif // wxUSE_ON_FATAL_EXCEPTION
1084 #endif // wxUSE_BASE
1088 // ----------------------------------------------------------------------------
1089 // wxExecute support
1090 // ----------------------------------------------------------------------------
1092 // Darwin doesn't use the same process end detection mechanisms so we don't
1093 // need wxExecute-related helpers for it
1094 #if !(defined(__DARWIN__) && defined(__WXMAC__))
1096 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& execData
)
1098 return execData
.pipeEndProcDetect
.Create();
1101 bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& execData
, int fd
)
1103 return fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
];
1106 void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& execData
)
1108 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
1109 execData
.pipeEndProcDetect
.Close();
1114 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1120 wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
),
1127 wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1129 // nothing to do here, we don't use the pipe
1132 #endif // !Darwin/Darwin
1134 int wxGUIAppTraits::WaitForChild(wxExecuteData
& execData
)
1136 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1138 const int flags
= execData
.flags
;
1140 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1141 // callback function directly if the process terminates before
1142 // the callback can be added to the run loop. Set up the endProcData.
1143 if ( flags
& wxEXEC_SYNC
)
1145 // we may have process for capturing the program output, but it's
1146 // not used in wxEndProcessData in the case of sync execution
1147 endProcData
->process
= NULL
;
1149 // sync execution: indicate it by negating the pid
1150 endProcData
->pid
= -execData
.pid
;
1154 // async execution, nothing special to do -- caller will be
1155 // notified about the process termination if process != NULL, endProcData
1156 // will be deleted in GTK_EndProcessDetector
1157 endProcData
->process
= execData
.process
;
1158 endProcData
->pid
= execData
.pid
;
1162 #if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1163 endProcData
->tag
= wxAddProcessCallbackForPid(endProcData
, execData
.pid
);
1165 endProcData
->tag
= wxAddProcessCallback
1168 execData
.pipeEndProcDetect
.Detach(wxPipe::Read
)
1171 execData
.pipeEndProcDetect
.Close();
1172 #endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1174 if ( flags
& wxEXEC_SYNC
)
1177 wxWindowDisabler
*wd
= flags
& wxEXEC_NODISABLE
? NULL
1178 : new wxWindowDisabler
;
1180 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1181 // process terminates
1182 while ( endProcData
->pid
!= 0 )
1187 if ( execData
.bufOut
)
1189 execData
.bufOut
->Update();
1193 if ( execData
.bufErr
)
1195 execData
.bufErr
->Update();
1198 #endif // wxUSE_STREAMS
1200 // don't consume 100% of the CPU while we're sitting in this
1205 // give GTK+ a chance to call GTK_EndProcessDetector here and
1206 // also repaint the GUI
1210 int exitcode
= endProcData
->exitcode
;
1217 else // async execution
1219 return execData
.pid
;
1226 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
1228 // notify user about termination if required
1229 if ( proc_data
->process
)
1231 proc_data
->process
->OnTerminate(proc_data
->pid
, proc_data
->exitcode
);
1235 if ( proc_data
->pid
> 0 )
1241 // let wxExecute() know that the process has terminated
1246 #endif // wxUSE_BASE