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 // ----------------------------------------------------------------------------
19 #include "wx/string.h"
26 #include "wx/process.h"
27 #include "wx/thread.h"
29 #include "wx/wfstream.h"
31 // not only the statfs syscall is called differently depending on platform, but
32 // one of its incarnations, statvfs(), takes different arguments under
33 // different platforms and even different versions of the same system (Solaris
34 // 7 and 8): if you want to test for this, don't forget that the problems only
35 // appear if the large files support is enabled
38 #include <sys/param.h>
39 #include <sys/mount.h>
42 #endif // __BSD__/!__BSD__
44 #define wxStatfs statfs
48 #include <sys/statvfs.h>
50 #define wxStatfs statvfs
51 #endif // HAVE_STATVFS
53 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
54 // WX_STATFS_T is detected by configure
55 #define wxStatfs_t WX_STATFS_T
59 #include "wx/unix/execute.h"
62 // SGI signal.h defines signal handler arguments differently depending on
63 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
64 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
65 #define _LANGUAGE_C_PLUS_PLUS 1
72 #include <sys/types.h>
79 #include <fcntl.h> // for O_WRONLY and friends
80 #include <time.h> // nanosleep() and/or usleep()
81 #include <ctype.h> // isspace()
82 #include <sys/time.h> // needed for FD_SETSIZE
85 #include <sys/utsname.h> // for uname()
88 // ----------------------------------------------------------------------------
89 // conditional compilation
90 // ----------------------------------------------------------------------------
92 // many versions of Unices have this function, but it is not defined in system
93 // headers - please add your system here if it is the case for your OS.
94 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
95 #if !defined(HAVE_USLEEP) && \
96 (defined(__SUN__) && !defined(__SunOs_5_6) && \
97 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
98 defined(__osf__) || defined(__EMX__)
102 int usleep(unsigned int usec
);
105 /* I copied this from the XFree86 diffs. AV. */
106 #define INCL_DOSPROCESS
108 inline void usleep(unsigned long delay
)
110 DosSleep(delay
? (delay
/1000l) : 1l);
112 #else // !Sun && !EMX
113 void usleep(unsigned long usec
);
115 #endif // Sun/EMX/Something else
118 #define HAVE_USLEEP 1
119 #endif // Unices without usleep()
121 // ============================================================================
123 // ============================================================================
125 // ----------------------------------------------------------------------------
127 // ----------------------------------------------------------------------------
129 void wxSleep(int nSecs
)
134 void wxUsleep(unsigned long milliseconds
)
136 #if defined(HAVE_NANOSLEEP)
138 tmReq
.tv_sec
= (time_t)(milliseconds
/ 1000);
139 tmReq
.tv_nsec
= (milliseconds
% 1000) * 1000 * 1000;
141 // we're not interested in remaining time nor in return value
142 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
143 #elif defined(HAVE_USLEEP)
144 // uncomment this if you feel brave or if you are sure that your version
145 // of Solaris has a safe usleep() function but please notice that usleep()
146 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
147 // documented as MT-Safe
148 #if defined(__SUN__) && wxUSE_THREADS
149 #error "usleep() cannot be used in MT programs under Solaris."
152 usleep(milliseconds
* 1000); // usleep(3) wants microseconds
153 #elif defined(HAVE_SLEEP)
154 // under BeOS sleep() takes seconds (what about other platforms, if any?)
155 sleep(milliseconds
* 1000);
156 #else // !sleep function
157 #error "usleep() or nanosleep() function required for wxUsleep"
158 #endif // sleep function
161 // ----------------------------------------------------------------------------
162 // process management
163 // ----------------------------------------------------------------------------
165 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
)
167 int err
= kill((pid_t
)pid
, (int)sig
);
177 *rc
= wxKILL_BAD_SIGNAL
;
181 *rc
= wxKILL_ACCESS_DENIED
;
185 *rc
= wxKILL_NO_PROCESS
;
189 // this goes against Unix98 docs so log it
190 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
200 #define WXEXECUTE_NARGS 127
202 long wxExecute( const wxString
& command
, int flags
, wxProcess
*process
)
204 wxCHECK_MSG( !command
.IsEmpty(), 0, wxT("can't exec empty command") );
207 // fork() doesn't mix well with POSIX threads: on many systems the program
208 // deadlocks or crashes for some reason. Probably our code is buggy and
209 // doesn't do something which must be done to allow this to work, but I
210 // don't know what yet, so for now just warn the user (this is the least we
212 wxASSERT_MSG( wxThread::IsMain(),
213 _T("wxExecute() can be called only from the main thread") );
214 #endif // wxUSE_THREADS
217 wxChar
*argv
[WXEXECUTE_NARGS
];
219 const wxChar
*cptr
= command
.c_str();
220 wxChar quotechar
= wxT('\0'); // is arg quoted?
221 bool escaped
= FALSE
;
223 // split the command line in arguments
227 quotechar
= wxT('\0');
229 // eat leading whitespace:
230 while ( wxIsspace(*cptr
) )
233 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
238 if ( *cptr
== wxT('\\') && ! escaped
)
245 // all other characters:
249 // have we reached the end of the argument?
250 if ( (*cptr
== quotechar
&& ! escaped
)
251 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
252 || *cptr
== wxT('\0') )
254 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
255 wxT("too many arguments in wxExecute") );
257 argv
[argc
] = new wxChar
[argument
.length() + 1];
258 wxStrcpy(argv
[argc
], argument
.c_str());
261 // if not at end of buffer, swallow last character:
265 break; // done with this one, start over
271 // do execute the command
272 long lRc
= wxExecute(argv
, flags
, process
);
277 delete [] argv
[argc
++];
282 // ----------------------------------------------------------------------------
284 // ----------------------------------------------------------------------------
286 static wxString
wxMakeShellCommand(const wxString
& command
)
291 // just an interactive shell
296 // execute command in a shell
297 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
303 bool wxShell(const wxString
& command
)
305 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
308 bool wxShell(const wxString
& command
, wxArrayString
& output
)
310 wxCHECK_MSG( !!command
, FALSE
, _T("can't exec shell non interactively") );
312 return wxExecute(wxMakeShellCommand(command
), output
);
315 // Shutdown or reboot the PC
316 bool wxShutdown(wxShutdownFlags wFlags
)
321 case wxSHUTDOWN_POWEROFF
:
325 case wxSHUTDOWN_REBOOT
:
330 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
334 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
340 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
342 // notify user about termination if required
343 if ( proc_data
->process
)
345 proc_data
->process
->OnTerminate(proc_data
->pid
, proc_data
->exitcode
);
349 if ( proc_data
->pid
> 0 )
355 // let wxExecute() know that the process has terminated
362 // ----------------------------------------------------------------------------
363 // wxStream classes to support IO redirection in wxExecute
364 // ----------------------------------------------------------------------------
368 // ----------------------------------------------------------------------------
369 // wxPipeInputStream: stream for reading from a pipe
370 // ----------------------------------------------------------------------------
372 class wxPipeInputStream
: public wxFileInputStream
375 wxPipeInputStream(int fd
) : wxFileInputStream(fd
) { }
377 // return TRUE if the pipe is still opened
378 bool IsOpened() const { return !Eof(); }
380 // return TRUE if we have anything to read, don't block
381 virtual bool CanRead() const;
384 bool wxPipeInputStream::CanRead() const
386 if ( m_lasterror
== wxSTREAM_EOF
)
389 // check if there is any input available
394 const int fd
= m_file
->fd();
398 FD_SET(fd
, &readfds
);
399 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
402 wxLogSysError(_("Impossible to get child process input"));
409 wxFAIL_MSG(_T("unexpected select() return value"));
410 // still fall through
413 // input available -- or maybe not, as select() returns 1 when a
414 // read() will complete without delay, but it could still not read
420 // define this to let wxexec.cpp know that we know what we're doing
421 #define _WX_USED_BY_WXEXECUTE_
422 #include "../common/execcmn.cpp"
424 #endif // wxUSE_STREAMS
426 // ----------------------------------------------------------------------------
427 // wxPipe: this encapsulates pipe() system call
428 // ----------------------------------------------------------------------------
433 // the symbolic names for the pipe ends
445 // default ctor doesn't do anything
446 wxPipe() { m_fds
[Read
] = m_fds
[Write
] = INVALID_FD
; }
448 // create the pipe, return TRUE if ok, FALSE on error
451 if ( pipe(m_fds
) == -1 )
453 wxLogSysError(_("Pipe creation failed"));
461 // return TRUE if we were created successfully
462 bool IsOk() const { return m_fds
[Read
] != INVALID_FD
; }
464 // return the descriptor for one of the pipe ends
465 int operator[](Direction which
) const
467 wxASSERT_MSG( which
>= 0 && (size_t)which
< WXSIZEOF(m_fds
),
468 _T("invalid pipe index") );
473 // detach a descriptor, meaning that the pipe dtor won't close it, and
475 int Detach(Direction which
)
477 wxASSERT_MSG( which
>= 0 && (size_t)which
< WXSIZEOF(m_fds
),
478 _T("invalid pipe index") );
480 int fd
= m_fds
[which
];
481 m_fds
[which
] = INVALID_FD
;
486 // close the pipe descriptors
489 for ( size_t n
= 0; n
< WXSIZEOF(m_fds
); n
++ )
491 if ( m_fds
[n
] != INVALID_FD
)
496 // dtor closes the pipe descriptors
497 ~wxPipe() { Close(); }
503 // ----------------------------------------------------------------------------
504 // wxExecute: the real worker function
505 // ----------------------------------------------------------------------------
508 #pragma message disable codeunreachable
511 long wxExecute(wxChar
**argv
,
515 // for the sync execution, we return -1 to indicate failure, but for async
516 // case we return 0 which is never a valid PID
518 // we define this as a macro, not a variable, to avoid compiler warnings
519 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
520 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
522 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
526 char *mb_argv
[WXEXECUTE_NARGS
];
528 while (argv
[mb_argc
])
530 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
531 mb_argv
[mb_argc
] = strdup(mb_arg
);
534 mb_argv
[mb_argc
] = (char *) NULL
;
536 // this macro will free memory we used above
537 #define ARGS_CLEANUP \
538 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
539 free(mb_argv[mb_argc])
541 // no need for cleanup
544 wxChar
**mb_argv
= argv
;
545 #endif // Unicode/ANSI
549 wxPipe pipeEndProcDetect
;
550 if ( !pipeEndProcDetect
.Create() )
552 wxLogError( _("Failed to execute '%s'\n"), *argv
);
556 return ERROR_RETURN_CODE
;
560 // pipes for inter process communication
561 wxPipe pipeIn
, // stdin
565 if ( process
&& process
->IsRedirected() )
567 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
569 wxLogError( _("Failed to execute '%s'\n"), *argv
);
573 return ERROR_RETURN_CODE
;
579 // NB: do *not* use vfork() here, it completely breaks this code for some
580 // reason under Solaris (and maybe others, although not under Linux)
581 // But on OpenVMS we do not have fork so we have to use vfork and
582 // cross our fingers that it works.
588 if ( pid
== -1 ) // error?
590 wxLogSysError( _("Fork failed") );
594 return ERROR_RETURN_CODE
;
596 else if ( pid
== 0 ) // we're in child
598 // These lines close the open file descriptors to to avoid any
599 // input/output which might block the process or irritate the user. If
600 // one wants proper IO for the subprocess, the right thing to do is to
601 // start an xterm executing it.
602 if ( !(flags
& wxEXEC_SYNC
) )
604 for ( int fd
= 0; fd
< FD_SETSIZE
; fd
++ )
606 if ( fd
== pipeIn
[wxPipe::Read
]
607 || fd
== pipeOut
[wxPipe::Write
]
608 || fd
== pipeErr
[wxPipe::Write
]
610 || fd
== pipeEndProcDetect
[wxPipe::Write
]
614 // don't close this one, we still need it
618 // leave stderr opened too, it won't do any harm
619 if ( fd
!= STDERR_FILENO
)
624 #if !defined(__VMS) && !defined(__EMX__)
625 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
627 // Set process group to child process' pid. Then killing -pid
628 // of the parent will kill the process and all of its children.
634 // reading side can be safely closed but we should keep the write one
636 pipeEndProcDetect
.Detach(wxPipe::Write
);
637 pipeEndProcDetect
.Close();
640 // redirect stdin, stdout and stderr
643 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
644 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
645 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
647 wxLogSysError(_("Failed to redirect child process input/output"));
655 execvp (*mb_argv
, mb_argv
);
657 fprintf(stderr
, "execvp(");
658 for ( char **ppc
= mb_argv
; *ppc
; ppc
++ )
659 fprintf(stderr
, "%s%s", ppc
== mb_argv
? "" : ", ", *ppc
);
660 fprintf(stderr
, ") failed with error %d!\n", errno
);
662 // there is no return after successful exec()
665 // some compilers complain about missing return - of course, they
666 // should know that exit() doesn't return but what else can we do if
669 // and, sure enough, other compilers complain about unreachable code
670 // after exit() call, so we can just always have return here...
671 #if defined(__VMS) || defined(__INTEL_COMPILER)
675 else // we're in parent
679 // prepare for IO redirection
682 // the input buffer bufOut is connected to stdout, this is why it is
683 // called bufOut and not bufIn
684 wxStreamTempInputBuffer bufOut
,
686 #endif // wxUSE_STREAMS
688 if ( process
&& process
->IsRedirected() )
691 wxOutputStream
*inStream
=
692 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
694 wxPipeInputStream
*outStream
=
695 new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
697 wxPipeInputStream
*errStream
=
698 new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
700 process
->SetPipeStreams(outStream
, inStream
, errStream
);
702 bufOut
.Init(outStream
);
703 bufErr
.Init(errStream
);
704 #endif // wxUSE_STREAMS
714 #if wxUSE_GUI && !defined(__WXMICROWIN__)
715 wxEndProcessData
*data
= new wxEndProcessData
;
717 data
->tag
= wxAddProcessCallback
720 pipeEndProcDetect
.Detach(wxPipe::Read
)
723 pipeEndProcDetect
.Close();
725 if ( flags
& wxEXEC_SYNC
)
727 // we may have process for capturing the program output, but it's
728 // not used in wxEndProcessData in the case of sync execution
729 data
->process
= NULL
;
731 // sync execution: indicate it by negating the pid
737 // data->pid will be set to 0 from GTK_EndProcessDetector when the
738 // process terminates
739 while ( data
->pid
!= 0 )
744 #endif // wxUSE_STREAMS
746 // give GTK+ a chance to call GTK_EndProcessDetector here and
747 // also repaint the GUI
751 int exitcode
= data
->exitcode
;
757 else // async execution
759 // async execution, nothing special to do - caller will be
760 // notified about the process termination if process != NULL, data
761 // will be deleted in GTK_EndProcessDetector
762 data
->process
= process
;
769 wxASSERT_MSG( flags
& wxEXEC_SYNC
,
770 wxT("async execution not supported yet") );
773 if ( waitpid(pid
, &exitcode
, 0) == -1 || !WIFEXITED(exitcode
) )
775 wxLogSysError(_("Waiting for subprocess termination failed"));
782 return ERROR_RETURN_CODE
;
786 #pragma message enable codeunreachable
789 #undef ERROR_RETURN_CODE
792 // ----------------------------------------------------------------------------
793 // file and directory functions
794 // ----------------------------------------------------------------------------
796 const wxChar
* wxGetHomeDir( wxString
*home
)
798 *home
= wxGetUserHome( wxString() );
800 if ( home
->IsEmpty() )
804 if ( tmp
.Last() != wxT(']'))
805 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
807 return home
->c_str();
811 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
812 #else // just for binary compatibility -- there is no 'const' here
813 char *wxGetUserHome( const wxString
&user
)
816 struct passwd
*who
= (struct passwd
*) NULL
;
822 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
825 wxWCharBuffer
buffer( ptr
);
831 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
833 who
= getpwnam(wxConvertWX2MB(ptr
));
836 // We now make sure the the user exists!
839 who
= getpwuid(getuid());
844 who
= getpwnam (user
.mb_str());
847 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
850 // ----------------------------------------------------------------------------
851 // network and user id routines
852 // ----------------------------------------------------------------------------
854 // retrieve either the hostname or FQDN depending on platform (caller must
855 // check whether it's one or the other, this is why this function is for
857 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
859 wxCHECK_MSG( buf
, FALSE
, wxT("NULL pointer in wxGetHostNameInternal") );
863 // we're using uname() which is POSIX instead of less standard sysinfo()
864 #if defined(HAVE_UNAME)
866 bool ok
= uname(&uts
) != -1;
869 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
872 #elif defined(HAVE_GETHOSTNAME)
873 bool ok
= gethostname(buf
, sz
) != -1;
874 #else // no uname, no gethostname
875 wxFAIL_MSG(wxT("don't know host name for this machine"));
878 #endif // uname/gethostname
882 wxLogSysError(_("Cannot get the hostname"));
888 bool wxGetHostName(wxChar
*buf
, int sz
)
890 bool ok
= wxGetHostNameInternal(buf
, sz
);
894 // BSD systems return the FQDN, we only want the hostname, so extract
895 // it (we consider that dots are domain separators)
896 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
907 bool wxGetFullHostName(wxChar
*buf
, int sz
)
909 bool ok
= wxGetHostNameInternal(buf
, sz
);
913 if ( !wxStrchr(buf
, wxT('.')) )
915 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
918 wxLogSysError(_("Cannot get the official hostname"));
924 // the canonical name
925 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
928 //else: it's already a FQDN (BSD behaves this way)
934 bool wxGetUserId(wxChar
*buf
, int sz
)
939 if ((who
= getpwuid(getuid ())) != NULL
)
941 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
948 bool wxGetUserName(wxChar
*buf
, int sz
)
953 if ((who
= getpwuid (getuid ())) != NULL
)
955 // pw_gecos field in struct passwd is not standard
957 char *comma
= strchr(who
->pw_gecos
, ',');
959 *comma
= '\0'; // cut off non-name comment fields
960 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
961 #else // !HAVE_PW_GECOS
962 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
963 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
971 wxString
wxGetOsDescription()
973 #ifndef WXWIN_OS_DESCRIPTION
974 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
976 return wxString::FromAscii( WXWIN_OS_DESCRIPTION
);
981 // this function returns the GUI toolkit version in GUI programs, but OS
982 // version in non-GUI ones
985 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
990 if ( sscanf(WXWIN_OS_DESCRIPTION
, "%s %d.%d", name
, &major
, &minor
) != 3 )
992 // unreckognized uname string format
1004 #endif // !wxUSE_GUI
1006 unsigned long wxGetProcessId()
1008 return (unsigned long)getpid();
1011 long wxGetFreeMemory()
1013 #if defined(__LINUX__)
1014 // get it from /proc/meminfo
1015 FILE *fp
= fopen("/proc/meminfo", "r");
1021 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
1023 long memTotal
, memUsed
;
1024 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
1031 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
1032 return sysconf(_SC_AVPHYS_PAGES
)*sysconf(_SC_PAGESIZE
);
1033 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1036 // can't find it out
1040 bool wxGetDiskSpace(const wxString
& path
, wxLongLong
*pTotal
, wxLongLong
*pFree
)
1042 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1043 // the case to "char *" is needed for AIX 4.3
1045 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
1047 wxLogSysError( wxT("Failed to get file system statistics") );
1052 // under Solaris we also have to use f_frsize field instead of f_bsize
1053 // which is in general a multiple of f_frsize
1055 wxLongLong blockSize
= fs
.f_frsize
;
1056 #else // HAVE_STATFS
1057 wxLongLong blockSize
= fs
.f_bsize
;
1058 #endif // HAVE_STATVFS/HAVE_STATFS
1062 *pTotal
= wxLongLong(fs
.f_blocks
) * blockSize
;
1067 *pFree
= wxLongLong(fs
.f_bavail
) * blockSize
;
1071 #else // !HAVE_STATFS && !HAVE_STATVFS
1073 #endif // HAVE_STATFS
1076 // ----------------------------------------------------------------------------
1078 // ----------------------------------------------------------------------------
1080 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1082 // wxGetenv is defined as getenv()
1083 wxChar
*p
= wxGetenv(var
);
1095 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
1097 #if defined(HAVE_SETENV)
1098 return setenv(variable
.mb_str(),
1099 value
? (const char *)wxString(value
).mb_str()
1101 1 /* overwrite */) == 0;
1102 #elif defined(HAVE_PUTENV)
1103 wxString s
= variable
;
1105 s
<< _T('=') << value
;
1107 // transform to ANSI
1108 const char *p
= s
.mb_str();
1110 // the string will be free()d by libc
1111 char *buf
= (char *)malloc(strlen(p
) + 1);
1114 return putenv(buf
) == 0;
1115 #else // no way to set an env var
1120 // ----------------------------------------------------------------------------
1122 // ----------------------------------------------------------------------------
1124 #if wxUSE_ON_FATAL_EXCEPTION
1128 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1132 // give the user a chance to do something special about this
1133 wxTheApp
->OnFatalException();
1139 bool wxHandleFatalExceptions(bool doit
)
1142 static bool s_savedHandlers
= FALSE
;
1143 static struct sigaction s_handlerFPE
,
1149 if ( doit
&& !s_savedHandlers
)
1151 // install the signal handler
1152 struct sigaction act
;
1154 // some systems extend it with non std fields, so zero everything
1155 memset(&act
, 0, sizeof(act
));
1157 act
.sa_handler
= wxFatalSignalHandler
;
1158 sigemptyset(&act
.sa_mask
);
1161 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1162 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1163 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1164 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1167 wxLogDebug(_T("Failed to install our signal handler."));
1170 s_savedHandlers
= TRUE
;
1172 else if ( s_savedHandlers
)
1174 // uninstall the signal handler
1175 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1176 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1177 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1178 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1181 wxLogDebug(_T("Failed to uninstall our signal handler."));
1184 s_savedHandlers
= FALSE
;
1186 //else: nothing to do
1191 #endif // wxUSE_ON_FATAL_EXCEPTION
1193 // ----------------------------------------------------------------------------
1194 // error and debug output routines (deprecated, use wxLog)
1195 // ----------------------------------------------------------------------------
1197 #if WXWIN_COMPATIBILITY_2_2
1199 void wxDebugMsg( const char *format
, ... )
1202 va_start( ap
, format
);
1203 vfprintf( stderr
, format
, ap
);
1208 void wxError( const wxString
&msg
, const wxString
&title
)
1210 wxFprintf( stderr
, _("Error ") );
1211 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
1212 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
1213 wxFprintf( stderr
, wxT(".\n") );
1216 void wxFatalError( const wxString
&msg
, const wxString
&title
)
1218 wxFprintf( stderr
, _("Error ") );
1219 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
1220 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
1221 wxFprintf( stderr
, wxT(".\n") );
1222 exit(3); // the same exit code as for abort()
1225 #endif // WXWIN_COMPATIBILITY_2_2