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"
23 #define USE_PUTENV (!defined(HAVE_SETENV) && defined(HAVE_PUTENV))
26 #include "wx/string.h"
30 #include "wx/wxcrtvararg.h"
32 #include "wx/module.h"
33 #include "wx/hashmap.h"
37 #include "wx/apptrait.h"
39 #include "wx/process.h"
40 #include "wx/thread.h"
42 #include "wx/cmdline.h"
44 #include "wx/wfstream.h"
46 #include "wx/private/selectdispatcher.h"
47 #include "wx/private/fdiodispatcher.h"
48 #include "wx/unix/execute.h"
49 #include "wx/unix/private.h"
51 #ifdef wxHAS_GENERIC_PROCESS_CALLBACK
52 #include "wx/private/fdiodispatcher.h"
56 #include <sys/wait.h> // waitpid()
58 #ifdef HAVE_SYS_SELECT_H
59 # include <sys/select.h>
62 #define HAS_PIPE_INPUT_STREAM (wxUSE_STREAMS && wxUSE_FILE)
64 #if HAS_PIPE_INPUT_STREAM
66 // define this to let wxexec.cpp know that we know what we're doing
67 #define _WX_USED_BY_WXEXECUTE_
68 #include "../common/execcmn.cpp"
70 #endif // HAS_PIPE_INPUT_STREAM
72 #if defined(__MWERKS__) && defined(__MACH__)
73 #ifndef WXWIN_OS_DESCRIPTION
74 #define WXWIN_OS_DESCRIPTION "MacOS X"
76 #ifndef HAVE_NANOSLEEP
77 #define HAVE_NANOSLEEP
83 // our configure test believes we can use sigaction() if the function is
84 // available but Metrowekrs with MSL run-time does have the function but
85 // doesn't have sigaction struct so finally we can't use it...
87 #undef wxUSE_ON_FATAL_EXCEPTION
88 #define wxUSE_ON_FATAL_EXCEPTION 0
92 // not only the statfs syscall is called differently depending on platform, but
93 // one of its incarnations, statvfs(), takes different arguments under
94 // different platforms and even different versions of the same system (Solaris
95 // 7 and 8): if you want to test for this, don't forget that the problems only
96 // appear if the large files support is enabled
99 #include <sys/param.h>
100 #include <sys/mount.h>
103 #endif // __BSD__/!__BSD__
105 #define wxStatfs statfs
107 #ifndef HAVE_STATFS_DECL
108 // some systems lack statfs() prototype in the system headers (AIX 4)
109 extern "C" int statfs(const char *path
, struct statfs
*buf
);
111 #endif // HAVE_STATFS
114 #include <sys/statvfs.h>
116 #define wxStatfs statvfs
117 #endif // HAVE_STATVFS
119 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
120 // WX_STATFS_T is detected by configure
121 #define wxStatfs_t WX_STATFS_T
124 // SGI signal.h defines signal handler arguments differently depending on
125 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
126 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
127 #define _LANGUAGE_C_PLUS_PLUS 1
133 #include <sys/stat.h>
134 #include <sys/types.h>
135 #include <sys/wait.h>
140 #include <fcntl.h> // for O_WRONLY and friends
141 #include <time.h> // nanosleep() and/or usleep()
142 #include <ctype.h> // isspace()
143 #include <sys/time.h> // needed for FD_SETSIZE
146 #include <sys/utsname.h> // for uname()
149 // Used by wxGetFreeMemory().
151 #include <sys/sysmp.h>
152 #include <sys/sysinfo.h> // for SAGET and MINFO structures
155 // ----------------------------------------------------------------------------
156 // conditional compilation
157 // ----------------------------------------------------------------------------
159 // many versions of Unices have this function, but it is not defined in system
160 // headers - please add your system here if it is the case for your OS.
161 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
162 #if !defined(HAVE_USLEEP) && \
163 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
164 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
165 defined(__osf__) || defined(__EMX__))
169 /* I copied this from the XFree86 diffs. AV. */
170 #define INCL_DOSPROCESS
172 inline void usleep(unsigned long delay
)
174 DosSleep(delay
? (delay
/1000l) : 1l);
177 int usleep(unsigned int usec
);
178 #endif // __EMX__/Unix
181 #define HAVE_USLEEP 1
182 #endif // Unices without usleep()
184 // ============================================================================
186 // ============================================================================
188 // ----------------------------------------------------------------------------
190 // ----------------------------------------------------------------------------
192 void wxSleep(int nSecs
)
197 void wxMicroSleep(unsigned long microseconds
)
199 #if defined(HAVE_NANOSLEEP)
201 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
202 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
204 // we're not interested in remaining time nor in return value
205 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
206 #elif defined(HAVE_USLEEP)
207 // uncomment this if you feel brave or if you are sure that your version
208 // of Solaris has a safe usleep() function but please notice that usleep()
209 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
210 // documented as MT-Safe
211 #if defined(__SUN__) && wxUSE_THREADS
212 #error "usleep() cannot be used in MT programs under Solaris."
215 usleep(microseconds
);
216 #elif defined(HAVE_SLEEP)
217 // under BeOS sleep() takes seconds (what about other platforms, if any?)
218 sleep(microseconds
* 1000000);
219 #else // !sleep function
220 #error "usleep() or nanosleep() function required for wxMicroSleep"
221 #endif // sleep function
224 void wxMilliSleep(unsigned long milliseconds
)
226 wxMicroSleep(milliseconds
*1000);
229 // ----------------------------------------------------------------------------
230 // process management
231 // ----------------------------------------------------------------------------
233 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
235 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
238 switch ( err
? errno
: 0 )
245 *rc
= wxKILL_BAD_SIGNAL
;
249 *rc
= wxKILL_ACCESS_DENIED
;
253 *rc
= wxKILL_NO_PROCESS
;
257 // this goes against Unix98 docs so log it
258 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
268 // Shutdown or reboot the PC
269 bool wxShutdown(wxShutdownFlags wFlags
)
274 case wxSHUTDOWN_POWEROFF
:
278 case wxSHUTDOWN_REBOOT
:
283 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
287 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
290 // ----------------------------------------------------------------------------
291 // wxStream classes to support IO redirection in wxExecute
292 // ----------------------------------------------------------------------------
294 #if HAS_PIPE_INPUT_STREAM
296 bool wxPipeInputStream::CanRead() const
298 if ( m_lasterror
== wxSTREAM_EOF
)
301 // check if there is any input available
306 const int fd
= m_file
->fd();
311 wxFD_SET(fd
, &readfds
);
313 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
316 wxLogSysError(_("Impossible to get child process input"));
323 wxFAIL_MSG(_T("unexpected select() return value"));
324 // still fall through
327 // input available -- or maybe not, as select() returns 1 when a
328 // read() will complete without delay, but it could still not read
334 #endif // HAS_PIPE_INPUT_STREAM
336 // ----------------------------------------------------------------------------
338 // ----------------------------------------------------------------------------
340 static wxString
wxMakeShellCommand(const wxString
& command
)
345 // just an interactive shell
350 // execute command in a shell
351 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
357 bool wxShell(const wxString
& command
)
359 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
362 bool wxShell(const wxString
& command
, wxArrayString
& output
)
364 wxCHECK_MSG( !command
.empty(), false, _T("can't exec shell non interactively") );
366 return wxExecute(wxMakeShellCommand(command
), output
);
372 // helper class for storing arguments as char** array suitable for passing to
373 // execvp(), whatever form they were passed to us
377 ArgsArray(const wxArrayString
& args
)
381 for ( int i
= 0; i
< m_argc
; i
++ )
383 m_argv
[i
] = wxStrdup(args
[i
]);
388 ArgsArray(wchar_t **wargv
)
396 for ( int i
= 0; i
< m_argc
; i
++ )
398 m_argv
[i
] = wxSafeConvertWX2MB(wargv
[i
]).release();
401 #endif // wxUSE_UNICODE
405 for ( int i
= 0; i
< m_argc
; i
++ )
413 operator char**() const { return m_argv
; }
419 m_argv
= new char *[m_argc
+ 1];
420 m_argv
[m_argc
] = NULL
;
426 DECLARE_NO_COPY_CLASS(ArgsArray
)
429 } // anonymous namespace
431 // ----------------------------------------------------------------------------
432 // wxExecute implementations
433 // ----------------------------------------------------------------------------
435 #if defined(__DARWIN__)
436 bool wxMacLaunch(char **argv
);
439 long wxExecute(const wxString
& command
, int flags
, wxProcess
*process
)
441 ArgsArray
argv(wxCmdLineParser::ConvertStringToArgs(command
,
442 wxCMD_LINE_SPLIT_UNIX
));
444 return wxExecute(argv
, flags
, process
);
449 long wxExecute(wchar_t **wargv
, int flags
, wxProcess
*process
)
451 ArgsArray
argv(wargv
);
453 return wxExecute(argv
, flags
, process
);
456 #endif // wxUSE_UNICODE
458 // wxExecute: the real worker function
459 long wxExecute(char **argv
, int flags
, wxProcess
*process
)
461 // for the sync execution, we return -1 to indicate failure, but for async
462 // case we return 0 which is never a valid PID
464 // we define this as a macro, not a variable, to avoid compiler warnings
465 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
466 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
468 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
471 // fork() doesn't mix well with POSIX threads: on many systems the program
472 // deadlocks or crashes for some reason. Probably our code is buggy and
473 // doesn't do something which must be done to allow this to work, but I
474 // don't know what yet, so for now just warn the user (this is the least we
476 wxASSERT_MSG( wxThread::IsMain(),
477 _T("wxExecute() can be called only from the main thread") );
478 #endif // wxUSE_THREADS
480 #if defined(__DARWIN__)
481 // wxMacLaunch() only executes app bundles and only does it asynchronously.
482 // It returns false if the target is not an app bundle, thus falling
483 // through to the regular code for non app bundles.
484 if ( !(flags
& wxEXEC_SYNC
) && wxMacLaunch(argv
) )
486 // we don't have any PID to return so just make up something non null
492 // this struct contains all information which we use for housekeeping
493 wxExecuteData execData
;
494 execData
.flags
= flags
;
495 execData
.process
= process
;
498 if ( !execData
.pipeEndProcDetect
.Create() )
500 wxLogError( _("Failed to execute '%s'\n"), *argv
);
502 return ERROR_RETURN_CODE
;
505 // pipes for inter process communication
506 wxPipe pipeIn
, // stdin
510 if ( process
&& process
->IsRedirected() )
512 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
514 wxLogError( _("Failed to execute '%s'\n"), *argv
);
516 return ERROR_RETURN_CODE
;
522 // NB: do *not* use vfork() here, it completely breaks this code for some
523 // reason under Solaris (and maybe others, although not under Linux)
524 // But on OpenVMS we do not have fork so we have to use vfork and
525 // cross our fingers that it works.
531 if ( pid
== -1 ) // error?
533 wxLogSysError( _("Fork failed") );
535 return ERROR_RETURN_CODE
;
537 else if ( pid
== 0 ) // we're in child
539 // These lines close the open file descriptors to to avoid any
540 // input/output which might block the process or irritate the user. If
541 // one wants proper IO for the subprocess, the right thing to do is to
542 // start an xterm executing it.
543 if ( !(flags
& wxEXEC_SYNC
) )
545 // FD_SETSIZE is unsigned under BSD, signed under other platforms
546 // so we need a cast to avoid warnings on all platforms
547 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
549 if ( fd
== pipeIn
[wxPipe::Read
]
550 || fd
== pipeOut
[wxPipe::Write
]
551 || fd
== pipeErr
[wxPipe::Write
]
552 || fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
] )
554 // don't close this one, we still need it
558 // leave stderr opened too, it won't do any harm
559 if ( fd
!= STDERR_FILENO
)
564 #if !defined(__VMS) && !defined(__EMX__)
565 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
567 // Set process group to child process' pid. Then killing -pid
568 // of the parent will kill the process and all of its children.
573 // reading side can be safely closed but we should keep the write one
574 // opened, it will be only closed when the process terminates resulting
575 // in a read notification to the parent
576 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
577 execData
.pipeEndProcDetect
.Close();
579 // redirect stdin, stdout and stderr
582 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
583 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
584 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
586 wxLogSysError(_("Failed to redirect child process input/output"));
596 fprintf(stderr
, "execvp(");
597 for ( char **a
= argv
; *a
; a
++ )
598 fprintf(stderr
, "%s%s", a
== argv
? "" : ", ", *a
);
599 fprintf(stderr
, ") failed with error %d!\n", errno
);
601 // there is no return after successful exec()
604 // some compilers complain about missing return - of course, they
605 // should know that exit() doesn't return but what else can we do if
608 // and, sure enough, other compilers complain about unreachable code
609 // after exit() call, so we can just always have return here...
610 #if defined(__VMS) || defined(__INTEL_COMPILER)
614 else // we're in parent
616 // save it for WaitForChild() use
619 // prepare for IO redirection
621 #if HAS_PIPE_INPUT_STREAM
622 // the input buffer bufOut is connected to stdout, this is why it is
623 // called bufOut and not bufIn
624 wxStreamTempInputBuffer bufOut
,
627 if ( process
&& process
->IsRedirected() )
629 wxOutputStream
*inStream
=
630 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
632 const int fdOut
= pipeOut
.Detach(wxPipe::Read
);
633 wxPipeInputStream
*outStream
= new wxPipeInputStream(fdOut
);
635 const int fdErr
= pipeErr
.Detach(wxPipe::Read
);
636 wxPipeInputStream
*errStream
= new wxPipeInputStream(fdErr
);
638 process
->SetPipeStreams(outStream
, inStream
, errStream
);
640 bufOut
.Init(outStream
);
641 bufErr
.Init(errStream
);
643 execData
.bufOut
= &bufOut
;
644 execData
.bufErr
= &bufErr
;
646 execData
.fdOut
= fdOut
;
647 execData
.fdErr
= fdErr
;
649 #endif // HAS_PIPE_INPUT_STREAM
658 // we want this function to work even if there is no wxApp so ensure
659 // that we have a valid traits pointer
660 wxConsoleAppTraits traitsConsole
;
661 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
663 traits
= &traitsConsole
;
665 return traits
->WaitForChild(execData
);
668 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
669 return ERROR_RETURN_CODE
;
673 #undef ERROR_RETURN_CODE
675 // ----------------------------------------------------------------------------
676 // file and directory functions
677 // ----------------------------------------------------------------------------
679 const wxChar
* wxGetHomeDir( wxString
*home
)
681 *home
= wxGetUserHome();
687 if ( tmp
.Last() != wxT(']'))
688 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
690 return home
->c_str();
693 wxString
wxGetUserHome( const wxString
&user
)
695 struct passwd
*who
= (struct passwd
*) NULL
;
701 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
706 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
||
707 (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
709 who
= getpwnam(wxSafeConvertWX2MB(ptr
));
712 // make sure the user exists!
715 who
= getpwuid(getuid());
720 who
= getpwnam (user
.mb_str());
723 return wxSafeConvertMB2WX(who
? who
->pw_dir
: 0);
726 // ----------------------------------------------------------------------------
727 // network and user id routines
728 // ----------------------------------------------------------------------------
730 // private utility function which returns output of the given command, removing
731 // the trailing newline
732 static wxString
wxGetCommandOutput(const wxString
&cmd
)
734 FILE *f
= popen(cmd
.ToAscii(), "r");
737 wxLogSysError(_T("Executing \"%s\" failed"), cmd
.c_str());
738 return wxEmptyString
;
745 if ( !fgets(buf
, sizeof(buf
), f
) )
748 s
+= wxString::FromAscii(buf
);
753 if ( !s
.empty() && s
.Last() == _T('\n') )
759 // retrieve either the hostname or FQDN depending on platform (caller must
760 // check whether it's one or the other, this is why this function is for
762 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
764 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
768 // we're using uname() which is POSIX instead of less standard sysinfo()
769 #if defined(HAVE_UNAME)
771 bool ok
= uname(&uts
) != -1;
774 wxStrncpy(buf
, wxSafeConvertMB2WX(uts
.nodename
), sz
- 1);
777 #elif defined(HAVE_GETHOSTNAME)
779 bool ok
= gethostname(cbuf
, sz
) != -1;
782 wxStrncpy(buf
, wxSafeConvertMB2WX(cbuf
), sz
- 1);
785 #else // no uname, no gethostname
786 wxFAIL_MSG(wxT("don't know host name for this machine"));
789 #endif // uname/gethostname
793 wxLogSysError(_("Cannot get the hostname"));
799 bool wxGetHostName(wxChar
*buf
, int sz
)
801 bool ok
= wxGetHostNameInternal(buf
, sz
);
805 // BSD systems return the FQDN, we only want the hostname, so extract
806 // it (we consider that dots are domain separators)
807 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
818 bool wxGetFullHostName(wxChar
*buf
, int sz
)
820 bool ok
= wxGetHostNameInternal(buf
, sz
);
824 if ( !wxStrchr(buf
, wxT('.')) )
826 struct hostent
*host
= gethostbyname(wxSafeConvertWX2MB(buf
));
829 wxLogSysError(_("Cannot get the official hostname"));
835 // the canonical name
836 wxStrncpy(buf
, wxSafeConvertMB2WX(host
->h_name
), sz
);
839 //else: it's already a FQDN (BSD behaves this way)
845 bool wxGetUserId(wxChar
*buf
, int sz
)
850 if ((who
= getpwuid(getuid ())) != NULL
)
852 wxStrncpy (buf
, wxSafeConvertMB2WX(who
->pw_name
), sz
- 1);
859 bool wxGetUserName(wxChar
*buf
, int sz
)
865 if ((who
= getpwuid (getuid ())) != NULL
)
867 char *comma
= strchr(who
->pw_gecos
, ',');
869 *comma
= '\0'; // cut off non-name comment fields
870 wxStrncpy (buf
, wxSafeConvertMB2WX(who
->pw_gecos
), sz
- 1);
875 #else // !HAVE_PW_GECOS
876 return wxGetUserId(buf
, sz
);
877 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
880 bool wxIsPlatform64Bit()
882 const wxString machine
= wxGetCommandOutput(wxT("uname -m"));
884 // the test for "64" is obviously not 100% reliable but seems to work fine
886 return machine
.Contains(wxT("64")) ||
887 machine
.Contains(wxT("alpha"));
890 // these functions are in mac/utils.cpp for wxMac
893 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
897 wxString release
= wxGetCommandOutput(wxT("uname -r"));
898 if ( release
.empty() ||
899 wxSscanf(release
.c_str(), wxT("%d.%d"), &major
, &minor
) != 2 )
901 // failed to get version string or unrecognized format
911 // try to understand which OS are we running
912 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
913 if ( kernel
.empty() )
914 kernel
= wxGetCommandOutput(wxT("uname -o"));
916 if ( kernel
.empty() )
919 return wxPlatformInfo::GetOperatingSystemId(kernel
);
922 wxString
wxGetOsDescription()
924 return wxGetCommandOutput(wxT("uname -s -r -m"));
929 unsigned long wxGetProcessId()
931 return (unsigned long)getpid();
934 wxMemorySize
wxGetFreeMemory()
936 #if defined(__LINUX__)
937 // get it from /proc/meminfo
938 FILE *fp
= fopen("/proc/meminfo", "r");
944 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
946 // /proc/meminfo changed its format in kernel 2.6
947 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
949 unsigned long cached
, buffers
;
950 sscanf(buf
, "MemFree: %ld", &memFree
);
952 fgets(buf
, WXSIZEOF(buf
), fp
);
953 sscanf(buf
, "Buffers: %lu", &buffers
);
955 fgets(buf
, WXSIZEOF(buf
), fp
);
956 sscanf(buf
, "Cached: %lu", &cached
);
958 // add to "MemFree" also the "Buffers" and "Cached" values as
959 // free(1) does as otherwise the value never makes sense: for
960 // kernel 2.6 it's always almost 0
961 memFree
+= buffers
+ cached
;
963 // values here are always expressed in kB and we want bytes
966 else // Linux 2.4 (or < 2.6, anyhow)
968 long memTotal
, memUsed
;
969 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
975 return (wxMemorySize
)memFree
;
977 #elif defined(__SGI__)
978 struct rminfo realmem
;
979 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
980 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
981 #elif defined(_SC_AVPHYS_PAGES)
982 return ((wxMemorySize
)sysconf(_SC_AVPHYS_PAGES
))*sysconf(_SC_PAGESIZE
);
983 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
990 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
992 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
993 // the case to "char *" is needed for AIX 4.3
995 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
997 wxLogSysError( wxT("Failed to get file system statistics") );
1002 // under Solaris we also have to use f_frsize field instead of f_bsize
1003 // which is in general a multiple of f_frsize
1005 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1006 #else // HAVE_STATFS
1007 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1008 #endif // HAVE_STATVFS/HAVE_STATFS
1012 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1017 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1021 #else // !HAVE_STATFS && !HAVE_STATVFS
1023 #endif // HAVE_STATFS
1026 // ----------------------------------------------------------------------------
1028 // ----------------------------------------------------------------------------
1032 WX_DECLARE_STRING_HASH_MAP(char *, wxEnvVars
);
1034 static wxEnvVars gs_envVars
;
1036 class wxSetEnvModule
: public wxModule
1039 virtual bool OnInit() { return true; }
1040 virtual void OnExit()
1042 for ( wxEnvVars::const_iterator i
= gs_envVars
.begin();
1043 i
!= gs_envVars
.end();
1052 DECLARE_DYNAMIC_CLASS(wxSetEnvModule
)
1055 IMPLEMENT_DYNAMIC_CLASS(wxSetEnvModule
, wxModule
)
1057 #endif // USE_PUTENV
1059 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1061 // wxGetenv is defined as getenv()
1062 char *p
= wxGetenv(var
);
1074 static bool wxDoSetEnv(const wxString
& variable
, const char *value
)
1076 #if defined(HAVE_SETENV)
1079 #ifdef HAVE_UNSETENV
1080 // don't test unsetenv() return value: it's void on some systems (at
1082 unsetenv(variable
.mb_str());
1085 value
= ""; // we can't pass NULL to setenv()
1089 return setenv(variable
.mb_str(), value
, 1 /* overwrite */) == 0;
1090 #elif defined(HAVE_PUTENV)
1091 wxString s
= variable
;
1093 s
<< _T('=') << value
;
1095 // transform to ANSI
1096 const wxWX2MBbuf p
= s
.mb_str();
1098 char *buf
= (char *)malloc(strlen(p
) + 1);
1101 // store the string to free() it later
1102 wxEnvVars::iterator i
= gs_envVars
.find(variable
);
1103 if ( i
!= gs_envVars
.end() )
1108 else // this variable hadn't been set before
1110 gs_envVars
[variable
] = buf
;
1113 return putenv(buf
) == 0;
1114 #else // no way to set an env var
1119 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
1121 return wxDoSetEnv(variable
, value
.mb_str());
1124 bool wxUnsetEnv(const wxString
& variable
)
1126 return wxDoSetEnv(variable
, NULL
);
1129 // ----------------------------------------------------------------------------
1131 // ----------------------------------------------------------------------------
1133 #if wxUSE_ON_FATAL_EXCEPTION
1137 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1141 // give the user a chance to do something special about this
1142 wxTheApp
->OnFatalException();
1148 bool wxHandleFatalExceptions(bool doit
)
1151 static bool s_savedHandlers
= false;
1152 static struct sigaction s_handlerFPE
,
1158 if ( doit
&& !s_savedHandlers
)
1160 // install the signal handler
1161 struct sigaction act
;
1163 // some systems extend it with non std fields, so zero everything
1164 memset(&act
, 0, sizeof(act
));
1166 act
.sa_handler
= wxFatalSignalHandler
;
1167 sigemptyset(&act
.sa_mask
);
1170 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1171 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1172 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1173 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1176 wxLogDebug(_T("Failed to install our signal handler."));
1179 s_savedHandlers
= true;
1181 else if ( s_savedHandlers
)
1183 // uninstall the signal handler
1184 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1185 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1186 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1187 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1190 wxLogDebug(_T("Failed to uninstall our signal handler."));
1193 s_savedHandlers
= false;
1195 //else: nothing to do
1200 #endif // wxUSE_ON_FATAL_EXCEPTION
1202 // ----------------------------------------------------------------------------
1203 // wxExecute support
1204 // ----------------------------------------------------------------------------
1206 int wxAppTraits::AddProcessCallback(wxEndProcessData
*data
, int fd
)
1208 // define a custom handler processing only the closure of the descriptor
1209 struct wxEndProcessFDIOHandler
: public wxFDIOHandler
1211 wxEndProcessFDIOHandler(wxEndProcessData
*data
, int fd
)
1212 : m_data(data
), m_fd(fd
)
1216 virtual void OnReadWaiting()
1218 wxFDIODispatcher::Get()->UnregisterFD(m_fd
);
1221 wxHandleProcessTermination(m_data
);
1226 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1227 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1229 wxEndProcessData
* const m_data
;
1233 wxFDIODispatcher::Get()->RegisterFD
1236 new wxEndProcessFDIOHandler(data
, fd
),
1239 return fd
; // unused, but return something unique for the tag
1242 bool wxAppTraits::CheckForRedirectedIO(wxExecuteData
& execData
)
1244 #if HAS_PIPE_INPUT_STREAM
1247 if ( execData
.bufOut
&& execData
.bufOut
->Update() )
1250 if ( execData
.bufErr
&& execData
.bufErr
->Update() )
1254 #else // !HAS_PIPE_INPUT_STREAM
1256 #endif // HAS_PIPE_INPUT_STREAM/!HAS_PIPE_INPUT_STREAM
1259 // helper classes/functions used by WaitForChild()
1263 // convenient base class for IO handlers which are registered for read
1264 // notifications only and which also stores the FD we're reading from
1266 // the derived classes still have to implement OnReadWaiting()
1267 class wxReadFDIOHandler
: public wxFDIOHandler
1270 wxReadFDIOHandler(wxFDIODispatcher
& disp
, int fd
) : m_fd(fd
)
1273 disp
.RegisterFD(fd
, this, wxFDIO_INPUT
);
1276 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1277 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1282 DECLARE_NO_COPY_CLASS(wxReadFDIOHandler
)
1285 // class for monitoring our end of the process detection pipe, simply sets a
1286 // flag when input on the pipe (which must be due to EOF) is detected
1287 class wxEndHandler
: public wxReadFDIOHandler
1290 wxEndHandler(wxFDIODispatcher
& disp
, int fd
)
1291 : wxReadFDIOHandler(disp
, fd
)
1293 m_terminated
= false;
1296 bool Terminated() const { return m_terminated
; }
1298 virtual void OnReadWaiting() { m_terminated
= true; }
1303 DECLARE_NO_COPY_CLASS(wxEndHandler
)
1308 // class for monitoring our ends of child stdout/err, should be constructed
1309 // with the FD and stream from wxExecuteData and will do nothing if they're
1312 // unlike wxEndHandler this class registers itself with the provided dispatcher
1313 class wxRedirectedIOHandler
: public wxReadFDIOHandler
1316 wxRedirectedIOHandler(wxFDIODispatcher
& disp
,
1318 wxStreamTempInputBuffer
*buf
)
1319 : wxReadFDIOHandler(disp
, fd
),
1324 virtual void OnReadWaiting()
1330 wxStreamTempInputBuffer
* const m_buf
;
1332 DECLARE_NO_COPY_CLASS(wxRedirectedIOHandler
)
1335 #endif // wxUSE_STREAMS
1337 // helper function which calls waitpid() and analyzes the result
1338 int DoWaitForChild(int pid
, int flags
= 0)
1340 wxASSERT_MSG( pid
> 0, "invalid PID" );
1344 // loop while we're getting EINTR
1347 rc
= waitpid(pid
, &status
, flags
);
1349 if ( rc
!= -1 || errno
!= EINTR
)
1355 // This can only happen if the child application closes our dummy pipe
1356 // that is used to monitor its lifetime; in that case, our best bet is
1357 // to pretend the process did terminate, because otherwise wxExecute()
1358 // would hang indefinitely (OnReadWaiting() won't be called again, the
1359 // descriptor is closed now).
1360 wxLogDebug("Child process (PID %d) still alive but pipe closed so "
1361 "generating a close notification", pid
);
1363 else if ( rc
== -1 )
1365 wxLogLastError(wxString::Format("waitpid(%d)", pid
));
1367 else // child did terminate
1369 wxASSERT_MSG( rc
== pid
, "unexpected waitpid() return value" );
1371 if ( WIFEXITED(status
) )
1372 return WEXITSTATUS(status
);
1373 else if ( WIFSIGNALED(status
) )
1374 return -WTERMSIG(status
);
1377 wxLogError("Child process (PID %d) exited for unknown reason, "
1378 "status = %d", pid
, status
);
1385 } // anonymous namespace
1387 int wxAppTraits::WaitForChild(wxExecuteData
& execData
)
1389 if ( !(execData
.flags
& wxEXEC_SYNC
) )
1391 // asynchronous execution: just launch the process and return,
1392 // endProcData will be destroyed when it terminates (currently we leak
1393 // it if the process doesn't terminate before we do and this should be
1394 // fixed but it's not a real leak so it's not really very high
1396 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1397 endProcData
->process
= execData
.process
;
1398 endProcData
->pid
= execData
.pid
;
1399 endProcData
->tag
= AddProcessCallback
1402 execData
.GetEndProcReadFD()
1404 endProcData
->async
= true;
1406 return execData
.pid
;
1408 //else: synchronous execution case
1411 wxProcess
* const process
= execData
.process
;
1412 if ( process
&& process
->IsRedirected() )
1414 // we can't simply block waiting for the child to terminate as we would
1415 // dead lock if it writes more than the pipe buffer size (typically
1416 // 4KB) bytes of output -- it would then block waiting for us to read
1417 // the data while we'd block waiting for it to terminate
1419 // so multiplex here waiting for any input from the child or closure of
1420 // the pipe used to indicate its termination
1421 wxSelectDispatcher disp
;
1423 wxEndHandler
endHandler(disp
, execData
.GetEndProcReadFD());
1425 wxRedirectedIOHandler
outHandler(disp
, execData
.fdOut
, execData
.bufOut
),
1426 errHandler(disp
, execData
.fdErr
, execData
.bufErr
);
1428 while ( !endHandler
.Terminated() )
1433 //else: no IO redirection, just block waiting for the child to exit
1434 #endif // wxUSE_STREAMS
1436 return DoWaitForChild(execData
.pid
);
1439 void wxHandleProcessTermination(wxEndProcessData
*data
)
1441 data
->exitcode
= DoWaitForChild(data
->pid
, WNOHANG
);
1443 // notify user about termination if required
1444 if ( data
->process
)
1446 data
->process
->OnTerminate(data
->pid
, data
->exitcode
);
1451 // in case of asynchronous execution we don't need this data any more
1452 // after the child terminates
1455 else // sync execution
1457 // let wxExecute() know that the process has terminated