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 // ----------------------------------------------------------------------------
20 // for compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
24 #include "wx/string.h"
29 #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"
41 // define this to let wxexec.cpp know that we know what we're doing
42 #define _WX_USED_BY_WXEXECUTE_
43 #include "../common/execcmn.cpp"
45 #endif // wxUSE_STREAMS
49 #if defined(__MWERKS__) && defined(__MACH__)
50 #ifndef WXWIN_OS_DESCRIPTION
51 #define WXWIN_OS_DESCRIPTION "MacOS X"
53 #ifndef HAVE_NANOSLEEP
54 #define HAVE_NANOSLEEP
60 // our configure test believes we can use sigaction() if the function is
61 // available but Metrowekrs with MSL run-time does have the function but
62 // doesn't have sigaction struct so finally we can't use it...
64 #undef wxUSE_ON_FATAL_EXCEPTION
65 #define wxUSE_ON_FATAL_EXCEPTION 0
69 // not only the statfs syscall is called differently depending on platform, but
70 // one of its incarnations, statvfs(), takes different arguments under
71 // different platforms and even different versions of the same system (Solaris
72 // 7 and 8): if you want to test for this, don't forget that the problems only
73 // appear if the large files support is enabled
76 #include <sys/param.h>
77 #include <sys/mount.h>
80 #endif // __BSD__/!__BSD__
82 #define wxStatfs statfs
84 #ifndef HAVE_STATFS_DECL
85 // some systems lack statfs() prototype in the system headers (AIX 4)
86 extern "C" int statfs(const char *path
, struct statfs
*buf
);
91 #include <sys/statvfs.h>
93 #define wxStatfs statvfs
94 #endif // HAVE_STATVFS
96 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
97 // WX_STATFS_T is detected by configure
98 #define wxStatfs_t WX_STATFS_T
101 // SGI signal.h defines signal handler arguments differently depending on
102 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
103 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
104 #define _LANGUAGE_C_PLUS_PLUS 1
110 #include <sys/stat.h>
111 #include <sys/types.h>
112 #include <sys/wait.h>
117 #include <fcntl.h> // for O_WRONLY and friends
118 #include <time.h> // nanosleep() and/or usleep()
119 #include <ctype.h> // isspace()
120 #include <sys/time.h> // needed for FD_SETSIZE
123 #include <sys/utsname.h> // for uname()
126 // ----------------------------------------------------------------------------
127 // conditional compilation
128 // ----------------------------------------------------------------------------
130 // many versions of Unices have this function, but it is not defined in system
131 // headers - please add your system here if it is the case for your OS.
132 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
133 #if !defined(HAVE_USLEEP) && \
134 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
135 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
136 defined(__osf__) || defined(__EMX__))
140 int usleep(unsigned int usec
);
143 /* I copied this from the XFree86 diffs. AV. */
144 #define INCL_DOSPROCESS
146 inline void usleep(unsigned long delay
)
148 DosSleep(delay
? (delay
/1000l) : 1l);
150 #else // !Sun && !EMX
151 void usleep(unsigned long usec
);
153 #endif // Sun/EMX/Something else
156 #define HAVE_USLEEP 1
157 #endif // Unices without usleep()
159 // ============================================================================
161 // ============================================================================
163 // ----------------------------------------------------------------------------
165 // ----------------------------------------------------------------------------
167 void wxSleep(int nSecs
)
172 void wxMicroSleep(unsigned long microseconds
)
174 #if defined(HAVE_NANOSLEEP)
176 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
177 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
179 // we're not interested in remaining time nor in return value
180 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
181 #elif defined(HAVE_USLEEP)
182 // uncomment this if you feel brave or if you are sure that your version
183 // of Solaris has a safe usleep() function but please notice that usleep()
184 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
185 // documented as MT-Safe
186 #if defined(__SUN__) && wxUSE_THREADS
187 #error "usleep() cannot be used in MT programs under Solaris."
190 usleep(microseconds
);
191 #elif defined(HAVE_SLEEP)
192 // under BeOS sleep() takes seconds (what about other platforms, if any?)
193 sleep(microseconds
* 1000000);
194 #else // !sleep function
195 #error "usleep() or nanosleep() function required for wxMicroSleep"
196 #endif // sleep function
199 void wxMilliSleep(unsigned long milliseconds
)
201 wxMicroSleep(milliseconds
*1000);
204 // ----------------------------------------------------------------------------
205 // process management
206 // ----------------------------------------------------------------------------
208 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
210 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
213 switch ( err
? errno
: 0 )
220 *rc
= wxKILL_BAD_SIGNAL
;
224 *rc
= wxKILL_ACCESS_DENIED
;
228 *rc
= wxKILL_NO_PROCESS
;
232 // this goes against Unix98 docs so log it
233 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
243 #define WXEXECUTE_NARGS 127
245 #if defined(__DARWIN__)
246 long wxMacExecute(wxChar
**argv
,
251 long wxExecute( const wxString
& command
, int flags
, wxProcess
*process
)
253 wxCHECK_MSG( !command
.empty(), 0, wxT("can't exec empty command") );
254 wxLogDebug(wxString(wxT("Launching: ")) + command
);
257 // fork() doesn't mix well with POSIX threads: on many systems the program
258 // deadlocks or crashes for some reason. Probably our code is buggy and
259 // doesn't do something which must be done to allow this to work, but I
260 // don't know what yet, so for now just warn the user (this is the least we
262 wxASSERT_MSG( wxThread::IsMain(),
263 _T("wxExecute() can be called only from the main thread") );
264 #endif // wxUSE_THREADS
267 wxChar
*argv
[WXEXECUTE_NARGS
];
269 const wxChar
*cptr
= command
.c_str();
270 wxChar quotechar
= wxT('\0'); // is arg quoted?
271 bool escaped
= false;
273 // split the command line in arguments
277 quotechar
= wxT('\0');
279 // eat leading whitespace:
280 while ( wxIsspace(*cptr
) )
283 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
288 if ( *cptr
== wxT('\\') && ! escaped
)
295 // all other characters:
299 // have we reached the end of the argument?
300 if ( (*cptr
== quotechar
&& ! escaped
)
301 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
302 || *cptr
== wxT('\0') )
304 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
305 wxT("too many arguments in wxExecute") );
307 argv
[argc
] = new wxChar
[argument
.length() + 1];
308 wxStrcpy(argv
[argc
], argument
.c_str());
311 // if not at end of buffer, swallow last character:
315 break; // done with this one, start over
322 #if defined(__DARWIN__)
323 // wxMacExecute only executes app bundles.
324 // It returns an error code if the target is not an app bundle, thus falling
325 // through to the regular wxExecute for non app bundles.
326 lRc
= wxMacExecute(argv
, flags
, process
);
327 if( lRc
!= ((flags
& wxEXEC_SYNC
) ? -1 : 0))
331 // do execute the command
332 lRc
= wxExecute(argv
, flags
, process
);
337 delete [] argv
[argc
++];
342 // ----------------------------------------------------------------------------
344 // ----------------------------------------------------------------------------
346 static wxString
wxMakeShellCommand(const wxString
& command
)
351 // just an interactive shell
356 // execute command in a shell
357 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
363 bool wxShell(const wxString
& command
)
365 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
368 bool wxShell(const wxString
& command
, wxArrayString
& output
)
370 wxCHECK_MSG( !command
.empty(), false, _T("can't exec shell non interactively") );
372 return wxExecute(wxMakeShellCommand(command
), output
);
375 // Shutdown or reboot the PC
376 bool wxShutdown(wxShutdownFlags wFlags
)
381 case wxSHUTDOWN_POWEROFF
:
385 case wxSHUTDOWN_REBOOT
:
390 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
394 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
397 wxPowerType
wxGetPowerType()
400 return wxPOWER_UNKNOWN
;
403 wxBatteryState
wxGetBatteryState()
406 return wxBATTERY_UNKNOWN_STATE
;
409 // ----------------------------------------------------------------------------
410 // wxStream classes to support IO redirection in wxExecute
411 // ----------------------------------------------------------------------------
415 bool wxPipeInputStream::CanRead() const
417 if ( m_lasterror
== wxSTREAM_EOF
)
420 // check if there is any input available
425 const int fd
= m_file
->fd();
429 FD_SET(fd
, &readfds
);
430 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
433 wxLogSysError(_("Impossible to get child process input"));
440 wxFAIL_MSG(_T("unexpected select() return value"));
441 // still fall through
444 // input available -- or maybe not, as select() returns 1 when a
445 // read() will complete without delay, but it could still not read
451 #endif // wxUSE_STREAMS
453 // ----------------------------------------------------------------------------
454 // wxExecute: the real worker function
455 // ----------------------------------------------------------------------------
458 #pragma message disable codeunreachable
461 long wxExecute(wxChar
**argv
,
465 // for the sync execution, we return -1 to indicate failure, but for async
466 // case we return 0 which is never a valid PID
468 // we define this as a macro, not a variable, to avoid compiler warnings
469 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
470 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
472 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
476 char *mb_argv
[WXEXECUTE_NARGS
];
478 while (argv
[mb_argc
])
480 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
481 mb_argv
[mb_argc
] = strdup(mb_arg
);
484 mb_argv
[mb_argc
] = (char *) NULL
;
486 // this macro will free memory we used above
487 #define ARGS_CLEANUP \
488 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
489 free(mb_argv[mb_argc])
491 // no need for cleanup
494 wxChar
**mb_argv
= argv
;
495 #endif // Unicode/ANSI
497 // we want this function to work even if there is no wxApp so ensure that
498 // we have a valid traits pointer
499 wxConsoleAppTraits traitsConsole
;
500 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
502 traits
= &traitsConsole
;
504 // this struct contains all information which we pass to and from
505 // wxAppTraits methods
506 wxExecuteData execData
;
507 execData
.flags
= flags
;
508 execData
.process
= process
;
511 if ( !traits
->CreateEndProcessPipe(execData
) )
513 wxLogError( _("Failed to execute '%s'\n"), *argv
);
517 return ERROR_RETURN_CODE
;
520 // pipes for inter process communication
521 wxPipe pipeIn
, // stdin
525 if ( process
&& process
->IsRedirected() )
527 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
529 wxLogError( _("Failed to execute '%s'\n"), *argv
);
533 return ERROR_RETURN_CODE
;
539 // NB: do *not* use vfork() here, it completely breaks this code for some
540 // reason under Solaris (and maybe others, although not under Linux)
541 // But on OpenVMS we do not have fork so we have to use vfork and
542 // cross our fingers that it works.
548 if ( pid
== -1 ) // error?
550 wxLogSysError( _("Fork failed") );
554 return ERROR_RETURN_CODE
;
556 else if ( pid
== 0 ) // we're in child
558 // These lines close the open file descriptors to to avoid any
559 // input/output which might block the process or irritate the user. If
560 // one wants proper IO for the subprocess, the right thing to do is to
561 // start an xterm executing it.
562 if ( !(flags
& wxEXEC_SYNC
) )
564 // FD_SETSIZE is unsigned under BSD, signed under other platforms
565 // so we need a cast to avoid warnings on all platforms
566 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
568 if ( fd
== pipeIn
[wxPipe::Read
]
569 || fd
== pipeOut
[wxPipe::Write
]
570 || fd
== pipeErr
[wxPipe::Write
]
571 || traits
->IsWriteFDOfEndProcessPipe(execData
, fd
) )
573 // don't close this one, we still need it
577 // leave stderr opened too, it won't do any harm
578 if ( fd
!= STDERR_FILENO
)
583 #if !defined(__VMS) && !defined(__EMX__)
584 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
586 // Set process group to child process' pid. Then killing -pid
587 // of the parent will kill the process and all of its children.
592 // reading side can be safely closed but we should keep the write one
594 traits
->DetachWriteFDOfEndProcessPipe(execData
);
596 // redirect stdin, stdout and stderr
599 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
600 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
601 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
603 wxLogSysError(_("Failed to redirect child process input/output"));
611 execvp (*mb_argv
, mb_argv
);
613 fprintf(stderr
, "execvp(");
614 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
615 for ( char **ppc_
= mb_argv
; *ppc_
; ppc_
++ )
616 fprintf(stderr
, "%s%s", ppc_
== mb_argv
? "" : ", ", *ppc_
);
617 fprintf(stderr
, ") failed with error %d!\n", errno
);
619 // there is no return after successful exec()
622 // some compilers complain about missing return - of course, they
623 // should know that exit() doesn't return but what else can we do if
626 // and, sure enough, other compilers complain about unreachable code
627 // after exit() call, so we can just always have return here...
628 #if defined(__VMS) || defined(__INTEL_COMPILER)
632 else // we're in parent
636 // save it for WaitForChild() use
639 // prepare for IO redirection
642 // the input buffer bufOut is connected to stdout, this is why it is
643 // called bufOut and not bufIn
644 wxStreamTempInputBuffer bufOut
,
646 #endif // wxUSE_STREAMS
648 if ( process
&& process
->IsRedirected() )
651 wxOutputStream
*inStream
=
652 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
654 wxPipeInputStream
*outStream
=
655 new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
657 wxPipeInputStream
*errStream
=
658 new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
660 process
->SetPipeStreams(outStream
, inStream
, errStream
);
662 bufOut
.Init(outStream
);
663 bufErr
.Init(errStream
);
665 execData
.bufOut
= &bufOut
;
666 execData
.bufErr
= &bufErr
;
667 #endif // wxUSE_STREAMS
677 return traits
->WaitForChild(execData
);
680 return ERROR_RETURN_CODE
;
684 #pragma message enable codeunreachable
687 #undef ERROR_RETURN_CODE
690 // ----------------------------------------------------------------------------
691 // file and directory functions
692 // ----------------------------------------------------------------------------
694 const wxChar
* wxGetHomeDir( wxString
*home
)
696 *home
= wxGetUserHome( wxEmptyString
);
702 if ( tmp
.Last() != wxT(']'))
703 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
705 return home
->c_str();
709 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
710 #else // just for binary compatibility -- there is no 'const' here
711 char *wxGetUserHome( const wxString
&user
)
714 struct passwd
*who
= (struct passwd
*) NULL
;
720 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
723 wxWCharBuffer
buffer( ptr
);
729 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
731 who
= getpwnam(wxConvertWX2MB(ptr
));
734 // We now make sure the the user exists!
737 who
= getpwuid(getuid());
742 who
= getpwnam (user
.mb_str());
745 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
748 // ----------------------------------------------------------------------------
749 // network and user id routines
750 // ----------------------------------------------------------------------------
752 // retrieve either the hostname or FQDN depending on platform (caller must
753 // check whether it's one or the other, this is why this function is for
755 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
757 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
761 // we're using uname() which is POSIX instead of less standard sysinfo()
762 #if defined(HAVE_UNAME)
764 bool ok
= uname(&uts
) != -1;
767 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
770 #elif defined(HAVE_GETHOSTNAME)
771 bool ok
= gethostname(buf
, sz
) != -1;
772 #else // no uname, no gethostname
773 wxFAIL_MSG(wxT("don't know host name for this machine"));
776 #endif // uname/gethostname
780 wxLogSysError(_("Cannot get the hostname"));
786 bool wxGetHostName(wxChar
*buf
, int sz
)
788 bool ok
= wxGetHostNameInternal(buf
, sz
);
792 // BSD systems return the FQDN, we only want the hostname, so extract
793 // it (we consider that dots are domain separators)
794 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
805 bool wxGetFullHostName(wxChar
*buf
, int sz
)
807 bool ok
= wxGetHostNameInternal(buf
, sz
);
811 if ( !wxStrchr(buf
, wxT('.')) )
813 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
816 wxLogSysError(_("Cannot get the official hostname"));
822 // the canonical name
823 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
826 //else: it's already a FQDN (BSD behaves this way)
832 bool wxGetUserId(wxChar
*buf
, int sz
)
837 if ((who
= getpwuid(getuid ())) != NULL
)
839 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
846 bool wxGetUserName(wxChar
*buf
, int sz
)
851 if ((who
= getpwuid (getuid ())) != NULL
)
853 // pw_gecos field in struct passwd is not standard
855 char *comma
= strchr(who
->pw_gecos
, ',');
857 *comma
= '\0'; // cut off non-name comment fields
858 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
859 #else // !HAVE_PW_GECOS
860 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
861 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
868 // this function is in mac/utils.cpp for wxMac
871 wxString
wxGetOsDescription()
873 FILE *f
= popen("uname -s -r -m", "r");
877 size_t c
= fread(buf
, 1, sizeof(buf
) - 1, f
);
879 // Trim newline from output.
880 if (c
&& buf
[c
- 1] == '\n')
883 return wxString::FromAscii( buf
);
885 wxFAIL_MSG( _T("uname failed") );
891 unsigned long wxGetProcessId()
893 return (unsigned long)getpid();
896 wxMemorySize
wxGetFreeMemory()
898 #if defined(__LINUX__)
899 // get it from /proc/meminfo
900 FILE *fp
= fopen("/proc/meminfo", "r");
906 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
908 long memTotal
, memUsed
;
909 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
914 return (wxMemorySize
)memFree
;
916 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
917 return (wxMemorySize
)(sysconf(_SC_AVPHYS_PAGES
)*sysconf(_SC_PAGESIZE
));
918 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
925 bool wxGetDiskSpace(const wxString
& path
, wxLongLong
*pTotal
, wxLongLong
*pFree
)
927 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
928 // the case to "char *" is needed for AIX 4.3
930 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
932 wxLogSysError( wxT("Failed to get file system statistics") );
937 // under Solaris we also have to use f_frsize field instead of f_bsize
938 // which is in general a multiple of f_frsize
940 wxLongLong blockSize
= fs
.f_frsize
;
942 wxLongLong blockSize
= fs
.f_bsize
;
943 #endif // HAVE_STATVFS/HAVE_STATFS
947 *pTotal
= wxLongLong(fs
.f_blocks
) * blockSize
;
952 *pFree
= wxLongLong(fs
.f_bavail
) * blockSize
;
956 #else // !HAVE_STATFS && !HAVE_STATVFS
958 #endif // HAVE_STATFS
961 // ----------------------------------------------------------------------------
963 // ----------------------------------------------------------------------------
965 bool wxGetEnv(const wxString
& var
, wxString
*value
)
967 // wxGetenv is defined as getenv()
968 wxChar
*p
= wxGetenv(var
);
980 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
982 #if defined(HAVE_SETENV)
983 return setenv(variable
.mb_str(),
984 value
? (const char *)wxString(value
).mb_str()
986 1 /* overwrite */) == 0;
987 #elif defined(HAVE_PUTENV)
988 wxString s
= variable
;
990 s
<< _T('=') << value
;
993 const wxWX2MBbuf p
= s
.mb_str();
995 // the string will be free()d by libc
996 char *buf
= (char *)malloc(strlen(p
) + 1);
999 return putenv(buf
) == 0;
1000 #else // no way to set an env var
1005 // ----------------------------------------------------------------------------
1007 // ----------------------------------------------------------------------------
1009 #if wxUSE_ON_FATAL_EXCEPTION
1013 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1017 // give the user a chance to do something special about this
1018 wxTheApp
->OnFatalException();
1024 bool wxHandleFatalExceptions(bool doit
)
1027 static bool s_savedHandlers
= false;
1028 static struct sigaction s_handlerFPE
,
1034 if ( doit
&& !s_savedHandlers
)
1036 // install the signal handler
1037 struct sigaction act
;
1039 // some systems extend it with non std fields, so zero everything
1040 memset(&act
, 0, sizeof(act
));
1042 act
.sa_handler
= wxFatalSignalHandler
;
1043 sigemptyset(&act
.sa_mask
);
1046 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1047 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1048 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1049 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1052 wxLogDebug(_T("Failed to install our signal handler."));
1055 s_savedHandlers
= true;
1057 else if ( s_savedHandlers
)
1059 // uninstall the signal handler
1060 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1061 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1062 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1063 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1066 wxLogDebug(_T("Failed to uninstall our signal handler."));
1069 s_savedHandlers
= false;
1071 //else: nothing to do
1076 #endif // wxUSE_ON_FATAL_EXCEPTION
1078 // ----------------------------------------------------------------------------
1079 // error and debug output routines (deprecated, use wxLog)
1080 // ----------------------------------------------------------------------------
1082 #if WXWIN_COMPATIBILITY_2_2
1084 void wxDebugMsg( const char *format
, ... )
1087 va_start( ap
, format
);
1088 vfprintf( stderr
, format
, ap
);
1093 void wxError( const wxString
&msg
, const wxString
&title
)
1095 wxFprintf( stderr
, _("Error ") );
1096 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
1097 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
1098 wxFprintf( stderr
, wxT(".\n") );
1101 void wxFatalError( const wxString
&msg
, const wxString
&title
)
1103 wxFprintf( stderr
, _("Error ") );
1104 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
1105 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
1106 wxFprintf( stderr
, wxT(".\n") );
1107 exit(3); // the same exit code as for abort()
1110 #endif // WXWIN_COMPATIBILITY_2_2
1112 #endif // wxUSE_BASE
1116 // ----------------------------------------------------------------------------
1117 // wxExecute support
1118 // ----------------------------------------------------------------------------
1120 // Darwin doesn't use the same process end detection mechanisms so we don't
1121 // need wxExecute-related helpers for it
1122 #if !(defined(__DARWIN__) && defined(__WXMAC__))
1124 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& execData
)
1126 return execData
.pipeEndProcDetect
.Create();
1129 bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& execData
, int fd
)
1131 return fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
];
1134 void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& execData
)
1136 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
1137 execData
.pipeEndProcDetect
.Close();
1142 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1148 wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
),
1155 wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1157 // nothing to do here, we don't use the pipe
1160 #endif // !Darwin/Darwin
1162 int wxGUIAppTraits::WaitForChild(wxExecuteData
& execData
)
1164 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1166 const int flags
= execData
.flags
;
1168 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1169 // callback function directly if the process terminates before
1170 // the callback can be added to the run loop. Set up the endProcData.
1171 if ( flags
& wxEXEC_SYNC
)
1173 // we may have process for capturing the program output, but it's
1174 // not used in wxEndProcessData in the case of sync execution
1175 endProcData
->process
= NULL
;
1177 // sync execution: indicate it by negating the pid
1178 endProcData
->pid
= -execData
.pid
;
1182 // async execution, nothing special to do -- caller will be
1183 // notified about the process termination if process != NULL, endProcData
1184 // will be deleted in GTK_EndProcessDetector
1185 endProcData
->process
= execData
.process
;
1186 endProcData
->pid
= execData
.pid
;
1190 #if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1191 endProcData
->tag
= wxAddProcessCallbackForPid(endProcData
, execData
.pid
);
1193 endProcData
->tag
= wxAddProcessCallback
1196 execData
.pipeEndProcDetect
.Detach(wxPipe::Read
)
1199 execData
.pipeEndProcDetect
.Close();
1200 #endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1202 if ( flags
& wxEXEC_SYNC
)
1205 wxWindowDisabler
*wd
= flags
& wxEXEC_NODISABLE
? NULL
1206 : new wxWindowDisabler
;
1208 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1209 // process terminates
1210 while ( endProcData
->pid
!= 0 )
1215 if ( execData
.bufOut
)
1217 execData
.bufOut
->Update();
1221 if ( execData
.bufErr
)
1223 execData
.bufErr
->Update();
1226 #endif // wxUSE_STREAMS
1228 // don't consume 100% of the CPU while we're sitting in this
1233 // give GTK+ a chance to call GTK_EndProcessDetector here and
1234 // also repaint the GUI
1238 int exitcode
= endProcData
->exitcode
;
1245 else // async execution
1247 return execData
.pid
;
1254 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
1256 // notify user about termination if required
1257 if ( proc_data
->process
)
1259 proc_data
->process
->OnTerminate(proc_data
->pid
, proc_data
->exitcode
);
1263 if ( proc_data
->pid
> 0 )
1269 // let wxExecute() know that the process has terminated
1274 #endif // wxUSE_BASE