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
]);
385 ArgsArray(wchar_t **wargv
)
393 for ( int i
= 0; i
< m_argc
; i
++ )
395 m_argv
[i
] = wxSafeConvertWX2MB(wargv
[i
]).release();
401 for ( int i
= 0; i
< m_argc
; i
++ )
409 operator char**() const { return m_argv
; }
415 m_argv
= new char *[m_argc
+ 1];
416 m_argv
[m_argc
] = NULL
;
422 DECLARE_NO_COPY_CLASS(ArgsArray
);
425 } // anonymous namespace
427 // ----------------------------------------------------------------------------
428 // wxExecute implementations
429 // ----------------------------------------------------------------------------
431 #if defined(__DARWIN__)
432 bool wxMacLaunch(char **argv
);
435 long wxExecute(const wxString
& command
, int flags
, wxProcess
*process
)
439 const char *cptr
= command
.c_str();
441 // split the command line in arguments
443 // TODO: combine this with wxCmdLineParser::ConvertStringToArgs(), it
444 // doesn't do exactly the same thing right now but it's pretty close
445 // and we shouldn't maintain 2 copies of this code
449 char quotechar
= '\0'; // is arg quoted?
450 bool escaped
= false;
452 // eat leading whitespace:
453 while ( wxIsspace(*cptr
) )
456 if ( *cptr
== '\'' || *cptr
== '"' )
461 if ( *cptr
== '\\' && !escaped
)
468 // all other characters:
472 // have we reached the end of the argument?
473 if ( (*cptr
== quotechar
&& !escaped
)
474 || (quotechar
== '\0' && wxIsspace(*cptr
))
477 args
.push_back(argument
);
479 // if not at end of buffer, swallow last character:
483 break; // done with this one, start over
488 ArgsArray
argv(args
);
490 // do execute the command
491 return wxExecute(argv
, flags
, process
);
494 long wxExecute(wchar_t **wargv
, int flags
, wxProcess
*process
)
496 ArgsArray
argv(wargv
);
498 return wxExecute(argv
, flags
, process
);
501 // wxExecute: the real worker function
502 long wxExecute(char **argv
, int flags
, wxProcess
*process
)
504 // for the sync execution, we return -1 to indicate failure, but for async
505 // case we return 0 which is never a valid PID
507 // we define this as a macro, not a variable, to avoid compiler warnings
508 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
509 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
511 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
514 // fork() doesn't mix well with POSIX threads: on many systems the program
515 // deadlocks or crashes for some reason. Probably our code is buggy and
516 // doesn't do something which must be done to allow this to work, but I
517 // don't know what yet, so for now just warn the user (this is the least we
519 wxASSERT_MSG( wxThread::IsMain(),
520 _T("wxExecute() can be called only from the main thread") );
521 #endif // wxUSE_THREADS
523 #if defined(__DARWIN__)
524 // wxMacLaunch() only executes app bundles and only does it asynchronously.
525 // It returns false if the target is not an app bundle, thus falling
526 // through to the regular code for non app bundles.
527 if ( !(flags
& wxEXEC_SYNC
) && wxMacLaunch(argv
) )
529 // we don't have any PID to return so just make up something non null
535 // this struct contains all information which we use for housekeeping
536 wxExecuteData execData
;
537 execData
.flags
= flags
;
538 execData
.process
= process
;
541 if ( !execData
.pipeEndProcDetect
.Create() )
543 wxLogError( _("Failed to execute '%s'\n"), *argv
);
545 return ERROR_RETURN_CODE
;
548 // pipes for inter process communication
549 wxPipe pipeIn
, // stdin
553 if ( process
&& process
->IsRedirected() )
555 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
557 wxLogError( _("Failed to execute '%s'\n"), *argv
);
559 return ERROR_RETURN_CODE
;
565 // NB: do *not* use vfork() here, it completely breaks this code for some
566 // reason under Solaris (and maybe others, although not under Linux)
567 // But on OpenVMS we do not have fork so we have to use vfork and
568 // cross our fingers that it works.
574 if ( pid
== -1 ) // error?
576 wxLogSysError( _("Fork failed") );
578 return ERROR_RETURN_CODE
;
580 else if ( pid
== 0 ) // we're in child
582 // These lines close the open file descriptors to to avoid any
583 // input/output which might block the process or irritate the user. If
584 // one wants proper IO for the subprocess, the right thing to do is to
585 // start an xterm executing it.
586 if ( !(flags
& wxEXEC_SYNC
) )
588 // FD_SETSIZE is unsigned under BSD, signed under other platforms
589 // so we need a cast to avoid warnings on all platforms
590 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
592 if ( fd
== pipeIn
[wxPipe::Read
]
593 || fd
== pipeOut
[wxPipe::Write
]
594 || fd
== pipeErr
[wxPipe::Write
]
595 || fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
] )
597 // don't close this one, we still need it
601 // leave stderr opened too, it won't do any harm
602 if ( fd
!= STDERR_FILENO
)
607 #if !defined(__VMS) && !defined(__EMX__)
608 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
610 // Set process group to child process' pid. Then killing -pid
611 // of the parent will kill the process and all of its children.
616 // reading side can be safely closed but we should keep the write one
617 // opened, it will be only closed when the process terminates resulting
618 // in a read notification to the parent
619 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
620 execData
.pipeEndProcDetect
.Close();
622 // redirect stdin, stdout and stderr
625 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
626 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
627 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
629 wxLogSysError(_("Failed to redirect child process input/output"));
639 fprintf(stderr
, "execvp(");
640 for ( char **a
= argv
; *a
; a
++ )
641 fprintf(stderr
, "%s%s", a
== argv
? "" : ", ", *a
);
642 fprintf(stderr
, ") failed with error %d!\n", errno
);
644 // there is no return after successful exec()
647 // some compilers complain about missing return - of course, they
648 // should know that exit() doesn't return but what else can we do if
651 // and, sure enough, other compilers complain about unreachable code
652 // after exit() call, so we can just always have return here...
653 #if defined(__VMS) || defined(__INTEL_COMPILER)
657 else // we're in parent
659 // save it for WaitForChild() use
662 // prepare for IO redirection
664 #if HAS_PIPE_INPUT_STREAM
665 // the input buffer bufOut is connected to stdout, this is why it is
666 // called bufOut and not bufIn
667 wxStreamTempInputBuffer bufOut
,
670 if ( process
&& process
->IsRedirected() )
672 wxOutputStream
*inStream
=
673 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
675 const int fdOut
= pipeOut
.Detach(wxPipe::Read
);
676 wxPipeInputStream
*outStream
= new wxPipeInputStream(fdOut
);
678 const int fdErr
= pipeErr
.Detach(wxPipe::Read
);
679 wxPipeInputStream
*errStream
= new wxPipeInputStream(fdErr
);
681 process
->SetPipeStreams(outStream
, inStream
, errStream
);
683 bufOut
.Init(outStream
);
684 bufErr
.Init(errStream
);
686 execData
.bufOut
= &bufOut
;
687 execData
.bufErr
= &bufErr
;
689 execData
.fdOut
= fdOut
;
690 execData
.fdErr
= fdErr
;
692 #endif // HAS_PIPE_INPUT_STREAM
701 // we want this function to work even if there is no wxApp so ensure
702 // that we have a valid traits pointer
703 wxConsoleAppTraits traitsConsole
;
704 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
706 traits
= &traitsConsole
;
708 return traits
->WaitForChild(execData
);
711 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
712 return ERROR_RETURN_CODE
;
716 #undef ERROR_RETURN_CODE
718 // ----------------------------------------------------------------------------
719 // file and directory functions
720 // ----------------------------------------------------------------------------
722 const wxChar
* wxGetHomeDir( wxString
*home
)
724 *home
= wxGetUserHome();
730 if ( tmp
.Last() != wxT(']'))
731 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
733 return home
->c_str();
736 wxString
wxGetUserHome( const wxString
&user
)
738 struct passwd
*who
= (struct passwd
*) NULL
;
744 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
749 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
||
750 (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
752 who
= getpwnam(wxSafeConvertWX2MB(ptr
));
755 // make sure the user exists!
758 who
= getpwuid(getuid());
763 who
= getpwnam (user
.mb_str());
766 return wxSafeConvertMB2WX(who
? who
->pw_dir
: 0);
769 // ----------------------------------------------------------------------------
770 // network and user id routines
771 // ----------------------------------------------------------------------------
773 // private utility function which returns output of the given command, removing
774 // the trailing newline
775 static wxString
wxGetCommandOutput(const wxString
&cmd
)
777 FILE *f
= popen(cmd
.ToAscii(), "r");
780 wxLogSysError(_T("Executing \"%s\" failed"), cmd
.c_str());
781 return wxEmptyString
;
788 if ( !fgets(buf
, sizeof(buf
), f
) )
791 s
+= wxString::FromAscii(buf
);
796 if ( !s
.empty() && s
.Last() == _T('\n') )
802 // retrieve either the hostname or FQDN depending on platform (caller must
803 // check whether it's one or the other, this is why this function is for
805 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
807 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
811 // we're using uname() which is POSIX instead of less standard sysinfo()
812 #if defined(HAVE_UNAME)
814 bool ok
= uname(&uts
) != -1;
817 wxStrncpy(buf
, wxSafeConvertMB2WX(uts
.nodename
), sz
- 1);
820 #elif defined(HAVE_GETHOSTNAME)
822 bool ok
= gethostname(cbuf
, sz
) != -1;
825 wxStrncpy(buf
, wxSafeConvertMB2WX(cbuf
), sz
- 1);
828 #else // no uname, no gethostname
829 wxFAIL_MSG(wxT("don't know host name for this machine"));
832 #endif // uname/gethostname
836 wxLogSysError(_("Cannot get the hostname"));
842 bool wxGetHostName(wxChar
*buf
, int sz
)
844 bool ok
= wxGetHostNameInternal(buf
, sz
);
848 // BSD systems return the FQDN, we only want the hostname, so extract
849 // it (we consider that dots are domain separators)
850 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
861 bool wxGetFullHostName(wxChar
*buf
, int sz
)
863 bool ok
= wxGetHostNameInternal(buf
, sz
);
867 if ( !wxStrchr(buf
, wxT('.')) )
869 struct hostent
*host
= gethostbyname(wxSafeConvertWX2MB(buf
));
872 wxLogSysError(_("Cannot get the official hostname"));
878 // the canonical name
879 wxStrncpy(buf
, wxSafeConvertMB2WX(host
->h_name
), sz
);
882 //else: it's already a FQDN (BSD behaves this way)
888 bool wxGetUserId(wxChar
*buf
, int sz
)
893 if ((who
= getpwuid(getuid ())) != NULL
)
895 wxStrncpy (buf
, wxSafeConvertMB2WX(who
->pw_name
), sz
- 1);
902 bool wxGetUserName(wxChar
*buf
, int sz
)
908 if ((who
= getpwuid (getuid ())) != NULL
)
910 char *comma
= strchr(who
->pw_gecos
, ',');
912 *comma
= '\0'; // cut off non-name comment fields
913 wxStrncpy (buf
, wxSafeConvertMB2WX(who
->pw_gecos
), sz
- 1);
918 #else // !HAVE_PW_GECOS
919 return wxGetUserId(buf
, sz
);
920 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
923 bool wxIsPlatform64Bit()
925 const wxString machine
= wxGetCommandOutput(wxT("uname -m"));
927 // the test for "64" is obviously not 100% reliable but seems to work fine
929 return machine
.Contains(wxT("64")) ||
930 machine
.Contains(wxT("alpha"));
933 // these functions are in mac/utils.cpp for wxMac
936 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
940 wxString release
= wxGetCommandOutput(wxT("uname -r"));
941 if ( release
.empty() ||
942 wxSscanf(release
.c_str(), wxT("%d.%d"), &major
, &minor
) != 2 )
944 // failed to get version string or unrecognized format
954 // try to understand which OS are we running
955 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
956 if ( kernel
.empty() )
957 kernel
= wxGetCommandOutput(wxT("uname -o"));
959 if ( kernel
.empty() )
962 return wxPlatformInfo::GetOperatingSystemId(kernel
);
965 wxString
wxGetOsDescription()
967 return wxGetCommandOutput(wxT("uname -s -r -m"));
972 unsigned long wxGetProcessId()
974 return (unsigned long)getpid();
977 wxMemorySize
wxGetFreeMemory()
979 #if defined(__LINUX__)
980 // get it from /proc/meminfo
981 FILE *fp
= fopen("/proc/meminfo", "r");
987 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
989 // /proc/meminfo changed its format in kernel 2.6
990 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
992 unsigned long cached
, buffers
;
993 sscanf(buf
, "MemFree: %ld", &memFree
);
995 fgets(buf
, WXSIZEOF(buf
), fp
);
996 sscanf(buf
, "Buffers: %lu", &buffers
);
998 fgets(buf
, WXSIZEOF(buf
), fp
);
999 sscanf(buf
, "Cached: %lu", &cached
);
1001 // add to "MemFree" also the "Buffers" and "Cached" values as
1002 // free(1) does as otherwise the value never makes sense: for
1003 // kernel 2.6 it's always almost 0
1004 memFree
+= buffers
+ cached
;
1006 // values here are always expressed in kB and we want bytes
1009 else // Linux 2.4 (or < 2.6, anyhow)
1011 long memTotal
, memUsed
;
1012 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
1018 return (wxMemorySize
)memFree
;
1020 #elif defined(__SGI__)
1021 struct rminfo realmem
;
1022 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
1023 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
1024 #elif defined(_SC_AVPHYS_PAGES)
1025 return ((wxMemorySize
)sysconf(_SC_AVPHYS_PAGES
))*sysconf(_SC_PAGESIZE
);
1026 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1029 // can't find it out
1033 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
1035 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1036 // the case to "char *" is needed for AIX 4.3
1038 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
1040 wxLogSysError( wxT("Failed to get file system statistics") );
1045 // under Solaris we also have to use f_frsize field instead of f_bsize
1046 // which is in general a multiple of f_frsize
1048 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1049 #else // HAVE_STATFS
1050 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1051 #endif // HAVE_STATVFS/HAVE_STATFS
1055 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1060 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1064 #else // !HAVE_STATFS && !HAVE_STATVFS
1066 #endif // HAVE_STATFS
1069 // ----------------------------------------------------------------------------
1071 // ----------------------------------------------------------------------------
1075 WX_DECLARE_STRING_HASH_MAP(char *, wxEnvVars
);
1077 static wxEnvVars gs_envVars
;
1079 class wxSetEnvModule
: public wxModule
1082 virtual bool OnInit() { return true; }
1083 virtual void OnExit()
1085 for ( wxEnvVars::const_iterator i
= gs_envVars
.begin();
1086 i
!= gs_envVars
.end();
1095 DECLARE_DYNAMIC_CLASS(wxSetEnvModule
)
1098 IMPLEMENT_DYNAMIC_CLASS(wxSetEnvModule
, wxModule
)
1100 #endif // USE_PUTENV
1102 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1104 // wxGetenv is defined as getenv()
1105 char *p
= wxGetenv(var
);
1117 static bool wxDoSetEnv(const wxString
& variable
, const char *value
)
1119 #if defined(HAVE_SETENV)
1122 #ifdef HAVE_UNSETENV
1123 // don't test unsetenv() return value: it's void on some systems (at
1125 unsetenv(variable
.mb_str());
1128 value
= ""; // we can't pass NULL to setenv()
1132 return setenv(variable
.mb_str(), value
, 1 /* overwrite */) == 0;
1133 #elif defined(HAVE_PUTENV)
1134 wxString s
= variable
;
1136 s
<< _T('=') << value
;
1138 // transform to ANSI
1139 const wxWX2MBbuf p
= s
.mb_str();
1141 char *buf
= (char *)malloc(strlen(p
) + 1);
1144 // store the string to free() it later
1145 wxEnvVars::iterator i
= gs_envVars
.find(variable
);
1146 if ( i
!= gs_envVars
.end() )
1151 else // this variable hadn't been set before
1153 gs_envVars
[variable
] = buf
;
1156 return putenv(buf
) == 0;
1157 #else // no way to set an env var
1162 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
1164 return wxDoSetEnv(variable
, value
.mb_str());
1167 bool wxUnsetEnv(const wxString
& variable
)
1169 return wxDoSetEnv(variable
, NULL
);
1172 // ----------------------------------------------------------------------------
1174 // ----------------------------------------------------------------------------
1176 #if wxUSE_ON_FATAL_EXCEPTION
1180 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1184 // give the user a chance to do something special about this
1185 wxTheApp
->OnFatalException();
1191 bool wxHandleFatalExceptions(bool doit
)
1194 static bool s_savedHandlers
= false;
1195 static struct sigaction s_handlerFPE
,
1201 if ( doit
&& !s_savedHandlers
)
1203 // install the signal handler
1204 struct sigaction act
;
1206 // some systems extend it with non std fields, so zero everything
1207 memset(&act
, 0, sizeof(act
));
1209 act
.sa_handler
= wxFatalSignalHandler
;
1210 sigemptyset(&act
.sa_mask
);
1213 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1214 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1215 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1216 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1219 wxLogDebug(_T("Failed to install our signal handler."));
1222 s_savedHandlers
= true;
1224 else if ( s_savedHandlers
)
1226 // uninstall the signal handler
1227 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1228 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1229 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1230 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1233 wxLogDebug(_T("Failed to uninstall our signal handler."));
1236 s_savedHandlers
= false;
1238 //else: nothing to do
1243 #endif // wxUSE_ON_FATAL_EXCEPTION
1245 // ----------------------------------------------------------------------------
1246 // wxExecute support
1247 // ----------------------------------------------------------------------------
1249 int wxAppTraits::AddProcessCallback(wxEndProcessData
*data
, int fd
)
1251 // define a custom handler processing only the closure of the descriptor
1252 struct wxEndProcessFDIOHandler
: public wxFDIOHandler
1254 wxEndProcessFDIOHandler(wxEndProcessData
*data
, int fd
)
1255 : m_data(data
), m_fd(fd
)
1259 virtual void OnReadWaiting()
1261 wxFDIODispatcher::Get()->UnregisterFD(m_fd
);
1264 wxHandleProcessTermination(m_data
);
1269 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1270 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1272 wxEndProcessData
* const m_data
;
1276 wxFDIODispatcher::Get()->RegisterFD
1279 new wxEndProcessFDIOHandler(data
, fd
),
1282 return fd
; // unused, but return something unique for the tag
1285 bool wxAppTraits::CheckForRedirectedIO(wxExecuteData
& execData
)
1287 #if HAS_PIPE_INPUT_STREAM
1290 if ( execData
.bufOut
&& execData
.bufOut
->Update() )
1293 if ( execData
.bufErr
&& execData
.bufErr
->Update() )
1297 #else // !HAS_PIPE_INPUT_STREAM
1299 #endif // HAS_PIPE_INPUT_STREAM/!HAS_PIPE_INPUT_STREAM
1302 // helper classes/functions used by WaitForChild()
1306 // convenient base class for IO handlers which are registered for read
1307 // notifications only and which also stores the FD we're reading from
1309 // the derived classes still have to implement OnReadWaiting()
1310 class wxReadFDIOHandler
: public wxFDIOHandler
1313 wxReadFDIOHandler(wxFDIODispatcher
& disp
, int fd
) : m_fd(fd
)
1316 disp
.RegisterFD(fd
, this, wxFDIO_INPUT
);
1319 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1320 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1325 DECLARE_NO_COPY_CLASS(wxReadFDIOHandler
)
1328 // class for monitoring our end of the process detection pipe, simply sets a
1329 // flag when input on the pipe (which must be due to EOF) is detected
1330 class wxEndHandler
: public wxReadFDIOHandler
1333 wxEndHandler(wxFDIODispatcher
& disp
, int fd
)
1334 : wxReadFDIOHandler(disp
, fd
)
1336 m_terminated
= false;
1339 bool Terminated() const { return m_terminated
; }
1341 virtual void OnReadWaiting() { m_terminated
= true; }
1346 DECLARE_NO_COPY_CLASS(wxEndHandler
)
1351 // class for monitoring our ends of child stdout/err, should be constructed
1352 // with the FD and stream from wxExecuteData and will do nothing if they're
1355 // unlike wxEndHandler this class registers itself with the provided dispatcher
1356 class wxRedirectedIOHandler
: public wxReadFDIOHandler
1359 wxRedirectedIOHandler(wxFDIODispatcher
& disp
,
1361 wxStreamTempInputBuffer
*buf
)
1362 : wxReadFDIOHandler(disp
, fd
),
1367 virtual void OnReadWaiting()
1373 wxStreamTempInputBuffer
* const m_buf
;
1375 DECLARE_NO_COPY_CLASS(wxRedirectedIOHandler
)
1378 #endif // wxUSE_STREAMS
1380 // helper function which calls waitpid() and analyzes the result
1381 int DoWaitForChild(int pid
, int flags
= 0)
1383 wxASSERT_MSG( pid
> 0, "invalid PID" );
1387 // loop while we're getting EINTR
1390 rc
= waitpid(pid
, &status
, flags
);
1392 if ( rc
!= -1 || errno
!= EINTR
)
1398 // This can only happen if the child application closes our dummy pipe
1399 // that is used to monitor its lifetime; in that case, our best bet is
1400 // to pretend the process did terminate, because otherwise wxExecute()
1401 // would hang indefinitely (OnReadWaiting() won't be called again, the
1402 // descriptor is closed now).
1403 wxLogDebug("Child process (PID %d) still alive but pipe closed so "
1404 "generating a close notification", pid
);
1406 else if ( rc
== -1 )
1408 wxLogLastError(wxString::Format("waitpid(%d)", pid
));
1410 else // child did terminate
1412 wxASSERT_MSG( rc
== pid
, "unexpected waitpid() return value" );
1414 if ( WIFEXITED(status
) )
1415 return WEXITSTATUS(status
);
1416 else if ( WIFSIGNALED(status
) )
1417 return -WTERMSIG(status
);
1420 wxLogError("Child process (PID %d) exited for unknown reason, "
1421 "status = %d", pid
, status
);
1428 } // anonymous namespace
1430 int wxAppTraits::WaitForChild(wxExecuteData
& execData
)
1432 if ( !(execData
.flags
& wxEXEC_SYNC
) )
1434 // asynchronous execution: just launch the process and return,
1435 // endProcData will be destroyed when it terminates (currently we leak
1436 // it if the process doesn't terminate before we do and this should be
1437 // fixed but it's not a real leak so it's not really very high
1439 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1440 endProcData
->process
= execData
.process
;
1441 endProcData
->pid
= execData
.pid
;
1442 endProcData
->tag
= AddProcessCallback
1445 execData
.GetEndProcReadFD()
1447 endProcData
->async
= true;
1449 return execData
.pid
;
1451 //else: synchronous execution case
1454 wxProcess
* const process
= execData
.process
;
1455 if ( process
&& process
->IsRedirected() )
1457 // we can't simply block waiting for the child to terminate as we would
1458 // dead lock if it writes more than the pipe buffer size (typically
1459 // 4KB) bytes of output -- it would then block waiting for us to read
1460 // the data while we'd block waiting for it to terminate
1462 // so multiplex here waiting for any input from the child or closure of
1463 // the pipe used to indicate its termination
1464 wxSelectDispatcher disp
;
1466 wxEndHandler
endHandler(disp
, execData
.GetEndProcReadFD());
1468 wxRedirectedIOHandler
outHandler(disp
, execData
.fdOut
, execData
.bufOut
),
1469 errHandler(disp
, execData
.fdErr
, execData
.bufErr
);
1471 while ( !endHandler
.Terminated() )
1476 //else: no IO redirection, just block waiting for the child to exit
1477 #endif // wxUSE_STREAMS
1479 return DoWaitForChild(execData
.pid
);
1482 void wxHandleProcessTermination(wxEndProcessData
*data
)
1484 data
->exitcode
= DoWaitForChild(data
->pid
, WNOHANG
);
1486 // notify user about termination if required
1487 if ( data
->process
)
1489 data
->process
->OnTerminate(data
->pid
, data
->exitcode
);
1494 // in case of asynchronous execution we don't need this data any more
1495 // after the child terminates
1498 else // sync execution
1500 // let wxExecute() know that the process has terminated