1 /////////////////////////////////////////////////////////////////////////////
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 // ----------------------------------------------------------------------------
19 #include "wx/string.h"
26 #include "wx/process.h"
27 #include "wx/thread.h"
29 #include "wx/stream.h"
33 # include <sys/param.h>
34 # include <sys/mount.h>
40 // not only the statfs syscall is called differently depending on platform, but
41 // we also can't use "struct statvfs" under Solaris because it breaks down if
42 // HAVE_LARGEFILE_SUPPORT == 1 and we must use statvfs_t instead
44 #include <sys/statvfs.h>
46 #define statfs statvfs
47 #define wxStatFs statvfs_t
49 #define wxStatFs struct statfs
50 #endif // HAVE_STAT[V]FS
53 #include "wx/unix/execute.h"
56 // SGI signal.h defines signal handler arguments differently depending on
57 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
58 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
59 #define _LANGUAGE_C_PLUS_PLUS 1
66 #include <sys/types.h>
73 #include <fcntl.h> // for O_WRONLY and friends
74 #include <time.h> // nanosleep() and/or usleep()
75 #include <ctype.h> // isspace()
76 #include <sys/time.h> // needed for FD_SETSIZE
79 #include <sys/utsname.h> // for uname()
82 // ----------------------------------------------------------------------------
83 // conditional compilation
84 // ----------------------------------------------------------------------------
86 // many versions of Unices have this function, but it is not defined in system
87 // headers - please add your system here if it is the case for your OS.
88 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
89 #if !defined(HAVE_USLEEP) && \
90 (defined(__SUN__) && !defined(__SunOs_5_6) && \
91 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
92 defined(__osf__) || defined(__EMX__)
96 int usleep(unsigned int usec
);
99 /* I copied this from the XFree86 diffs. AV. */
100 #define INCL_DOSPROCESS
102 inline void usleep(unsigned long delay
)
104 DosSleep(delay
? (delay
/1000l) : 1l);
106 #else // !Sun && !EMX
107 void usleep(unsigned long usec
);
109 #endif // Sun/EMX/Something else
112 #define HAVE_USLEEP 1
113 #endif // Unices without usleep()
115 // ============================================================================
117 // ============================================================================
119 // ----------------------------------------------------------------------------
121 // ----------------------------------------------------------------------------
123 void wxSleep(int nSecs
)
128 void wxUsleep(unsigned long milliseconds
)
130 #if defined(HAVE_NANOSLEEP)
132 tmReq
.tv_sec
= (time_t)(milliseconds
/ 1000);
133 tmReq
.tv_nsec
= (milliseconds
% 1000) * 1000 * 1000;
135 // we're not interested in remaining time nor in return value
136 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
137 #elif defined(HAVE_USLEEP)
138 // uncomment this if you feel brave or if you are sure that your version
139 // of Solaris has a safe usleep() function but please notice that usleep()
140 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
141 // documented as MT-Safe
142 #if defined(__SUN__) && wxUSE_THREADS
143 #error "usleep() cannot be used in MT programs under Solaris."
146 usleep(milliseconds
* 1000); // usleep(3) wants microseconds
147 #elif defined(HAVE_SLEEP)
148 // under BeOS sleep() takes seconds (what about other platforms, if any?)
149 sleep(milliseconds
* 1000);
150 #else // !sleep function
151 #error "usleep() or nanosleep() function required for wxUsleep"
152 #endif // sleep function
155 // ----------------------------------------------------------------------------
156 // process management
157 // ----------------------------------------------------------------------------
159 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
)
161 int err
= kill((pid_t
)pid
, (int)sig
);
171 *rc
= wxKILL_BAD_SIGNAL
;
175 *rc
= wxKILL_ACCESS_DENIED
;
179 *rc
= wxKILL_NO_PROCESS
;
183 // this goes against Unix98 docs so log it
184 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
194 #define WXEXECUTE_NARGS 127
196 long wxExecute( const wxString
& command
, int flags
, wxProcess
*process
)
198 wxCHECK_MSG( !command
.IsEmpty(), 0, wxT("can't exec empty command") );
201 wxChar
*argv
[WXEXECUTE_NARGS
];
203 const wxChar
*cptr
= command
.c_str();
204 wxChar quotechar
= wxT('\0'); // is arg quoted?
205 bool escaped
= FALSE
;
207 // split the command line in arguments
211 quotechar
= wxT('\0');
213 // eat leading whitespace:
214 while ( wxIsspace(*cptr
) )
217 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
222 if ( *cptr
== wxT('\\') && ! escaped
)
229 // all other characters:
233 // have we reached the end of the argument?
234 if ( (*cptr
== quotechar
&& ! escaped
)
235 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
236 || *cptr
== wxT('\0') )
238 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
239 wxT("too many arguments in wxExecute") );
241 argv
[argc
] = new wxChar
[argument
.length() + 1];
242 wxStrcpy(argv
[argc
], argument
.c_str());
245 // if not at end of buffer, swallow last character:
249 break; // done with this one, start over
255 // do execute the command
256 long lRc
= wxExecute(argv
, flags
, process
);
261 delete [] argv
[argc
++];
266 // ----------------------------------------------------------------------------
268 // ----------------------------------------------------------------------------
270 static wxString
wxMakeShellCommand(const wxString
& command
)
275 // just an interactive shell
280 // execute command in a shell
281 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
287 bool wxShell(const wxString
& command
)
289 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
292 bool wxShell(const wxString
& command
, wxArrayString
& output
)
294 wxCHECK_MSG( !!command
, FALSE
, _T("can't exec shell non interactively") );
296 return wxExecute(wxMakeShellCommand(command
), output
);
299 // Shutdown or reboot the PC
300 bool wxShutdown(wxShutdownFlags wFlags
)
305 case wxSHUTDOWN_POWEROFF
:
309 case wxSHUTDOWN_REBOOT
:
314 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
318 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
324 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
326 // notify user about termination if required
327 if ( proc_data
->process
)
329 proc_data
->process
->OnTerminate(proc_data
->pid
, proc_data
->exitcode
);
333 if ( proc_data
->pid
> 0 )
339 // let wxExecute() know that the process has terminated
346 // ----------------------------------------------------------------------------
347 // wxStream classes to support IO redirection in wxExecute
348 // ----------------------------------------------------------------------------
352 class wxProcessFileInputStream
: public wxInputStream
355 wxProcessFileInputStream(int fd
) { m_fd
= fd
; }
356 ~wxProcessFileInputStream() { close(m_fd
); }
358 virtual bool Eof() const;
361 size_t OnSysRead(void *buffer
, size_t bufsize
);
367 class wxProcessFileOutputStream
: public wxOutputStream
370 wxProcessFileOutputStream(int fd
) { m_fd
= fd
; }
371 ~wxProcessFileOutputStream() { close(m_fd
); }
374 size_t OnSysWrite(const void *buffer
, size_t bufsize
);
380 bool wxProcessFileInputStream::Eof() const
382 if ( m_lasterror
== wxSTREAM_EOF
)
385 // check if there is any input available
392 FD_SET(m_fd
, &readfds
);
393 switch ( select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
396 wxLogSysError(_("Impossible to get child process input"));
403 wxFAIL_MSG(_T("unexpected select() return value"));
404 // still fall through
407 // input available: check if there is any
408 return wxInputStream::Eof();
412 size_t wxProcessFileInputStream::OnSysRead(void *buffer
, size_t bufsize
)
414 int ret
= read(m_fd
, buffer
, bufsize
);
417 m_lasterror
= wxSTREAM_EOF
;
419 else if ( ret
== -1 )
421 m_lasterror
= wxSTREAM_READ_ERROR
;
426 m_lasterror
= wxSTREAM_NOERROR
;
432 size_t wxProcessFileOutputStream::OnSysWrite(const void *buffer
, size_t bufsize
)
434 int ret
= write(m_fd
, buffer
, bufsize
);
437 m_lasterror
= wxSTREAM_WRITE_ERROR
;
442 m_lasterror
= wxSTREAM_NOERROR
;
448 // ----------------------------------------------------------------------------
449 // wxStreamTempBuffer
450 // ----------------------------------------------------------------------------
453 Extract of a mail to wx-users to give the context of the problem we are
454 trying to solve here:
456 MC> If I run the command:
457 MC> find . -name "*.h" -exec grep linux {} \;
458 MC> in the exec sample synchronously from the 'Capture command output'
459 MC> menu, wxExecute never returns. I have to xkill it. Has anyone
460 MC> else encountered this?
462 Yes, I can reproduce it too.
464 I even think I understand why it happens: before launching the external
465 command we set up a pipe with a valid file descriptor on the reading side
466 when the output is redirected. So the subprocess happily writes to it ...
467 until the pipe buffer (which is usually quite big on Unix, I think the
468 default is 4Mb) is full. Then the writing process stops and waits until we
469 read some data from the pipe to be able to continue writing to it but we
470 never do it because we wait until it terminates to start reading and so we
471 have a classical deadlock.
473 Here is the fix: we now read the output as soon as it appears into a temp
474 buffer (wxStreamTempBuffer object) and later just stuff it back into the
475 stream when the process terminates. See supporting code in wxExecute()
479 class wxStreamTempBuffer
482 wxStreamTempBuffer();
484 // call to associate a stream with this buffer, otherwise nothing happens
486 void Init(wxInputStream
*stream
);
488 // check for input on our stream and cache it in our buffer if any
491 ~wxStreamTempBuffer();
494 // the stream we're buffering, if NULL we don't do anything at all
495 wxInputStream
*m_stream
;
497 // the buffer of size m_size (NULL if m_size == 0)
500 // the size of the buffer
504 wxStreamTempBuffer::wxStreamTempBuffer()
511 void wxStreamTempBuffer::Init(wxInputStream
*stream
)
516 void wxStreamTempBuffer::Update()
518 if ( m_stream
&& !m_stream
->Eof() )
520 // realloc in blocks of 1Kb - surely not the best strategy but which
522 static const size_t incSize
= 1024;
524 void *buf
= realloc(m_buffer
, m_size
+ incSize
);
527 // don't read any more, we don't have enough memory to do it
530 else // got memory for the buffer
533 m_stream
->Read((char *)m_buffer
+ m_size
, incSize
);
539 wxStreamTempBuffer::~wxStreamTempBuffer()
543 m_stream
->Ungetch(m_buffer
, m_size
);
548 #endif // wxUSE_STREAMS
550 long wxExecute(wxChar
**argv
,
554 // for the sync execution, we return -1 to indicate failure, but for async
555 // case we return 0 which is never a valid PID
557 // we define this as a macro, not a variable, to avoid compiler warnings
558 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
559 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
561 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
565 char *mb_argv
[WXEXECUTE_NARGS
];
567 while (argv
[mb_argc
])
569 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
570 mb_argv
[mb_argc
] = strdup(mb_arg
);
573 mb_argv
[mb_argc
] = (char *) NULL
;
575 // this macro will free memory we used above
576 #define ARGS_CLEANUP \
577 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
578 free(mb_argv[mb_argc])
580 // no need for cleanup
583 wxChar
**mb_argv
= argv
;
584 #endif // Unicode/ANSI
588 int end_proc_detect
[2];
589 if ( pipe(end_proc_detect
) == -1 )
591 wxLogSysError( _("Pipe creation failed") );
592 wxLogError( _("Failed to execute '%s'\n"), *argv
);
596 return ERROR_RETURN_CODE
;
600 // pipes for inter process communication
601 int pipeIn
[2], // stdin
602 pipeOut
[2], // stdout
603 pipeErr
[2]; // stderr
605 pipeIn
[0] = pipeIn
[1] =
606 pipeOut
[0] = pipeOut
[1] =
607 pipeErr
[0] = pipeErr
[1] = -1;
609 if ( process
&& process
->IsRedirected() )
611 if ( pipe(pipeIn
) == -1 || pipe(pipeOut
) == -1 || pipe(pipeErr
) == -1 )
614 // free previously allocated resources
615 close(end_proc_detect
[0]);
616 close(end_proc_detect
[1]);
619 wxLogSysError( _("Pipe creation failed") );
620 wxLogError( _("Failed to execute '%s'\n"), *argv
);
624 return ERROR_RETURN_CODE
;
635 if ( pid
== -1 ) // error?
638 close(end_proc_detect
[0]);
639 close(end_proc_detect
[1]);
648 wxLogSysError( _("Fork failed") );
652 return ERROR_RETURN_CODE
;
654 else if ( pid
== 0 ) // we're in child
657 close(end_proc_detect
[0]); // close reading side
660 // These lines close the open file descriptors to to avoid any
661 // input/output which might block the process or irritate the user. If
662 // one wants proper IO for the subprocess, the right thing to do is to
663 // start an xterm executing it.
664 if ( !(flags
& wxEXEC_SYNC
) )
666 for ( int fd
= 0; fd
< FD_SETSIZE
; fd
++ )
668 if ( fd
== pipeIn
[0] || fd
== pipeOut
[1] || fd
== pipeErr
[1]
670 || fd
== end_proc_detect
[1]
674 // don't close this one, we still need it
678 // leave stderr opened too, it won't do any hurm
679 if ( fd
!= STDERR_FILENO
)
684 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
686 // Set process group to child process' pid. Then killing -pid
687 // of the parent will kill the process and all of its children.
693 // redirect stdio, stdout and stderr
694 if ( pipeIn
[0] != -1 )
696 if ( dup2(pipeIn
[0], STDIN_FILENO
) == -1 ||
697 dup2(pipeOut
[1], STDOUT_FILENO
) == -1 ||
698 dup2(pipeErr
[1], STDERR_FILENO
) == -1 )
700 wxLogSysError(_("Failed to redirect child process input/output"));
708 execvp (*mb_argv
, mb_argv
);
710 // there is no return after successful exec()
713 // some compilers complain about missing return - of course, they
714 // should know that exit() doesn't return but what else can we do if
716 #if defined(__VMS) || defined(__INTEL_COMPILER)
720 else // we're in parent
724 // pipe initialization: construction of the wxStreams
726 wxStreamTempBuffer bufIn
, bufErr
;
727 #endif // wxUSE_STREAMS
729 if ( process
&& process
->IsRedirected() )
732 // in/out for subprocess correspond to our out/in
733 wxOutputStream
*outStream
= new wxProcessFileOutputStream(pipeIn
[1]);
734 wxInputStream
*inStream
= new wxProcessFileInputStream(pipeOut
[0]);
735 wxInputStream
*errStream
= new wxProcessFileInputStream(pipeErr
[0]);
737 process
->SetPipeStreams(inStream
, outStream
, errStream
);
739 bufIn
.Init(inStream
);
740 bufErr
.Init(inStream
);
741 #endif // wxUSE_STREAMS
743 close(pipeIn
[0]); // close reading side
744 close(pipeOut
[1]); // close writing side
745 close(pipeErr
[1]); // close writing side
748 #if wxUSE_GUI && !defined(__WXMICROWIN__)
749 wxEndProcessData
*data
= new wxEndProcessData
;
751 if ( flags
& wxEXEC_SYNC
)
753 // we may have process for capturing the program output, but it's
754 // not used in wxEndProcessData in the case of sync execution
755 data
->process
= NULL
;
757 // sync execution: indicate it by negating the pid
759 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
761 close(end_proc_detect
[1]); // close writing side
766 // data->pid will be set to 0 from GTK_EndProcessDetector when the
767 // process terminates
768 while ( data
->pid
!= 0 )
773 #endif // wxUSE_STREAMS
775 // give GTK+ a chance to call GTK_EndProcessDetector here and
776 // also repaint the GUI
780 int exitcode
= data
->exitcode
;
786 else // async execution
788 // async execution, nothing special to do - caller will be
789 // notified about the process termination if process != NULL, data
790 // will be deleted in GTK_EndProcessDetector
791 data
->process
= process
;
793 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
795 close(end_proc_detect
[1]); // close writing side
801 wxASSERT_MSG( flags
& wxEXEC_SYNC
,
802 wxT("async execution not supported yet") );
805 if ( waitpid(pid
, &exitcode
, 0) == -1 || !WIFEXITED(exitcode
) )
807 wxLogSysError(_("Waiting for subprocess termination failed"));
815 #undef ERROR_RETURN_CODE
818 // ----------------------------------------------------------------------------
819 // file and directory functions
820 // ----------------------------------------------------------------------------
822 const wxChar
* wxGetHomeDir( wxString
*home
)
824 *home
= wxGetUserHome( wxString() );
826 if ( home
->IsEmpty() )
830 if ( tmp
.Last() != wxT(']'))
831 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
833 return home
->c_str();
837 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
838 #else // just for binary compatibility -- there is no 'const' here
839 char *wxGetUserHome( const wxString
&user
)
842 struct passwd
*who
= (struct passwd
*) NULL
;
848 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
852 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
854 who
= getpwnam(wxConvertWX2MB(ptr
));
857 // We now make sure the the user exists!
860 who
= getpwuid(getuid());
865 who
= getpwnam (user
.mb_str());
868 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
871 // ----------------------------------------------------------------------------
872 // network and user id routines
873 // ----------------------------------------------------------------------------
875 // retrieve either the hostname or FQDN depending on platform (caller must
876 // check whether it's one or the other, this is why this function is for
878 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
880 wxCHECK_MSG( buf
, FALSE
, wxT("NULL pointer in wxGetHostNameInternal") );
884 // we're using uname() which is POSIX instead of less standard sysinfo()
885 #if defined(HAVE_UNAME)
887 bool ok
= uname(&uts
) != -1;
890 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
893 #elif defined(HAVE_GETHOSTNAME)
894 bool ok
= gethostname(buf
, sz
) != -1;
895 #else // no uname, no gethostname
896 wxFAIL_MSG(wxT("don't know host name for this machine"));
899 #endif // uname/gethostname
903 wxLogSysError(_("Cannot get the hostname"));
909 bool wxGetHostName(wxChar
*buf
, int sz
)
911 bool ok
= wxGetHostNameInternal(buf
, sz
);
915 // BSD systems return the FQDN, we only want the hostname, so extract
916 // it (we consider that dots are domain separators)
917 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
928 bool wxGetFullHostName(wxChar
*buf
, int sz
)
930 bool ok
= wxGetHostNameInternal(buf
, sz
);
934 if ( !wxStrchr(buf
, wxT('.')) )
936 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
939 wxLogSysError(_("Cannot get the official hostname"));
945 // the canonical name
946 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
949 //else: it's already a FQDN (BSD behaves this way)
955 bool wxGetUserId(wxChar
*buf
, int sz
)
960 if ((who
= getpwuid(getuid ())) != NULL
)
962 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
969 bool wxGetUserName(wxChar
*buf
, int sz
)
974 if ((who
= getpwuid (getuid ())) != NULL
)
976 // pw_gecos field in struct passwd is not standard
978 char *comma
= strchr(who
->pw_gecos
, ',');
980 *comma
= '\0'; // cut off non-name comment fields
981 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
982 #else // !HAVE_PW_GECOS
983 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
984 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
992 wxString
wxGetOsDescription()
994 #ifndef WXWIN_OS_DESCRIPTION
995 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
997 return WXWIN_OS_DESCRIPTION
;
1002 // this function returns the GUI toolkit version in GUI programs, but OS
1003 // version in non-GUI ones
1006 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
1011 if ( sscanf(WXWIN_OS_DESCRIPTION
, "%s %d.%d", name
, &major
, &minor
) != 3 )
1013 // unreckognized uname string format
1025 #endif // !wxUSE_GUI
1027 unsigned long wxGetProcessId()
1029 return (unsigned long)getpid();
1032 long wxGetFreeMemory()
1034 #if defined(__LINUX__)
1035 // get it from /proc/meminfo
1036 FILE *fp
= fopen("/proc/meminfo", "r");
1042 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
1044 long memTotal
, memUsed
;
1045 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
1052 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
1053 return sysconf(_SC_AVPHYS_PAGES
)*sysconf(_SC_PAGESIZE
);
1054 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1057 // can't find it out
1061 bool wxGetDiskSpace(const wxString
& path
, wxLongLong
*pTotal
, wxLongLong
*pFree
)
1063 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1064 // the case to "char *" is needed for AIX 4.3
1066 if ( statfs((char *)path
.fn_str(), &fs
) != 0 )
1068 wxLogSysError("Failed to get file system statistics");
1073 // under Solaris we also have to use f_frsize field instead of f_bsize
1074 // which is in general a multiple of f_frsize
1076 wxLongLong blockSize
= fs
.f_frsize
;
1077 #else // HAVE_STATFS
1078 wxLongLong blockSize
= fs
.f_bsize
;
1079 #endif // HAVE_STATVFS/HAVE_STATFS
1083 *pTotal
= wxLongLong(fs
.f_blocks
) * blockSize
;
1088 *pFree
= wxLongLong(fs
.f_bavail
) * blockSize
;
1092 #else // !HAVE_STATFS && !HAVE_STATVFS
1094 #endif // HAVE_STATFS
1097 // ----------------------------------------------------------------------------
1099 // ----------------------------------------------------------------------------
1101 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1103 // wxGetenv is defined as getenv()
1104 wxChar
*p
= wxGetenv(var
);
1116 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
1118 #if defined(HAVE_SETENV)
1119 return setenv(variable
.mb_str(),
1120 value
? (const char *)wxString(value
).mb_str()
1122 1 /* overwrite */) == 0;
1123 #elif defined(HAVE_PUTENV)
1124 wxString s
= variable
;
1126 s
<< _T('=') << value
;
1128 // transform to ANSI
1129 const char *p
= s
.mb_str();
1131 // the string will be free()d by libc
1132 char *buf
= (char *)malloc(strlen(p
) + 1);
1135 return putenv(buf
) == 0;
1136 #else // no way to set an env var
1141 // ----------------------------------------------------------------------------
1143 // ----------------------------------------------------------------------------
1145 #if wxUSE_ON_FATAL_EXCEPTION
1149 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1153 // give the user a chance to do something special about this
1154 wxTheApp
->OnFatalException();
1160 bool wxHandleFatalExceptions(bool doit
)
1163 static bool s_savedHandlers
= FALSE
;
1164 static struct sigaction s_handlerFPE
,
1170 if ( doit
&& !s_savedHandlers
)
1172 // install the signal handler
1173 struct sigaction act
;
1175 // some systems extend it with non std fields, so zero everything
1176 memset(&act
, 0, sizeof(act
));
1178 act
.sa_handler
= wxFatalSignalHandler
;
1179 sigemptyset(&act
.sa_mask
);
1182 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1183 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1184 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1185 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1188 wxLogDebug(_T("Failed to install our signal handler."));
1191 s_savedHandlers
= TRUE
;
1193 else if ( s_savedHandlers
)
1195 // uninstall the signal handler
1196 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1197 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1198 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1199 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1202 wxLogDebug(_T("Failed to uninstall our signal handler."));
1205 s_savedHandlers
= FALSE
;
1207 //else: nothing to do
1212 #endif // wxUSE_ON_FATAL_EXCEPTION
1214 // ----------------------------------------------------------------------------
1215 // error and debug output routines (deprecated, use wxLog)
1216 // ----------------------------------------------------------------------------
1218 #if WXWIN_COMPATIBILITY_2_2
1220 void wxDebugMsg( const char *format
, ... )
1223 va_start( ap
, format
);
1224 vfprintf( stderr
, format
, ap
);
1229 void wxError( const wxString
&msg
, const wxString
&title
)
1231 wxFprintf( stderr
, _("Error ") );
1232 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
1233 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
1234 wxFprintf( stderr
, wxT(".\n") );
1237 void wxFatalError( const wxString
&msg
, const wxString
&title
)
1239 wxFprintf( stderr
, _("Error ") );
1240 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
1241 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
1242 wxFprintf( stderr
, wxT(".\n") );
1243 exit(3); // the same exit code as for abort()
1246 #endif // WXWIN_COMPATIBILITY_2_2