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/wfstream.h"
44 #include "wx/private/selectdispatcher.h"
45 #include "wx/private/fdiodispatcher.h"
46 #include "wx/unix/execute.h"
47 #include "wx/unix/private.h"
49 #ifdef wxHAS_GENERIC_PROCESS_CALLBACK
50 #include "wx/private/fdiodispatcher.h"
54 #include <sys/wait.h> // waitpid()
56 #ifdef HAVE_SYS_SELECT_H
57 # include <sys/select.h>
60 #define HAS_PIPE_INPUT_STREAM (wxUSE_STREAMS && wxUSE_FILE)
62 #if HAS_PIPE_INPUT_STREAM
64 // define this to let wxexec.cpp know that we know what we're doing
65 #define _WX_USED_BY_WXEXECUTE_
66 #include "../common/execcmn.cpp"
68 #endif // HAS_PIPE_INPUT_STREAM
70 #if defined(__MWERKS__) && defined(__MACH__)
71 #ifndef WXWIN_OS_DESCRIPTION
72 #define WXWIN_OS_DESCRIPTION "MacOS X"
74 #ifndef HAVE_NANOSLEEP
75 #define HAVE_NANOSLEEP
81 // our configure test believes we can use sigaction() if the function is
82 // available but Metrowekrs with MSL run-time does have the function but
83 // doesn't have sigaction struct so finally we can't use it...
85 #undef wxUSE_ON_FATAL_EXCEPTION
86 #define wxUSE_ON_FATAL_EXCEPTION 0
90 // not only the statfs syscall is called differently depending on platform, but
91 // one of its incarnations, statvfs(), takes different arguments under
92 // different platforms and even different versions of the same system (Solaris
93 // 7 and 8): if you want to test for this, don't forget that the problems only
94 // appear if the large files support is enabled
97 #include <sys/param.h>
98 #include <sys/mount.h>
101 #endif // __BSD__/!__BSD__
103 #define wxStatfs statfs
105 #ifndef HAVE_STATFS_DECL
106 // some systems lack statfs() prototype in the system headers (AIX 4)
107 extern "C" int statfs(const char *path
, struct statfs
*buf
);
109 #endif // HAVE_STATFS
112 #include <sys/statvfs.h>
114 #define wxStatfs statvfs
115 #endif // HAVE_STATVFS
117 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
118 // WX_STATFS_T is detected by configure
119 #define wxStatfs_t WX_STATFS_T
122 // SGI signal.h defines signal handler arguments differently depending on
123 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
124 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
125 #define _LANGUAGE_C_PLUS_PLUS 1
131 #include <sys/stat.h>
132 #include <sys/types.h>
133 #include <sys/wait.h>
138 #include <fcntl.h> // for O_WRONLY and friends
139 #include <time.h> // nanosleep() and/or usleep()
140 #include <ctype.h> // isspace()
141 #include <sys/time.h> // needed for FD_SETSIZE
144 #include <sys/utsname.h> // for uname()
147 // Used by wxGetFreeMemory().
149 #include <sys/sysmp.h>
150 #include <sys/sysinfo.h> // for SAGET and MINFO structures
153 // ----------------------------------------------------------------------------
154 // conditional compilation
155 // ----------------------------------------------------------------------------
157 // many versions of Unices have this function, but it is not defined in system
158 // headers - please add your system here if it is the case for your OS.
159 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
160 #if !defined(HAVE_USLEEP) && \
161 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
162 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
163 defined(__osf__) || defined(__EMX__))
167 /* I copied this from the XFree86 diffs. AV. */
168 #define INCL_DOSPROCESS
170 inline void usleep(unsigned long delay
)
172 DosSleep(delay
? (delay
/1000l) : 1l);
175 int usleep(unsigned int usec
);
176 #endif // __EMX__/Unix
179 #define HAVE_USLEEP 1
180 #endif // Unices without usleep()
182 // ============================================================================
184 // ============================================================================
186 // ----------------------------------------------------------------------------
188 // ----------------------------------------------------------------------------
190 void wxSleep(int nSecs
)
195 void wxMicroSleep(unsigned long microseconds
)
197 #if defined(HAVE_NANOSLEEP)
199 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
200 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
202 // we're not interested in remaining time nor in return value
203 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
204 #elif defined(HAVE_USLEEP)
205 // uncomment this if you feel brave or if you are sure that your version
206 // of Solaris has a safe usleep() function but please notice that usleep()
207 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
208 // documented as MT-Safe
209 #if defined(__SUN__) && wxUSE_THREADS
210 #error "usleep() cannot be used in MT programs under Solaris."
213 usleep(microseconds
);
214 #elif defined(HAVE_SLEEP)
215 // under BeOS sleep() takes seconds (what about other platforms, if any?)
216 sleep(microseconds
* 1000000);
217 #else // !sleep function
218 #error "usleep() or nanosleep() function required for wxMicroSleep"
219 #endif // sleep function
222 void wxMilliSleep(unsigned long milliseconds
)
224 wxMicroSleep(milliseconds
*1000);
227 // ----------------------------------------------------------------------------
228 // process management
229 // ----------------------------------------------------------------------------
231 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
233 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
236 switch ( err
? errno
: 0 )
243 *rc
= wxKILL_BAD_SIGNAL
;
247 *rc
= wxKILL_ACCESS_DENIED
;
251 *rc
= wxKILL_NO_PROCESS
;
255 // this goes against Unix98 docs so log it
256 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
266 // Shutdown or reboot the PC
267 bool wxShutdown(wxShutdownFlags wFlags
)
272 case wxSHUTDOWN_POWEROFF
:
276 case wxSHUTDOWN_REBOOT
:
281 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
285 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
288 // ----------------------------------------------------------------------------
289 // wxStream classes to support IO redirection in wxExecute
290 // ----------------------------------------------------------------------------
292 #if HAS_PIPE_INPUT_STREAM
294 bool wxPipeInputStream::CanRead() const
296 if ( m_lasterror
== wxSTREAM_EOF
)
299 // check if there is any input available
304 const int fd
= m_file
->fd();
309 wxFD_SET(fd
, &readfds
);
311 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
314 wxLogSysError(_("Impossible to get child process input"));
321 wxFAIL_MSG(_T("unexpected select() return value"));
322 // still fall through
325 // input available -- or maybe not, as select() returns 1 when a
326 // read() will complete without delay, but it could still not read
332 #endif // HAS_PIPE_INPUT_STREAM
334 // ----------------------------------------------------------------------------
336 // ----------------------------------------------------------------------------
338 static wxString
wxMakeShellCommand(const wxString
& command
)
343 // just an interactive shell
348 // execute command in a shell
349 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
355 bool wxShell(const wxString
& command
)
357 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
360 bool wxShell(const wxString
& command
, wxArrayString
& output
)
362 wxCHECK_MSG( !command
.empty(), false, _T("can't exec shell non interactively") );
364 return wxExecute(wxMakeShellCommand(command
), output
);
370 // helper class for storing arguments as char** array suitable for passing to
371 // execvp(), whatever form they were passed to us
375 ArgsArray(const wxArrayString
& args
)
379 for ( int i
= 0; i
< m_argc
; i
++ )
381 m_argv
[i
] = wxStrdup(args
[i
]);
386 ArgsArray(wchar_t **wargv
)
394 for ( int i
= 0; i
< m_argc
; i
++ )
396 m_argv
[i
] = wxSafeConvertWX2MB(wargv
[i
]).release();
399 #endif // wxUSE_UNICODE
403 for ( int i
= 0; i
< m_argc
; i
++ )
411 operator char**() const { return m_argv
; }
417 m_argv
= new char *[m_argc
+ 1];
418 m_argv
[m_argc
] = NULL
;
424 DECLARE_NO_COPY_CLASS(ArgsArray
);
427 } // anonymous namespace
429 // ----------------------------------------------------------------------------
430 // wxExecute implementations
431 // ----------------------------------------------------------------------------
433 #if defined(__DARWIN__)
434 bool wxMacLaunch(char **argv
);
437 long wxExecute(const wxString
& command
, int flags
, wxProcess
*process
)
441 const char *cptr
= command
.c_str();
443 // split the command line in arguments
445 // TODO: combine this with wxCmdLineParser::ConvertStringToArgs(), it
446 // doesn't do exactly the same thing right now but it's pretty close
447 // and we shouldn't maintain 2 copies of this code
451 char quotechar
= '\0'; // is arg quoted?
452 bool escaped
= false;
454 // eat leading whitespace:
455 while ( wxIsspace(*cptr
) )
458 if ( *cptr
== '\'' || *cptr
== '"' )
463 if ( *cptr
== '\\' && !escaped
)
470 // all other characters:
474 // have we reached the end of the argument?
475 if ( (*cptr
== quotechar
&& !escaped
)
476 || (quotechar
== '\0' && wxIsspace(*cptr
))
479 args
.push_back(argument
);
481 // if not at end of buffer, swallow last character:
485 break; // done with this one, start over
490 ArgsArray
argv(args
);
492 // do execute the command
493 return wxExecute(argv
, flags
, process
);
498 long wxExecute(wchar_t **wargv
, int flags
, wxProcess
*process
)
500 ArgsArray
argv(wargv
);
502 return wxExecute(argv
, flags
, process
);
505 #endif // wxUSE_UNICODE
507 // wxExecute: the real worker function
508 long wxExecute(char **argv
, int flags
, wxProcess
*process
)
510 // for the sync execution, we return -1 to indicate failure, but for async
511 // case we return 0 which is never a valid PID
513 // we define this as a macro, not a variable, to avoid compiler warnings
514 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
515 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
517 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
520 // fork() doesn't mix well with POSIX threads: on many systems the program
521 // deadlocks or crashes for some reason. Probably our code is buggy and
522 // doesn't do something which must be done to allow this to work, but I
523 // don't know what yet, so for now just warn the user (this is the least we
525 wxASSERT_MSG( wxThread::IsMain(),
526 _T("wxExecute() can be called only from the main thread") );
527 #endif // wxUSE_THREADS
529 #if defined(__DARWIN__)
530 // wxMacLaunch() only executes app bundles and only does it asynchronously.
531 // It returns false if the target is not an app bundle, thus falling
532 // through to the regular code for non app bundles.
533 if ( !(flags
& wxEXEC_SYNC
) && wxMacLaunch(argv
) )
535 // we don't have any PID to return so just make up something non null
541 // this struct contains all information which we use for housekeeping
542 wxExecuteData execData
;
543 execData
.flags
= flags
;
544 execData
.process
= process
;
547 if ( !execData
.pipeEndProcDetect
.Create() )
549 wxLogError( _("Failed to execute '%s'\n"), *argv
);
551 return ERROR_RETURN_CODE
;
554 // pipes for inter process communication
555 wxPipe pipeIn
, // stdin
559 if ( process
&& process
->IsRedirected() )
561 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
563 wxLogError( _("Failed to execute '%s'\n"), *argv
);
565 return ERROR_RETURN_CODE
;
571 // NB: do *not* use vfork() here, it completely breaks this code for some
572 // reason under Solaris (and maybe others, although not under Linux)
573 // But on OpenVMS we do not have fork so we have to use vfork and
574 // cross our fingers that it works.
580 if ( pid
== -1 ) // error?
582 wxLogSysError( _("Fork failed") );
584 return ERROR_RETURN_CODE
;
586 else if ( pid
== 0 ) // we're in child
588 // These lines close the open file descriptors to to avoid any
589 // input/output which might block the process or irritate the user. If
590 // one wants proper IO for the subprocess, the right thing to do is to
591 // start an xterm executing it.
592 if ( !(flags
& wxEXEC_SYNC
) )
594 // FD_SETSIZE is unsigned under BSD, signed under other platforms
595 // so we need a cast to avoid warnings on all platforms
596 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
598 if ( fd
== pipeIn
[wxPipe::Read
]
599 || fd
== pipeOut
[wxPipe::Write
]
600 || fd
== pipeErr
[wxPipe::Write
]
601 || fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
] )
603 // don't close this one, we still need it
607 // leave stderr opened too, it won't do any harm
608 if ( fd
!= STDERR_FILENO
)
613 #if !defined(__VMS) && !defined(__EMX__)
614 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
616 // Set process group to child process' pid. Then killing -pid
617 // of the parent will kill the process and all of its children.
622 // reading side can be safely closed but we should keep the write one
623 // opened, it will be only closed when the process terminates resulting
624 // in a read notification to the parent
625 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
626 execData
.pipeEndProcDetect
.Close();
628 // redirect stdin, stdout and stderr
631 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
632 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
633 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
635 wxLogSysError(_("Failed to redirect child process input/output"));
645 fprintf(stderr
, "execvp(");
646 for ( char **a
= argv
; *a
; a
++ )
647 fprintf(stderr
, "%s%s", a
== argv
? "" : ", ", *a
);
648 fprintf(stderr
, ") failed with error %d!\n", errno
);
650 // there is no return after successful exec()
653 // some compilers complain about missing return - of course, they
654 // should know that exit() doesn't return but what else can we do if
657 // and, sure enough, other compilers complain about unreachable code
658 // after exit() call, so we can just always have return here...
659 #if defined(__VMS) || defined(__INTEL_COMPILER)
663 else // we're in parent
665 // save it for WaitForChild() use
668 // prepare for IO redirection
670 #if HAS_PIPE_INPUT_STREAM
671 // the input buffer bufOut is connected to stdout, this is why it is
672 // called bufOut and not bufIn
673 wxStreamTempInputBuffer bufOut
,
676 if ( process
&& process
->IsRedirected() )
678 wxOutputStream
*inStream
=
679 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
681 const int fdOut
= pipeOut
.Detach(wxPipe::Read
);
682 wxPipeInputStream
*outStream
= new wxPipeInputStream(fdOut
);
684 const int fdErr
= pipeErr
.Detach(wxPipe::Read
);
685 wxPipeInputStream
*errStream
= new wxPipeInputStream(fdErr
);
687 process
->SetPipeStreams(outStream
, inStream
, errStream
);
689 bufOut
.Init(outStream
);
690 bufErr
.Init(errStream
);
692 execData
.bufOut
= &bufOut
;
693 execData
.bufErr
= &bufErr
;
695 execData
.fdOut
= fdOut
;
696 execData
.fdErr
= fdErr
;
698 #endif // HAS_PIPE_INPUT_STREAM
707 // we want this function to work even if there is no wxApp so ensure
708 // that we have a valid traits pointer
709 wxConsoleAppTraits traitsConsole
;
710 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
712 traits
= &traitsConsole
;
714 return traits
->WaitForChild(execData
);
717 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
718 return ERROR_RETURN_CODE
;
722 #undef ERROR_RETURN_CODE
724 // ----------------------------------------------------------------------------
725 // file and directory functions
726 // ----------------------------------------------------------------------------
728 const wxChar
* wxGetHomeDir( wxString
*home
)
730 *home
= wxGetUserHome();
736 if ( tmp
.Last() != wxT(']'))
737 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
739 return home
->c_str();
742 wxString
wxGetUserHome( const wxString
&user
)
744 struct passwd
*who
= (struct passwd
*) NULL
;
750 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
755 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
||
756 (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
758 who
= getpwnam(wxSafeConvertWX2MB(ptr
));
761 // make sure the user exists!
764 who
= getpwuid(getuid());
769 who
= getpwnam (user
.mb_str());
772 return wxSafeConvertMB2WX(who
? who
->pw_dir
: 0);
775 // ----------------------------------------------------------------------------
776 // network and user id routines
777 // ----------------------------------------------------------------------------
779 // private utility function which returns output of the given command, removing
780 // the trailing newline
781 static wxString
wxGetCommandOutput(const wxString
&cmd
)
783 FILE *f
= popen(cmd
.ToAscii(), "r");
786 wxLogSysError(_T("Executing \"%s\" failed"), cmd
.c_str());
787 return wxEmptyString
;
794 if ( !fgets(buf
, sizeof(buf
), f
) )
797 s
+= wxString::FromAscii(buf
);
802 if ( !s
.empty() && s
.Last() == _T('\n') )
808 // retrieve either the hostname or FQDN depending on platform (caller must
809 // check whether it's one or the other, this is why this function is for
811 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
813 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
817 // we're using uname() which is POSIX instead of less standard sysinfo()
818 #if defined(HAVE_UNAME)
820 bool ok
= uname(&uts
) != -1;
823 wxStrncpy(buf
, wxSafeConvertMB2WX(uts
.nodename
), sz
- 1);
826 #elif defined(HAVE_GETHOSTNAME)
828 bool ok
= gethostname(cbuf
, sz
) != -1;
831 wxStrncpy(buf
, wxSafeConvertMB2WX(cbuf
), sz
- 1);
834 #else // no uname, no gethostname
835 wxFAIL_MSG(wxT("don't know host name for this machine"));
838 #endif // uname/gethostname
842 wxLogSysError(_("Cannot get the hostname"));
848 bool wxGetHostName(wxChar
*buf
, int sz
)
850 bool ok
= wxGetHostNameInternal(buf
, sz
);
854 // BSD systems return the FQDN, we only want the hostname, so extract
855 // it (we consider that dots are domain separators)
856 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
867 bool wxGetFullHostName(wxChar
*buf
, int sz
)
869 bool ok
= wxGetHostNameInternal(buf
, sz
);
873 if ( !wxStrchr(buf
, wxT('.')) )
875 struct hostent
*host
= gethostbyname(wxSafeConvertWX2MB(buf
));
878 wxLogSysError(_("Cannot get the official hostname"));
884 // the canonical name
885 wxStrncpy(buf
, wxSafeConvertMB2WX(host
->h_name
), sz
);
888 //else: it's already a FQDN (BSD behaves this way)
894 bool wxGetUserId(wxChar
*buf
, int sz
)
899 if ((who
= getpwuid(getuid ())) != NULL
)
901 wxStrncpy (buf
, wxSafeConvertMB2WX(who
->pw_name
), sz
- 1);
908 bool wxGetUserName(wxChar
*buf
, int sz
)
914 if ((who
= getpwuid (getuid ())) != NULL
)
916 char *comma
= strchr(who
->pw_gecos
, ',');
918 *comma
= '\0'; // cut off non-name comment fields
919 wxStrncpy (buf
, wxSafeConvertMB2WX(who
->pw_gecos
), sz
- 1);
924 #else // !HAVE_PW_GECOS
925 return wxGetUserId(buf
, sz
);
926 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
929 bool wxIsPlatform64Bit()
931 const wxString machine
= wxGetCommandOutput(wxT("uname -m"));
933 // the test for "64" is obviously not 100% reliable but seems to work fine
935 return machine
.Contains(wxT("64")) ||
936 machine
.Contains(wxT("alpha"));
939 // these functions are in mac/utils.cpp for wxMac
942 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
946 wxString release
= wxGetCommandOutput(wxT("uname -r"));
947 if ( release
.empty() ||
948 wxSscanf(release
.c_str(), wxT("%d.%d"), &major
, &minor
) != 2 )
950 // failed to get version string or unrecognized format
960 // try to understand which OS are we running
961 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
962 if ( kernel
.empty() )
963 kernel
= wxGetCommandOutput(wxT("uname -o"));
965 if ( kernel
.empty() )
968 return wxPlatformInfo::GetOperatingSystemId(kernel
);
971 wxString
wxGetOsDescription()
973 return wxGetCommandOutput(wxT("uname -s -r -m"));
978 unsigned long wxGetProcessId()
980 return (unsigned long)getpid();
983 wxMemorySize
wxGetFreeMemory()
985 #if defined(__LINUX__)
986 // get it from /proc/meminfo
987 FILE *fp
= fopen("/proc/meminfo", "r");
993 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
995 // /proc/meminfo changed its format in kernel 2.6
996 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
998 unsigned long cached
, buffers
;
999 sscanf(buf
, "MemFree: %ld", &memFree
);
1001 fgets(buf
, WXSIZEOF(buf
), fp
);
1002 sscanf(buf
, "Buffers: %lu", &buffers
);
1004 fgets(buf
, WXSIZEOF(buf
), fp
);
1005 sscanf(buf
, "Cached: %lu", &cached
);
1007 // add to "MemFree" also the "Buffers" and "Cached" values as
1008 // free(1) does as otherwise the value never makes sense: for
1009 // kernel 2.6 it's always almost 0
1010 memFree
+= buffers
+ cached
;
1012 // values here are always expressed in kB and we want bytes
1015 else // Linux 2.4 (or < 2.6, anyhow)
1017 long memTotal
, memUsed
;
1018 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
1024 return (wxMemorySize
)memFree
;
1026 #elif defined(__SGI__)
1027 struct rminfo realmem
;
1028 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
1029 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
1030 #elif defined(_SC_AVPHYS_PAGES)
1031 return ((wxMemorySize
)sysconf(_SC_AVPHYS_PAGES
))*sysconf(_SC_PAGESIZE
);
1032 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1035 // can't find it out
1039 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
1041 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1042 // the case to "char *" is needed for AIX 4.3
1044 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
1046 wxLogSysError( wxT("Failed to get file system statistics") );
1051 // under Solaris we also have to use f_frsize field instead of f_bsize
1052 // which is in general a multiple of f_frsize
1054 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1055 #else // HAVE_STATFS
1056 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1057 #endif // HAVE_STATVFS/HAVE_STATFS
1061 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1066 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1070 #else // !HAVE_STATFS && !HAVE_STATVFS
1072 #endif // HAVE_STATFS
1075 // ----------------------------------------------------------------------------
1077 // ----------------------------------------------------------------------------
1081 WX_DECLARE_STRING_HASH_MAP(char *, wxEnvVars
);
1083 static wxEnvVars gs_envVars
;
1085 class wxSetEnvModule
: public wxModule
1088 virtual bool OnInit() { return true; }
1089 virtual void OnExit()
1091 for ( wxEnvVars::const_iterator i
= gs_envVars
.begin();
1092 i
!= gs_envVars
.end();
1101 DECLARE_DYNAMIC_CLASS(wxSetEnvModule
)
1104 IMPLEMENT_DYNAMIC_CLASS(wxSetEnvModule
, wxModule
)
1106 #endif // USE_PUTENV
1108 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1110 // wxGetenv is defined as getenv()
1111 char *p
= wxGetenv(var
);
1123 static bool wxDoSetEnv(const wxString
& variable
, const char *value
)
1125 #if defined(HAVE_SETENV)
1128 #ifdef HAVE_UNSETENV
1129 // don't test unsetenv() return value: it's void on some systems (at
1131 unsetenv(variable
.mb_str());
1134 value
= ""; // we can't pass NULL to setenv()
1138 return setenv(variable
.mb_str(), value
, 1 /* overwrite */) == 0;
1139 #elif defined(HAVE_PUTENV)
1140 wxString s
= variable
;
1142 s
<< _T('=') << value
;
1144 // transform to ANSI
1145 const wxWX2MBbuf p
= s
.mb_str();
1147 char *buf
= (char *)malloc(strlen(p
) + 1);
1150 // store the string to free() it later
1151 wxEnvVars::iterator i
= gs_envVars
.find(variable
);
1152 if ( i
!= gs_envVars
.end() )
1157 else // this variable hadn't been set before
1159 gs_envVars
[variable
] = buf
;
1162 return putenv(buf
) == 0;
1163 #else // no way to set an env var
1168 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
1170 return wxDoSetEnv(variable
, value
.mb_str());
1173 bool wxUnsetEnv(const wxString
& variable
)
1175 return wxDoSetEnv(variable
, NULL
);
1178 // ----------------------------------------------------------------------------
1180 // ----------------------------------------------------------------------------
1182 #if wxUSE_ON_FATAL_EXCEPTION
1186 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1190 // give the user a chance to do something special about this
1191 wxTheApp
->OnFatalException();
1197 bool wxHandleFatalExceptions(bool doit
)
1200 static bool s_savedHandlers
= false;
1201 static struct sigaction s_handlerFPE
,
1207 if ( doit
&& !s_savedHandlers
)
1209 // install the signal handler
1210 struct sigaction act
;
1212 // some systems extend it with non std fields, so zero everything
1213 memset(&act
, 0, sizeof(act
));
1215 act
.sa_handler
= wxFatalSignalHandler
;
1216 sigemptyset(&act
.sa_mask
);
1219 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1220 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1221 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1222 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1225 wxLogDebug(_T("Failed to install our signal handler."));
1228 s_savedHandlers
= true;
1230 else if ( s_savedHandlers
)
1232 // uninstall the signal handler
1233 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1234 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1235 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1236 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1239 wxLogDebug(_T("Failed to uninstall our signal handler."));
1242 s_savedHandlers
= false;
1244 //else: nothing to do
1249 #endif // wxUSE_ON_FATAL_EXCEPTION
1251 // ----------------------------------------------------------------------------
1252 // wxExecute support
1253 // ----------------------------------------------------------------------------
1255 int wxAppTraits::AddProcessCallback(wxEndProcessData
*data
, int fd
)
1257 // define a custom handler processing only the closure of the descriptor
1258 struct wxEndProcessFDIOHandler
: public wxFDIOHandler
1260 wxEndProcessFDIOHandler(wxEndProcessData
*data
, int fd
)
1261 : m_data(data
), m_fd(fd
)
1265 virtual void OnReadWaiting()
1267 wxFDIODispatcher::Get()->UnregisterFD(m_fd
);
1270 wxHandleProcessTermination(m_data
);
1275 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1276 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1278 wxEndProcessData
* const m_data
;
1282 wxFDIODispatcher::Get()->RegisterFD
1285 new wxEndProcessFDIOHandler(data
, fd
),
1288 return fd
; // unused, but return something unique for the tag
1291 bool wxAppTraits::CheckForRedirectedIO(wxExecuteData
& execData
)
1293 #if HAS_PIPE_INPUT_STREAM
1296 if ( execData
.bufOut
&& execData
.bufOut
->Update() )
1299 if ( execData
.bufErr
&& execData
.bufErr
->Update() )
1303 #else // !HAS_PIPE_INPUT_STREAM
1305 #endif // HAS_PIPE_INPUT_STREAM/!HAS_PIPE_INPUT_STREAM
1308 // helper classes/functions used by WaitForChild()
1312 // convenient base class for IO handlers which are registered for read
1313 // notifications only and which also stores the FD we're reading from
1315 // the derived classes still have to implement OnReadWaiting()
1316 class wxReadFDIOHandler
: public wxFDIOHandler
1319 wxReadFDIOHandler(wxFDIODispatcher
& disp
, int fd
) : m_fd(fd
)
1322 disp
.RegisterFD(fd
, this, wxFDIO_INPUT
);
1325 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1326 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1331 DECLARE_NO_COPY_CLASS(wxReadFDIOHandler
)
1334 // class for monitoring our end of the process detection pipe, simply sets a
1335 // flag when input on the pipe (which must be due to EOF) is detected
1336 class wxEndHandler
: public wxReadFDIOHandler
1339 wxEndHandler(wxFDIODispatcher
& disp
, int fd
)
1340 : wxReadFDIOHandler(disp
, fd
)
1342 m_terminated
= false;
1345 bool Terminated() const { return m_terminated
; }
1347 virtual void OnReadWaiting() { m_terminated
= true; }
1352 DECLARE_NO_COPY_CLASS(wxEndHandler
)
1357 // class for monitoring our ends of child stdout/err, should be constructed
1358 // with the FD and stream from wxExecuteData and will do nothing if they're
1361 // unlike wxEndHandler this class registers itself with the provided dispatcher
1362 class wxRedirectedIOHandler
: public wxReadFDIOHandler
1365 wxRedirectedIOHandler(wxFDIODispatcher
& disp
,
1367 wxStreamTempInputBuffer
*buf
)
1368 : wxReadFDIOHandler(disp
, fd
),
1373 virtual void OnReadWaiting()
1379 wxStreamTempInputBuffer
* const m_buf
;
1381 DECLARE_NO_COPY_CLASS(wxRedirectedIOHandler
)
1384 #endif // wxUSE_STREAMS
1386 // helper function which calls waitpid() and analyzes the result
1387 int DoWaitForChild(int pid
, int flags
= 0)
1389 wxASSERT_MSG( pid
> 0, "invalid PID" );
1393 // loop while we're getting EINTR
1396 rc
= waitpid(pid
, &status
, flags
);
1398 if ( rc
!= -1 || errno
!= EINTR
)
1404 // This can only happen if the child application closes our dummy pipe
1405 // that is used to monitor its lifetime; in that case, our best bet is
1406 // to pretend the process did terminate, because otherwise wxExecute()
1407 // would hang indefinitely (OnReadWaiting() won't be called again, the
1408 // descriptor is closed now).
1409 wxLogDebug("Child process (PID %d) still alive but pipe closed so "
1410 "generating a close notification", pid
);
1412 else if ( rc
== -1 )
1414 wxLogLastError(wxString::Format("waitpid(%d)", pid
));
1416 else // child did terminate
1418 wxASSERT_MSG( rc
== pid
, "unexpected waitpid() return value" );
1420 if ( WIFEXITED(status
) )
1421 return WEXITSTATUS(status
);
1422 else if ( WIFSIGNALED(status
) )
1423 return -WTERMSIG(status
);
1426 wxLogError("Child process (PID %d) exited for unknown reason, "
1427 "status = %d", pid
, status
);
1434 } // anonymous namespace
1436 int wxAppTraits::WaitForChild(wxExecuteData
& execData
)
1438 if ( !(execData
.flags
& wxEXEC_SYNC
) )
1440 // asynchronous execution: just launch the process and return,
1441 // endProcData will be destroyed when it terminates (currently we leak
1442 // it if the process doesn't terminate before we do and this should be
1443 // fixed but it's not a real leak so it's not really very high
1445 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1446 endProcData
->process
= execData
.process
;
1447 endProcData
->pid
= execData
.pid
;
1448 endProcData
->tag
= AddProcessCallback
1451 execData
.GetEndProcReadFD()
1453 endProcData
->async
= true;
1455 return execData
.pid
;
1457 //else: synchronous execution case
1460 wxProcess
* const process
= execData
.process
;
1461 if ( process
&& process
->IsRedirected() )
1463 // we can't simply block waiting for the child to terminate as we would
1464 // dead lock if it writes more than the pipe buffer size (typically
1465 // 4KB) bytes of output -- it would then block waiting for us to read
1466 // the data while we'd block waiting for it to terminate
1468 // so multiplex here waiting for any input from the child or closure of
1469 // the pipe used to indicate its termination
1470 wxSelectDispatcher disp
;
1472 wxEndHandler
endHandler(disp
, execData
.GetEndProcReadFD());
1474 wxRedirectedIOHandler
outHandler(disp
, execData
.fdOut
, execData
.bufOut
),
1475 errHandler(disp
, execData
.fdErr
, execData
.bufErr
);
1477 while ( !endHandler
.Terminated() )
1482 //else: no IO redirection, just block waiting for the child to exit
1483 #endif // wxUSE_STREAMS
1485 return DoWaitForChild(execData
.pid
);
1488 void wxHandleProcessTermination(wxEndProcessData
*data
)
1490 data
->exitcode
= DoWaitForChild(data
->pid
, WNOHANG
);
1492 // notify user about termination if required
1493 if ( data
->process
)
1495 data
->process
->OnTerminate(data
->pid
, data
->exitcode
);
1500 // in case of asynchronous execution we don't need this data any more
1501 // after the child terminates
1504 else // sync execution
1506 // let wxExecute() know that the process has terminated