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"
42 #ifdef HAVE_SYS_SELECT_H
43 # include <sys/select.h>
46 #define HAS_PIPE_INPUT_STREAM (wxUSE_STREAMS && wxUSE_FILE)
48 #if HAS_PIPE_INPUT_STREAM
50 // define this to let wxexec.cpp know that we know what we're doing
51 #define _WX_USED_BY_WXEXECUTE_
52 #include "../common/execcmn.cpp"
54 #endif // HAS_PIPE_INPUT_STREAM
58 #if defined(__MWERKS__) && defined(__MACH__)
59 #ifndef WXWIN_OS_DESCRIPTION
60 #define WXWIN_OS_DESCRIPTION "MacOS X"
62 #ifndef HAVE_NANOSLEEP
63 #define HAVE_NANOSLEEP
69 // our configure test believes we can use sigaction() if the function is
70 // available but Metrowekrs with MSL run-time does have the function but
71 // doesn't have sigaction struct so finally we can't use it...
73 #undef wxUSE_ON_FATAL_EXCEPTION
74 #define wxUSE_ON_FATAL_EXCEPTION 0
78 // not only the statfs syscall is called differently depending on platform, but
79 // one of its incarnations, statvfs(), takes different arguments under
80 // different platforms and even different versions of the same system (Solaris
81 // 7 and 8): if you want to test for this, don't forget that the problems only
82 // appear if the large files support is enabled
85 #include <sys/param.h>
86 #include <sys/mount.h>
89 #endif // __BSD__/!__BSD__
91 #define wxStatfs statfs
93 #ifndef HAVE_STATFS_DECL
94 // some systems lack statfs() prototype in the system headers (AIX 4)
95 extern "C" int statfs(const char *path
, struct statfs
*buf
);
100 #include <sys/statvfs.h>
102 #define wxStatfs statvfs
103 #endif // HAVE_STATVFS
105 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
106 // WX_STATFS_T is detected by configure
107 #define wxStatfs_t WX_STATFS_T
110 // SGI signal.h defines signal handler arguments differently depending on
111 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
112 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
113 #define _LANGUAGE_C_PLUS_PLUS 1
119 #include <sys/stat.h>
120 #include <sys/types.h>
121 #include <sys/wait.h>
126 #include <fcntl.h> // for O_WRONLY and friends
127 #include <time.h> // nanosleep() and/or usleep()
128 #include <ctype.h> // isspace()
129 #include <sys/time.h> // needed for FD_SETSIZE
132 #include <sys/utsname.h> // for uname()
135 // Used by wxGetFreeMemory().
137 #include <sys/sysmp.h>
138 #include <sys/sysinfo.h> // for SAGET and MINFO structures
141 // ----------------------------------------------------------------------------
142 // conditional compilation
143 // ----------------------------------------------------------------------------
145 // many versions of Unices have this function, but it is not defined in system
146 // headers - please add your system here if it is the case for your OS.
147 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
148 #if !defined(HAVE_USLEEP) && \
149 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
150 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
151 defined(__osf__) || defined(__EMX__))
155 int usleep(unsigned int usec
);
158 /* I copied this from the XFree86 diffs. AV. */
159 #define INCL_DOSPROCESS
161 inline void usleep(unsigned long delay
)
163 DosSleep(delay
? (delay
/1000l) : 1l);
165 #else // !Sun && !EMX
166 void usleep(unsigned long usec
);
168 #endif // Sun/EMX/Something else
171 #define HAVE_USLEEP 1
172 #endif // Unices without usleep()
174 // ============================================================================
176 // ============================================================================
178 // ----------------------------------------------------------------------------
180 // ----------------------------------------------------------------------------
182 void wxSleep(int nSecs
)
187 void wxMicroSleep(unsigned long microseconds
)
189 #if defined(HAVE_NANOSLEEP)
191 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
192 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
194 // we're not interested in remaining time nor in return value
195 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
196 #elif defined(HAVE_USLEEP)
197 // uncomment this if you feel brave or if you are sure that your version
198 // of Solaris has a safe usleep() function but please notice that usleep()
199 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
200 // documented as MT-Safe
201 #if defined(__SUN__) && wxUSE_THREADS
202 #error "usleep() cannot be used in MT programs under Solaris."
205 usleep(microseconds
);
206 #elif defined(HAVE_SLEEP)
207 // under BeOS sleep() takes seconds (what about other platforms, if any?)
208 sleep(microseconds
* 1000000);
209 #else // !sleep function
210 #error "usleep() or nanosleep() function required for wxMicroSleep"
211 #endif // sleep function
214 void wxMilliSleep(unsigned long milliseconds
)
216 wxMicroSleep(milliseconds
*1000);
219 // ----------------------------------------------------------------------------
220 // process management
221 // ----------------------------------------------------------------------------
223 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
225 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
228 switch ( err
? errno
: 0 )
235 *rc
= wxKILL_BAD_SIGNAL
;
239 *rc
= wxKILL_ACCESS_DENIED
;
243 *rc
= wxKILL_NO_PROCESS
;
247 // this goes against Unix98 docs so log it
248 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
258 #define WXEXECUTE_NARGS 127
260 #if defined(__DARWIN__)
261 long wxMacExecute(wxChar
**argv
,
266 long wxExecute( const wxString
& command
, int flags
, wxProcess
*process
)
268 wxCHECK_MSG( !command
.empty(), 0, wxT("can't exec empty command") );
269 wxLogDebug(wxString(wxT("Launching: ")) + command
);
272 // fork() doesn't mix well with POSIX threads: on many systems the program
273 // deadlocks or crashes for some reason. Probably our code is buggy and
274 // doesn't do something which must be done to allow this to work, but I
275 // don't know what yet, so for now just warn the user (this is the least we
277 wxASSERT_MSG( wxThread::IsMain(),
278 _T("wxExecute() can be called only from the main thread") );
279 #endif // wxUSE_THREADS
282 wxChar
*argv
[WXEXECUTE_NARGS
];
284 const wxChar
*cptr
= command
.c_str();
285 wxChar quotechar
= wxT('\0'); // is arg quoted?
286 bool escaped
= false;
288 // split the command line in arguments
291 argument
= wxEmptyString
;
292 quotechar
= wxT('\0');
294 // eat leading whitespace:
295 while ( wxIsspace(*cptr
) )
298 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
303 if ( *cptr
== wxT('\\') && ! escaped
)
310 // all other characters:
314 // have we reached the end of the argument?
315 if ( (*cptr
== quotechar
&& ! escaped
)
316 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
317 || *cptr
== wxT('\0') )
319 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
320 wxT("too many arguments in wxExecute") );
322 argv
[argc
] = new wxChar
[argument
.length() + 1];
323 wxStrcpy(argv
[argc
], argument
.c_str());
326 // if not at end of buffer, swallow last character:
330 break; // done with this one, start over
337 #if defined(__DARWIN__)
338 // wxMacExecute only executes app bundles.
339 // It returns an error code if the target is not an app bundle, thus falling
340 // through to the regular wxExecute for non app bundles.
341 lRc
= wxMacExecute(argv
, flags
, process
);
342 if( lRc
!= ((flags
& wxEXEC_SYNC
) ? -1 : 0))
346 // do execute the command
347 lRc
= wxExecute(argv
, flags
, process
);
352 delete [] argv
[argc
++];
357 // ----------------------------------------------------------------------------
359 // ----------------------------------------------------------------------------
361 static wxString
wxMakeShellCommand(const wxString
& command
)
366 // just an interactive shell
371 // execute command in a shell
372 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
378 bool wxShell(const wxString
& command
)
380 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
383 bool wxShell(const wxString
& command
, wxArrayString
& output
)
385 wxCHECK_MSG( !command
.empty(), false, _T("can't exec shell non interactively") );
387 return wxExecute(wxMakeShellCommand(command
), output
);
390 // Shutdown or reboot the PC
391 bool wxShutdown(wxShutdownFlags wFlags
)
396 case wxSHUTDOWN_POWEROFF
:
400 case wxSHUTDOWN_REBOOT
:
405 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
409 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
412 // ----------------------------------------------------------------------------
413 // wxStream classes to support IO redirection in wxExecute
414 // ----------------------------------------------------------------------------
416 #if HAS_PIPE_INPUT_STREAM
418 bool wxPipeInputStream::CanRead() const
420 if ( m_lasterror
== wxSTREAM_EOF
)
423 // check if there is any input available
428 const int fd
= m_file
->fd();
433 wxFD_SET(fd
, &readfds
);
435 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
438 wxLogSysError(_("Impossible to get child process input"));
445 wxFAIL_MSG(_T("unexpected select() return value"));
446 // still fall through
449 // input available -- or maybe not, as select() returns 1 when a
450 // read() will complete without delay, but it could still not read
456 #endif // HAS_PIPE_INPUT_STREAM
458 // ----------------------------------------------------------------------------
459 // wxExecute: the real worker function
460 // ----------------------------------------------------------------------------
462 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*process
)
464 // for the sync execution, we return -1 to indicate failure, but for async
465 // case we return 0 which is never a valid PID
467 // we define this as a macro, not a variable, to avoid compiler warnings
468 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
469 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
471 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
475 char *mb_argv
[WXEXECUTE_NARGS
];
477 while (argv
[mb_argc
])
479 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
480 mb_argv
[mb_argc
] = strdup(mb_arg
);
483 mb_argv
[mb_argc
] = (char *) NULL
;
485 // this macro will free memory we used above
486 #define ARGS_CLEANUP \
487 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
488 free(mb_argv[mb_argc])
490 // no need for cleanup
493 wxChar
**mb_argv
= argv
;
494 #endif // Unicode/ANSI
496 // we want this function to work even if there is no wxApp so ensure that
497 // we have a valid traits pointer
498 wxConsoleAppTraits traitsConsole
;
499 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
501 traits
= &traitsConsole
;
503 // this struct contains all information which we pass to and from
504 // wxAppTraits methods
505 wxExecuteData execData
;
506 execData
.flags
= flags
;
507 execData
.process
= process
;
510 if ( !traits
->CreateEndProcessPipe(execData
) )
512 wxLogError( _("Failed to execute '%s'\n"), *argv
);
516 return ERROR_RETURN_CODE
;
519 // pipes for inter process communication
520 wxPipe pipeIn
, // stdin
524 if ( process
&& process
->IsRedirected() )
526 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
528 wxLogError( _("Failed to execute '%s'\n"), *argv
);
532 return ERROR_RETURN_CODE
;
538 // NB: do *not* use vfork() here, it completely breaks this code for some
539 // reason under Solaris (and maybe others, although not under Linux)
540 // But on OpenVMS we do not have fork so we have to use vfork and
541 // cross our fingers that it works.
547 if ( pid
== -1 ) // error?
549 wxLogSysError( _("Fork failed") );
553 return ERROR_RETURN_CODE
;
555 else if ( pid
== 0 ) // we're in child
557 // These lines close the open file descriptors to to avoid any
558 // input/output which might block the process or irritate the user. If
559 // one wants proper IO for the subprocess, the right thing to do is to
560 // start an xterm executing it.
561 if ( !(flags
& wxEXEC_SYNC
) )
563 // FD_SETSIZE is unsigned under BSD, signed under other platforms
564 // so we need a cast to avoid warnings on all platforms
565 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
567 if ( fd
== pipeIn
[wxPipe::Read
]
568 || fd
== pipeOut
[wxPipe::Write
]
569 || fd
== pipeErr
[wxPipe::Write
]
570 || traits
->IsWriteFDOfEndProcessPipe(execData
, fd
) )
572 // don't close this one, we still need it
576 // leave stderr opened too, it won't do any harm
577 if ( fd
!= STDERR_FILENO
)
582 #if !defined(__VMS) && !defined(__EMX__)
583 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
585 // Set process group to child process' pid. Then killing -pid
586 // of the parent will kill the process and all of its children.
591 // reading side can be safely closed but we should keep the write one
593 traits
->DetachWriteFDOfEndProcessPipe(execData
);
595 // redirect stdin, stdout and stderr
598 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
599 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
600 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
602 wxLogSysError(_("Failed to redirect child process input/output"));
610 execvp (*mb_argv
, mb_argv
);
612 fprintf(stderr
, "execvp(");
613 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
614 for ( char **ppc_
= mb_argv
; *ppc_
; ppc_
++ )
615 fprintf(stderr
, "%s%s", ppc_
== mb_argv
? "" : ", ", *ppc_
);
616 fprintf(stderr
, ") failed with error %d!\n", errno
);
618 // there is no return after successful exec()
621 // some compilers complain about missing return - of course, they
622 // should know that exit() doesn't return but what else can we do if
625 // and, sure enough, other compilers complain about unreachable code
626 // after exit() call, so we can just always have return here...
627 #if defined(__VMS) || defined(__INTEL_COMPILER)
631 else // we're in parent
635 // save it for WaitForChild() use
638 // prepare for IO redirection
640 #if HAS_PIPE_INPUT_STREAM
641 // the input buffer bufOut is connected to stdout, this is why it is
642 // called bufOut and not bufIn
643 wxStreamTempInputBuffer bufOut
,
645 #endif // HAS_PIPE_INPUT_STREAM
647 if ( process
&& process
->IsRedirected() )
649 #if HAS_PIPE_INPUT_STREAM
650 wxOutputStream
*inStream
=
651 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
653 wxPipeInputStream
*outStream
=
654 new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
656 wxPipeInputStream
*errStream
=
657 new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
659 process
->SetPipeStreams(outStream
, inStream
, errStream
);
661 bufOut
.Init(outStream
);
662 bufErr
.Init(errStream
);
664 execData
.bufOut
= &bufOut
;
665 execData
.bufErr
= &bufErr
;
666 #endif // HAS_PIPE_INPUT_STREAM
676 return traits
->WaitForChild(execData
);
679 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
680 return ERROR_RETURN_CODE
;
684 #undef ERROR_RETURN_CODE
687 // ----------------------------------------------------------------------------
688 // file and directory functions
689 // ----------------------------------------------------------------------------
691 const wxChar
* wxGetHomeDir( wxString
*home
)
693 *home
= wxGetUserHome( wxEmptyString
);
699 if ( tmp
.Last() != wxT(']'))
700 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
702 return home
->c_str();
706 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
707 #else // just for binary compatibility -- there is no 'const' here
708 char *wxGetUserHome( const wxString
&user
)
711 struct passwd
*who
= (struct passwd
*) NULL
;
717 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
720 wxWCharBuffer
buffer( ptr
);
726 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
728 who
= getpwnam(wxConvertWX2MB(ptr
));
731 // We now make sure the the user exists!
734 who
= getpwuid(getuid());
739 who
= getpwnam (user
.mb_str());
742 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
745 // ----------------------------------------------------------------------------
746 // network and user id routines
747 // ----------------------------------------------------------------------------
749 // retrieve either the hostname or FQDN depending on platform (caller must
750 // check whether it's one or the other, this is why this function is for
752 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
754 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
758 // we're using uname() which is POSIX instead of less standard sysinfo()
759 #if defined(HAVE_UNAME)
761 bool ok
= uname(&uts
) != -1;
764 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
767 #elif defined(HAVE_GETHOSTNAME)
768 bool ok
= gethostname(buf
, sz
) != -1;
769 #else // no uname, no gethostname
770 wxFAIL_MSG(wxT("don't know host name for this machine"));
773 #endif // uname/gethostname
777 wxLogSysError(_("Cannot get the hostname"));
783 bool wxGetHostName(wxChar
*buf
, int sz
)
785 bool ok
= wxGetHostNameInternal(buf
, sz
);
789 // BSD systems return the FQDN, we only want the hostname, so extract
790 // it (we consider that dots are domain separators)
791 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
802 bool wxGetFullHostName(wxChar
*buf
, int sz
)
804 bool ok
= wxGetHostNameInternal(buf
, sz
);
808 if ( !wxStrchr(buf
, wxT('.')) )
810 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
813 wxLogSysError(_("Cannot get the official hostname"));
819 // the canonical name
820 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
823 //else: it's already a FQDN (BSD behaves this way)
829 bool wxGetUserId(wxChar
*buf
, int sz
)
834 if ((who
= getpwuid(getuid ())) != NULL
)
836 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
843 bool wxGetUserName(wxChar
*buf
, int sz
)
848 if ((who
= getpwuid (getuid ())) != NULL
)
850 // pw_gecos field in struct passwd is not standard
852 char *comma
= strchr(who
->pw_gecos
, ',');
854 *comma
= '\0'; // cut off non-name comment fields
855 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
856 #else // !HAVE_PW_GECOS
857 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
858 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
865 // this function is in mac/utils.cpp for wxMac
868 wxString
wxGetOsDescription()
870 FILE *f
= popen("uname -s -r -m", "r");
874 size_t c
= fread(buf
, 1, sizeof(buf
) - 1, f
);
876 // Trim newline from output.
877 if (c
&& buf
[c
- 1] == '\n')
880 return wxString::FromAscii( buf
);
882 wxFAIL_MSG( _T("uname failed") );
883 return wxEmptyString
;
888 unsigned long wxGetProcessId()
890 return (unsigned long)getpid();
893 wxMemorySize
wxGetFreeMemory()
895 #if defined(__LINUX__)
896 // get it from /proc/meminfo
897 FILE *fp
= fopen("/proc/meminfo", "r");
903 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
905 long memTotal
, memUsed
;
906 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
911 return (wxMemorySize
)memFree
;
913 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
914 return (wxMemorySize
)(sysconf(_SC_AVPHYS_PAGES
)*sysconf(_SC_PAGESIZE
));
915 #elif defined(__SGI__)
916 struct rminfo realmem
;
917 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
918 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
919 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
926 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
928 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
929 // the case to "char *" is needed for AIX 4.3
931 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
933 wxLogSysError( wxT("Failed to get file system statistics") );
938 // under Solaris we also have to use f_frsize field instead of f_bsize
939 // which is in general a multiple of f_frsize
941 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
943 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
944 #endif // HAVE_STATVFS/HAVE_STATFS
948 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
953 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
957 #else // !HAVE_STATFS && !HAVE_STATVFS
959 #endif // HAVE_STATFS
962 // ----------------------------------------------------------------------------
964 // ----------------------------------------------------------------------------
966 bool wxGetEnv(const wxString
& var
, wxString
*value
)
968 // wxGetenv is defined as getenv()
969 wxChar
*p
= wxGetenv(var
);
981 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
983 #if defined(HAVE_SETENV)
984 return setenv(variable
.mb_str(),
985 value
? (const char *)wxString(value
).mb_str()
987 1 /* overwrite */) == 0;
988 #elif defined(HAVE_PUTENV)
989 wxString s
= variable
;
991 s
<< _T('=') << value
;
994 const wxWX2MBbuf p
= s
.mb_str();
996 // the string will be free()d by libc
997 char *buf
= (char *)malloc(strlen(p
) + 1);
1000 return putenv(buf
) == 0;
1001 #else // no way to set an env var
1006 // ----------------------------------------------------------------------------
1008 // ----------------------------------------------------------------------------
1010 #if wxUSE_ON_FATAL_EXCEPTION
1014 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1018 // give the user a chance to do something special about this
1019 wxTheApp
->OnFatalException();
1025 bool wxHandleFatalExceptions(bool doit
)
1028 static bool s_savedHandlers
= false;
1029 static struct sigaction s_handlerFPE
,
1035 if ( doit
&& !s_savedHandlers
)
1037 // install the signal handler
1038 struct sigaction act
;
1040 // some systems extend it with non std fields, so zero everything
1041 memset(&act
, 0, sizeof(act
));
1043 act
.sa_handler
= wxFatalSignalHandler
;
1044 sigemptyset(&act
.sa_mask
);
1047 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1048 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1049 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1050 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1053 wxLogDebug(_T("Failed to install our signal handler."));
1056 s_savedHandlers
= true;
1058 else if ( s_savedHandlers
)
1060 // uninstall the signal handler
1061 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1062 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1063 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1064 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1067 wxLogDebug(_T("Failed to uninstall our signal handler."));
1070 s_savedHandlers
= false;
1072 //else: nothing to do
1077 #endif // wxUSE_ON_FATAL_EXCEPTION
1079 #endif // wxUSE_BASE
1083 // ----------------------------------------------------------------------------
1084 // wxExecute support
1085 // ----------------------------------------------------------------------------
1087 // Darwin doesn't use the same process end detection mechanisms so we don't
1088 // need wxExecute-related helpers for it
1089 #if !(defined(__DARWIN__) && defined(__WXMAC__))
1091 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& execData
)
1093 return execData
.pipeEndProcDetect
.Create();
1096 bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& execData
, int fd
)
1098 return fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
];
1101 void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& execData
)
1103 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
1104 execData
.pipeEndProcDetect
.Close();
1109 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1115 wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
),
1122 wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1124 // nothing to do here, we don't use the pipe
1127 #endif // !Darwin/Darwin
1129 int wxGUIAppTraits::WaitForChild(wxExecuteData
& execData
)
1131 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1133 const int flags
= execData
.flags
;
1135 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1136 // callback function directly if the process terminates before
1137 // the callback can be added to the run loop. Set up the endProcData.
1138 if ( flags
& wxEXEC_SYNC
)
1140 // we may have process for capturing the program output, but it's
1141 // not used in wxEndProcessData in the case of sync execution
1142 endProcData
->process
= NULL
;
1144 // sync execution: indicate it by negating the pid
1145 endProcData
->pid
= -execData
.pid
;
1149 // async execution, nothing special to do -- caller will be
1150 // notified about the process termination if process != NULL, endProcData
1151 // will be deleted in GTK_EndProcessDetector
1152 endProcData
->process
= execData
.process
;
1153 endProcData
->pid
= execData
.pid
;
1157 #if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1158 endProcData
->tag
= wxAddProcessCallbackForPid(endProcData
, execData
.pid
);
1160 endProcData
->tag
= wxAddProcessCallback
1163 execData
.pipeEndProcDetect
.Detach(wxPipe::Read
)
1166 execData
.pipeEndProcDetect
.Close();
1167 #endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1169 if ( flags
& wxEXEC_SYNC
)
1172 wxWindowDisabler
*wd
= flags
& wxEXEC_NODISABLE
? NULL
1173 : new wxWindowDisabler
;
1175 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1176 // process terminates
1177 while ( endProcData
->pid
!= 0 )
1181 #if HAS_PIPE_INPUT_STREAM
1182 if ( execData
.bufOut
)
1184 execData
.bufOut
->Update();
1188 if ( execData
.bufErr
)
1190 execData
.bufErr
->Update();
1193 #endif // HAS_PIPE_INPUT_STREAM
1195 // don't consume 100% of the CPU while we're sitting in this
1200 // give GTK+ a chance to call GTK_EndProcessDetector here and
1201 // also repaint the GUI
1205 int exitcode
= endProcData
->exitcode
;
1212 else // async execution
1214 return execData
.pid
;
1221 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
1223 // notify user about termination if required
1224 if ( proc_data
->process
)
1226 proc_data
->process
->OnTerminate(proc_data
->pid
, proc_data
->exitcode
);
1230 if ( proc_data
->pid
> 0 )
1236 // let wxExecute() know that the process has terminated
1241 #endif // wxUSE_BASE