1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/utilsunx.cpp
3 // Purpose: generic Unix implementation of many wx functions (for wxBase)
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
, 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(wxT("unexpected kill(2) return value %d"), err
);
268 // Shutdown or reboot the PC
269 bool wxShutdown(int flags
)
271 flags
&= ~wxSHUTDOWN_FORCE
;
276 case wxSHUTDOWN_POWEROFF
:
280 case wxSHUTDOWN_REBOOT
:
284 case wxSHUTDOWN_LOGOFF
:
285 // TODO: use dcop to log off?
289 wxFAIL_MSG( wxT("unknown wxShutdown() flag") );
293 return system(wxString::Format("init %c", level
).mb_str()) == 0;
296 // ----------------------------------------------------------------------------
297 // wxStream classes to support IO redirection in wxExecute
298 // ----------------------------------------------------------------------------
300 #if HAS_PIPE_INPUT_STREAM
302 bool wxPipeInputStream::CanRead() const
304 if ( m_lasterror
== wxSTREAM_EOF
)
307 // check if there is any input available
312 const int fd
= m_file
->fd();
317 wxFD_SET(fd
, &readfds
);
319 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
322 wxLogSysError(_("Impossible to get child process input"));
329 wxFAIL_MSG(wxT("unexpected select() return value"));
330 // still fall through
333 // input available -- or maybe not, as select() returns 1 when a
334 // read() will complete without delay, but it could still not read
340 #endif // HAS_PIPE_INPUT_STREAM
342 // ----------------------------------------------------------------------------
344 // ----------------------------------------------------------------------------
346 static wxString
wxMakeShellCommand(const wxString
& command
)
351 // just an interactive shell
356 // execute command in a shell
357 cmd
<< wxT("/bin/sh -c '") << command
<< wxT('\'');
363 bool wxShell(const wxString
& command
)
365 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
368 bool wxShell(const wxString
& command
, wxArrayString
& output
)
370 wxCHECK_MSG( !command
.empty(), false, wxT("can't exec shell non interactively") );
372 return wxExecute(wxMakeShellCommand(command
), output
);
378 // helper class for storing arguments as char** array suitable for passing to
379 // execvp(), whatever form they were passed to us
383 ArgsArray(const wxArrayString
& args
)
387 for ( int i
= 0; i
< m_argc
; i
++ )
389 m_argv
[i
] = wxStrdup(args
[i
]);
394 ArgsArray(wchar_t **wargv
)
397 while ( wargv
[argc
] )
402 for ( int i
= 0; i
< m_argc
; i
++ )
404 m_argv
[i
] = wxSafeConvertWX2MB(wargv
[i
]).release();
407 #endif // wxUSE_UNICODE
411 for ( int i
= 0; i
< m_argc
; i
++ )
419 operator char**() const { return m_argv
; }
425 m_argv
= new char *[m_argc
+ 1];
426 m_argv
[m_argc
] = NULL
;
432 wxDECLARE_NO_COPY_CLASS(ArgsArray
);
435 } // anonymous namespace
437 // ----------------------------------------------------------------------------
438 // wxExecute implementations
439 // ----------------------------------------------------------------------------
441 #if defined(__DARWIN__)
442 bool wxMacLaunch(char **argv
);
445 long wxExecute(const wxString
& command
, int flags
, wxProcess
*process
,
446 const wxExecuteEnv
*env
)
448 ArgsArray
argv(wxCmdLineParser::ConvertStringToArgs(command
,
449 wxCMD_LINE_SPLIT_UNIX
));
451 return wxExecute(argv
, flags
, process
, env
);
456 long wxExecute(wchar_t **wargv
, int flags
, wxProcess
*process
,
457 const wxExecuteEnv
*env
)
459 ArgsArray
argv(wargv
);
461 return wxExecute(argv
, flags
, process
, env
);
464 #endif // wxUSE_UNICODE
466 // wxExecute: the real worker function
467 long wxExecute(char **argv
, int flags
, wxProcess
*process
,
468 const wxExecuteEnv
*env
)
470 // for the sync execution, we return -1 to indicate failure, but for async
471 // case we return 0 which is never a valid PID
473 // we define this as a macro, not a variable, to avoid compiler warnings
474 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
475 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
477 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
480 // fork() doesn't mix well with POSIX threads: on many systems the program
481 // deadlocks or crashes for some reason. Probably our code is buggy and
482 // doesn't do something which must be done to allow this to work, but I
483 // don't know what yet, so for now just warn the user (this is the least we
485 wxASSERT_MSG( wxThread::IsMain(),
486 wxT("wxExecute() can be called only from the main thread") );
487 #endif // wxUSE_THREADS
489 #if defined(__WXCOCOA__) || ( defined(__WXOSX_MAC__) && wxOSX_USE_COCOA_OR_CARBON )
490 // wxMacLaunch() only executes app bundles and only does it asynchronously.
491 // It returns false if the target is not an app bundle, thus falling
492 // through to the regular code for non app bundles.
493 if ( !(flags
& wxEXEC_SYNC
) && wxMacLaunch(argv
) )
495 // we don't have any PID to return so just make up something non null
501 // this struct contains all information which we use for housekeeping
502 wxExecuteData execData
;
503 execData
.flags
= flags
;
504 execData
.process
= process
;
507 if ( !execData
.pipeEndProcDetect
.Create() )
509 wxLogError( _("Failed to execute '%s'\n"), *argv
);
511 return ERROR_RETURN_CODE
;
514 // pipes for inter process communication
515 wxPipe pipeIn
, // stdin
519 if ( process
&& process
->IsRedirected() )
521 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
523 wxLogError( _("Failed to execute '%s'\n"), *argv
);
525 return ERROR_RETURN_CODE
;
531 // NB: do *not* use vfork() here, it completely breaks this code for some
532 // reason under Solaris (and maybe others, although not under Linux)
533 // But on OpenVMS we do not have fork so we have to use vfork and
534 // cross our fingers that it works.
540 if ( pid
== -1 ) // error?
542 wxLogSysError( _("Fork failed") );
544 return ERROR_RETURN_CODE
;
546 else if ( pid
== 0 ) // we're in child
548 // NB: we used to close all the unused descriptors of the child here
549 // but this broke some programs which relied on e.g. FD 1 being
550 // always opened so don't do it any more, after all there doesn't
551 // seem to be any real problem with keeping them opened
553 #if !defined(__VMS) && !defined(__EMX__)
554 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
556 // Set process group to child process' pid. Then killing -pid
557 // of the parent will kill the process and all of its children.
562 // reading side can be safely closed but we should keep the write one
563 // opened, it will be only closed when the process terminates resulting
564 // in a read notification to the parent
565 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
566 execData
.pipeEndProcDetect
.Close();
568 // redirect stdin, stdout and stderr
571 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
572 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
573 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
575 wxLogSysError(_("Failed to redirect child process input/output"));
583 // Process additional options if we have any
586 // Change working directory if it is specified
587 if ( !env
->cwd
.empty() )
588 wxSetWorkingDirectory(env
->cwd
);
590 // Change environment if needed.
592 // NB: We can't use execve() currently because we allow using
593 // non full paths to wxExecute(), i.e. we want to search for
594 // the program in PATH. However it just might be simpler/better
595 // to do the search manually and use execve() envp parameter to
596 // set up the environment of the child process explicitly
597 // instead of doing what we do below.
598 if ( !env
->env
.empty() )
600 wxEnvVariableHashMap oldenv
;
601 wxGetEnvMap(&oldenv
);
603 // Remove unwanted variables
604 wxEnvVariableHashMap::const_iterator it
;
605 for ( it
= oldenv
.begin(); it
!= oldenv
.end(); ++it
)
607 if ( env
->env
.find(it
->first
) == env
->env
.end() )
608 wxUnsetEnv(it
->first
);
611 // And add the new ones (possibly replacing the old values)
612 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
613 wxSetEnv(it
->first
, it
->second
);
619 fprintf(stderr
, "execvp(");
620 for ( char **a
= argv
; *a
; a
++ )
621 fprintf(stderr
, "%s%s", a
== argv
? "" : ", ", *a
);
622 fprintf(stderr
, ") failed with error %d!\n", errno
);
624 // there is no return after successful exec()
627 // some compilers complain about missing return - of course, they
628 // should know that exit() doesn't return but what else can we do if
631 // and, sure enough, other compilers complain about unreachable code
632 // after exit() call, so we can just always have return here...
633 #if defined(__VMS) || defined(__INTEL_COMPILER)
637 else // we're in parent
639 // save it for WaitForChild() use
641 if (execData
.process
)
642 execData
.process
->SetPid(pid
); // and also in the wxProcess
644 // prepare for IO redirection
646 #if HAS_PIPE_INPUT_STREAM
647 // the input buffer bufOut is connected to stdout, this is why it is
648 // called bufOut and not bufIn
649 wxStreamTempInputBuffer bufOut
,
652 if ( process
&& process
->IsRedirected() )
654 wxOutputStream
*inStream
=
655 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
657 const int fdOut
= pipeOut
.Detach(wxPipe::Read
);
658 wxPipeInputStream
*outStream
= new wxPipeInputStream(fdOut
);
660 const int fdErr
= pipeErr
.Detach(wxPipe::Read
);
661 wxPipeInputStream
*errStream
= new wxPipeInputStream(fdErr
);
663 process
->SetPipeStreams(outStream
, inStream
, errStream
);
665 bufOut
.Init(outStream
);
666 bufErr
.Init(errStream
);
668 execData
.bufOut
= &bufOut
;
669 execData
.bufErr
= &bufErr
;
671 execData
.fdOut
= fdOut
;
672 execData
.fdErr
= fdErr
;
674 #endif // HAS_PIPE_INPUT_STREAM
683 // we want this function to work even if there is no wxApp so ensure
684 // that we have a valid traits pointer
685 wxConsoleAppTraits traitsConsole
;
686 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
688 traits
= &traitsConsole
;
690 return traits
->WaitForChild(execData
);
693 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
694 return ERROR_RETURN_CODE
;
698 #undef ERROR_RETURN_CODE
700 // ----------------------------------------------------------------------------
701 // file and directory functions
702 // ----------------------------------------------------------------------------
704 const wxChar
* wxGetHomeDir( wxString
*home
)
706 *home
= wxGetUserHome();
712 if ( tmp
.Last() != wxT(']'))
713 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
715 return home
->c_str();
718 wxString
wxGetUserHome( const wxString
&user
)
720 struct passwd
*who
= (struct passwd
*) NULL
;
726 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
731 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
||
732 (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
734 who
= getpwnam(wxSafeConvertWX2MB(ptr
));
737 // make sure the user exists!
740 who
= getpwuid(getuid());
745 who
= getpwnam (user
.mb_str());
748 return wxSafeConvertMB2WX(who
? who
->pw_dir
: 0);
751 // ----------------------------------------------------------------------------
752 // network and user id routines
753 // ----------------------------------------------------------------------------
755 // private utility function which returns output of the given command, removing
756 // the trailing newline
757 static wxString
wxGetCommandOutput(const wxString
&cmd
)
759 FILE *f
= popen(cmd
.ToAscii(), "r");
762 wxLogSysError(wxT("Executing \"%s\" failed"), cmd
.c_str());
763 return wxEmptyString
;
770 if ( !fgets(buf
, sizeof(buf
), f
) )
773 s
+= wxString::FromAscii(buf
);
778 if ( !s
.empty() && s
.Last() == wxT('\n') )
784 // retrieve either the hostname or FQDN depending on platform (caller must
785 // check whether it's one or the other, this is why this function is for
787 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
789 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
793 // we're using uname() which is POSIX instead of less standard sysinfo()
794 #if defined(HAVE_UNAME)
796 bool ok
= uname(&uts
) != -1;
799 wxStrlcpy(buf
, wxSafeConvertMB2WX(uts
.nodename
), sz
);
801 #elif defined(HAVE_GETHOSTNAME)
803 bool ok
= gethostname(cbuf
, sz
) != -1;
806 wxStrlcpy(buf
, wxSafeConvertMB2WX(cbuf
), sz
);
808 #else // no uname, no gethostname
809 wxFAIL_MSG(wxT("don't know host name for this machine"));
812 #endif // uname/gethostname
816 wxLogSysError(_("Cannot get the hostname"));
822 bool wxGetHostName(wxChar
*buf
, int sz
)
824 bool ok
= wxGetHostNameInternal(buf
, sz
);
828 // BSD systems return the FQDN, we only want the hostname, so extract
829 // it (we consider that dots are domain separators)
830 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
841 bool wxGetFullHostName(wxChar
*buf
, int sz
)
843 bool ok
= wxGetHostNameInternal(buf
, sz
);
847 if ( !wxStrchr(buf
, wxT('.')) )
849 struct hostent
*host
= gethostbyname(wxSafeConvertWX2MB(buf
));
852 wxLogSysError(_("Cannot get the official hostname"));
858 // the canonical name
859 wxStrlcpy(buf
, wxSafeConvertMB2WX(host
->h_name
), sz
);
862 //else: it's already a FQDN (BSD behaves this way)
868 bool wxGetUserId(wxChar
*buf
, int sz
)
873 if ((who
= getpwuid(getuid ())) != NULL
)
875 wxStrlcpy (buf
, wxSafeConvertMB2WX(who
->pw_name
), sz
);
882 bool wxGetUserName(wxChar
*buf
, int sz
)
888 if ((who
= getpwuid (getuid ())) != NULL
)
890 char *comma
= strchr(who
->pw_gecos
, ',');
892 *comma
= '\0'; // cut off non-name comment fields
893 wxStrlcpy(buf
, wxSafeConvertMB2WX(who
->pw_gecos
), sz
);
898 #else // !HAVE_PW_GECOS
899 return wxGetUserId(buf
, sz
);
900 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
903 bool wxIsPlatform64Bit()
905 const wxString machine
= wxGetCommandOutput(wxT("uname -m"));
907 // the test for "64" is obviously not 100% reliable but seems to work fine
909 return machine
.Contains(wxT("64")) ||
910 machine
.Contains(wxT("alpha"));
914 wxLinuxDistributionInfo
wxGetLinuxDistributionInfo()
916 const wxString id
= wxGetCommandOutput(wxT("lsb_release --id"));
917 const wxString desc
= wxGetCommandOutput(wxT("lsb_release --description"));
918 const wxString rel
= wxGetCommandOutput(wxT("lsb_release --release"));
919 const wxString codename
= wxGetCommandOutput(wxT("lsb_release --codename"));
921 wxLinuxDistributionInfo ret
;
923 id
.StartsWith("Distributor ID:\t", &ret
.Id
);
924 desc
.StartsWith("Description:\t", &ret
.Description
);
925 rel
.StartsWith("Release:\t", &ret
.Release
);
926 codename
.StartsWith("Codename:\t", &ret
.CodeName
);
932 // these functions are in src/osx/utilsexc_base.cpp for wxMac
935 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
939 wxString release
= wxGetCommandOutput(wxT("uname -r"));
940 if ( release
.empty() ||
941 wxSscanf(release
.c_str(), wxT("%d.%d"), &major
, &minor
) != 2 )
943 // failed to get version string or unrecognized format
953 // try to understand which OS are we running
954 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
955 if ( kernel
.empty() )
956 kernel
= wxGetCommandOutput(wxT("uname -o"));
958 if ( kernel
.empty() )
961 return wxPlatformInfo::GetOperatingSystemId(kernel
);
964 wxString
wxGetOsDescription()
966 return wxGetCommandOutput(wxT("uname -s -r -m"));
971 unsigned long wxGetProcessId()
973 return (unsigned long)getpid();
976 wxMemorySize
wxGetFreeMemory()
978 #if defined(__LINUX__)
979 // get it from /proc/meminfo
980 FILE *fp
= fopen("/proc/meminfo", "r");
986 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
988 // /proc/meminfo changed its format in kernel 2.6
989 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
991 unsigned long cached
, buffers
;
992 sscanf(buf
, "MemFree: %ld", &memFree
);
994 fgets(buf
, WXSIZEOF(buf
), fp
);
995 sscanf(buf
, "Buffers: %lu", &buffers
);
997 fgets(buf
, WXSIZEOF(buf
), fp
);
998 sscanf(buf
, "Cached: %lu", &cached
);
1000 // add to "MemFree" also the "Buffers" and "Cached" values as
1001 // free(1) does as otherwise the value never makes sense: for
1002 // kernel 2.6 it's always almost 0
1003 memFree
+= buffers
+ cached
;
1005 // values here are always expressed in kB and we want bytes
1008 else // Linux 2.4 (or < 2.6, anyhow)
1010 long memTotal
, memUsed
;
1011 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
1017 return (wxMemorySize
)memFree
;
1019 #elif defined(__SGI__)
1020 struct rminfo realmem
;
1021 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
1022 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
1023 #elif defined(_SC_AVPHYS_PAGES)
1024 return ((wxMemorySize
)sysconf(_SC_AVPHYS_PAGES
))*sysconf(_SC_PAGESIZE
);
1025 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1028 // can't find it out
1032 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
1034 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1035 // the case to "char *" is needed for AIX 4.3
1037 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
1039 wxLogSysError( wxT("Failed to get file system statistics") );
1044 // under Solaris we also have to use f_frsize field instead of f_bsize
1045 // which is in general a multiple of f_frsize
1047 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1048 #else // HAVE_STATFS
1049 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1050 #endif // HAVE_STATVFS/HAVE_STATFS
1054 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1059 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1063 #else // !HAVE_STATFS && !HAVE_STATVFS
1065 #endif // HAVE_STATFS
1068 // ----------------------------------------------------------------------------
1070 // ----------------------------------------------------------------------------
1074 WX_DECLARE_STRING_HASH_MAP(char *, wxEnvVars
);
1076 static wxEnvVars gs_envVars
;
1078 class wxSetEnvModule
: public wxModule
1081 virtual bool OnInit() { return true; }
1082 virtual void OnExit()
1084 for ( wxEnvVars::const_iterator i
= gs_envVars
.begin();
1085 i
!= gs_envVars
.end();
1094 DECLARE_DYNAMIC_CLASS(wxSetEnvModule
)
1097 IMPLEMENT_DYNAMIC_CLASS(wxSetEnvModule
, wxModule
)
1099 #endif // USE_PUTENV
1101 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1103 // wxGetenv is defined as getenv()
1104 char *p
= wxGetenv(var
);
1116 static bool wxDoSetEnv(const wxString
& variable
, const char *value
)
1118 #if defined(HAVE_SETENV)
1121 #ifdef HAVE_UNSETENV
1122 // don't test unsetenv() return value: it's void on some systems (at
1124 unsetenv(variable
.mb_str());
1127 value
= ""; // we can't pass NULL to setenv()
1131 return setenv(variable
.mb_str(), value
, 1 /* overwrite */) == 0;
1132 #elif defined(HAVE_PUTENV)
1133 wxString s
= variable
;
1135 s
<< wxT('=') << value
;
1137 // transform to ANSI
1138 const wxWX2MBbuf p
= s
.mb_str();
1140 char *buf
= (char *)malloc(strlen(p
) + 1);
1143 // store the string to free() it later
1144 wxEnvVars::iterator i
= gs_envVars
.find(variable
);
1145 if ( i
!= gs_envVars
.end() )
1150 else // this variable hadn't been set before
1152 gs_envVars
[variable
] = buf
;
1155 return putenv(buf
) == 0;
1156 #else // no way to set an env var
1161 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
1163 return wxDoSetEnv(variable
, value
.mb_str());
1166 bool wxUnsetEnv(const wxString
& variable
)
1168 return wxDoSetEnv(variable
, NULL
);
1171 // ----------------------------------------------------------------------------
1173 // ----------------------------------------------------------------------------
1175 #if wxUSE_ON_FATAL_EXCEPTION
1179 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1183 // give the user a chance to do something special about this
1184 wxTheApp
->OnFatalException();
1190 bool wxHandleFatalExceptions(bool doit
)
1193 static bool s_savedHandlers
= false;
1194 static struct sigaction s_handlerFPE
,
1200 if ( doit
&& !s_savedHandlers
)
1202 // install the signal handler
1203 struct sigaction act
;
1205 // some systems extend it with non std fields, so zero everything
1206 memset(&act
, 0, sizeof(act
));
1208 act
.sa_handler
= wxFatalSignalHandler
;
1209 sigemptyset(&act
.sa_mask
);
1212 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1213 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1214 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1215 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1218 wxLogDebug(wxT("Failed to install our signal handler."));
1221 s_savedHandlers
= true;
1223 else if ( s_savedHandlers
)
1225 // uninstall the signal handler
1226 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1227 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1228 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1229 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1232 wxLogDebug(wxT("Failed to uninstall our signal handler."));
1235 s_savedHandlers
= false;
1237 //else: nothing to do
1242 #endif // wxUSE_ON_FATAL_EXCEPTION
1244 // ----------------------------------------------------------------------------
1245 // wxExecute support
1246 // ----------------------------------------------------------------------------
1248 int wxAppTraits::AddProcessCallback(wxEndProcessData
*data
, int fd
)
1250 // define a custom handler processing only the closure of the descriptor
1251 struct wxEndProcessFDIOHandler
: public wxFDIOHandler
1253 wxEndProcessFDIOHandler(wxEndProcessData
*data
, int fd
)
1254 : m_data(data
), m_fd(fd
)
1258 virtual void OnReadWaiting()
1260 wxFDIODispatcher::Get()->UnregisterFD(m_fd
);
1263 wxHandleProcessTermination(m_data
);
1268 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1269 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1271 wxEndProcessData
* const m_data
;
1275 wxFDIODispatcher::Get()->RegisterFD
1278 new wxEndProcessFDIOHandler(data
, fd
),
1281 return fd
; // unused, but return something unique for the tag
1284 bool wxAppTraits::CheckForRedirectedIO(wxExecuteData
& execData
)
1286 #if HAS_PIPE_INPUT_STREAM
1289 if ( execData
.bufOut
&& execData
.bufOut
->Update() )
1292 if ( execData
.bufErr
&& execData
.bufErr
->Update() )
1296 #else // !HAS_PIPE_INPUT_STREAM
1298 #endif // HAS_PIPE_INPUT_STREAM/!HAS_PIPE_INPUT_STREAM
1301 // helper classes/functions used by WaitForChild()
1305 // convenient base class for IO handlers which are registered for read
1306 // notifications only and which also stores the FD we're reading from
1308 // the derived classes still have to implement OnReadWaiting()
1309 class wxReadFDIOHandler
: public wxFDIOHandler
1312 wxReadFDIOHandler(wxFDIODispatcher
& disp
, int fd
) : m_fd(fd
)
1315 disp
.RegisterFD(fd
, this, wxFDIO_INPUT
);
1318 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1319 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1324 wxDECLARE_NO_COPY_CLASS(wxReadFDIOHandler
);
1327 // class for monitoring our end of the process detection pipe, simply sets a
1328 // flag when input on the pipe (which must be due to EOF) is detected
1329 class wxEndHandler
: public wxReadFDIOHandler
1332 wxEndHandler(wxFDIODispatcher
& disp
, int fd
)
1333 : wxReadFDIOHandler(disp
, fd
)
1335 m_terminated
= false;
1338 bool Terminated() const { return m_terminated
; }
1340 virtual void OnReadWaiting() { m_terminated
= true; }
1345 wxDECLARE_NO_COPY_CLASS(wxEndHandler
);
1348 #if HAS_PIPE_INPUT_STREAM
1350 // class for monitoring our ends of child stdout/err, should be constructed
1351 // with the FD and stream from wxExecuteData and will do nothing if they're
1354 // unlike wxEndHandler this class registers itself with the provided dispatcher
1355 class wxRedirectedIOHandler
: public wxReadFDIOHandler
1358 wxRedirectedIOHandler(wxFDIODispatcher
& disp
,
1360 wxStreamTempInputBuffer
*buf
)
1361 : wxReadFDIOHandler(disp
, fd
),
1366 virtual void OnReadWaiting()
1372 wxStreamTempInputBuffer
* const m_buf
;
1374 wxDECLARE_NO_COPY_CLASS(wxRedirectedIOHandler
);
1377 #endif // HAS_PIPE_INPUT_STREAM
1379 // helper function which calls waitpid() and analyzes the result
1380 int DoWaitForChild(int pid
, int flags
= 0)
1382 wxASSERT_MSG( pid
> 0, "invalid PID" );
1386 // loop while we're getting EINTR
1389 rc
= waitpid(pid
, &status
, flags
);
1391 if ( rc
!= -1 || errno
!= EINTR
)
1397 // This can only happen if the child application closes our dummy pipe
1398 // that is used to monitor its lifetime; in that case, our best bet is
1399 // to pretend the process did terminate, because otherwise wxExecute()
1400 // would hang indefinitely (OnReadWaiting() won't be called again, the
1401 // descriptor is closed now).
1402 wxLogDebug("Child process (PID %d) still alive but pipe closed so "
1403 "generating a close notification", pid
);
1405 else if ( rc
== -1 )
1407 wxLogLastError(wxString::Format("waitpid(%d)", pid
));
1409 else // child did terminate
1411 wxASSERT_MSG( rc
== pid
, "unexpected waitpid() return value" );
1413 // notice that the caller expects the exit code to be signed, e.g. -1
1414 // instead of 255 so don't assign WEXITSTATUS() to an int
1415 signed char exitcode
;
1416 if ( WIFEXITED(status
) )
1417 exitcode
= WEXITSTATUS(status
);
1418 else if ( WIFSIGNALED(status
) )
1419 exitcode
= -WTERMSIG(status
);
1422 wxLogError("Child process (PID %d) exited for unknown reason, "
1423 "status = %d", pid
, status
);
1433 } // anonymous namespace
1435 int wxAppTraits::WaitForChild(wxExecuteData
& execData
)
1437 if ( !(execData
.flags
& wxEXEC_SYNC
) )
1439 // asynchronous execution: just launch the process and return,
1440 // endProcData will be destroyed when it terminates (currently we leak
1441 // it if the process doesn't terminate before we do and this should be
1442 // fixed but it's not a real leak so it's not really very high
1444 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1445 endProcData
->process
= execData
.process
;
1446 endProcData
->pid
= execData
.pid
;
1447 endProcData
->tag
= AddProcessCallback
1450 execData
.GetEndProcReadFD()
1452 endProcData
->async
= true;
1454 return execData
.pid
;
1456 //else: synchronous execution case
1458 #if HAS_PIPE_INPUT_STREAM && wxUSE_SOCKETS
1459 wxProcess
* const process
= execData
.process
;
1460 if ( process
&& process
->IsRedirected() )
1462 // we can't simply block waiting for the child to terminate as we would
1463 // dead lock if it writes more than the pipe buffer size (typically
1464 // 4KB) bytes of output -- it would then block waiting for us to read
1465 // the data while we'd block waiting for it to terminate
1467 // so multiplex here waiting for any input from the child or closure of
1468 // the pipe used to indicate its termination
1469 wxSelectDispatcher disp
;
1471 wxEndHandler
endHandler(disp
, execData
.GetEndProcReadFD());
1473 wxRedirectedIOHandler
outHandler(disp
, execData
.fdOut
, execData
.bufOut
),
1474 errHandler(disp
, execData
.fdErr
, execData
.bufErr
);
1476 while ( !endHandler
.Terminated() )
1481 //else: no IO redirection, just block waiting for the child to exit
1482 #endif // HAS_PIPE_INPUT_STREAM
1484 return DoWaitForChild(execData
.pid
);
1487 void wxHandleProcessTermination(wxEndProcessData
*data
)
1489 data
->exitcode
= DoWaitForChild(data
->pid
, WNOHANG
);
1491 // notify user about termination if required
1492 if ( data
->process
)
1494 data
->process
->OnTerminate(data
->pid
, data
->exitcode
);
1499 // in case of asynchronous execution we don't need this data any more
1500 // after the child terminates
1503 else // sync execution
1505 // let wxExecute() know that the process has terminated