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"
24 #include "wx/string.h"
30 #include "wx/apptrait.h"
32 #include "wx/process.h"
33 #include "wx/thread.h"
35 #include "wx/wfstream.h"
37 #include "wx/unix/execute.h"
38 #include "wx/unix/private.h"
41 #include <sys/wait.h> // waitpid()
43 #ifdef HAVE_SYS_SELECT_H
44 # include <sys/select.h>
47 #define HAS_PIPE_INPUT_STREAM (wxUSE_STREAMS && wxUSE_FILE)
49 #if HAS_PIPE_INPUT_STREAM
51 // define this to let wxexec.cpp know that we know what we're doing
52 #define _WX_USED_BY_WXEXECUTE_
53 #include "../common/execcmn.cpp"
55 #endif // HAS_PIPE_INPUT_STREAM
59 #if defined(__MWERKS__) && defined(__MACH__)
60 #ifndef WXWIN_OS_DESCRIPTION
61 #define WXWIN_OS_DESCRIPTION "MacOS X"
63 #ifndef HAVE_NANOSLEEP
64 #define HAVE_NANOSLEEP
70 // our configure test believes we can use sigaction() if the function is
71 // available but Metrowekrs with MSL run-time does have the function but
72 // doesn't have sigaction struct so finally we can't use it...
74 #undef wxUSE_ON_FATAL_EXCEPTION
75 #define wxUSE_ON_FATAL_EXCEPTION 0
79 // not only the statfs syscall is called differently depending on platform, but
80 // one of its incarnations, statvfs(), takes different arguments under
81 // different platforms and even different versions of the same system (Solaris
82 // 7 and 8): if you want to test for this, don't forget that the problems only
83 // appear if the large files support is enabled
86 #include <sys/param.h>
87 #include <sys/mount.h>
90 #endif // __BSD__/!__BSD__
92 #define wxStatfs statfs
94 #ifndef HAVE_STATFS_DECL
95 // some systems lack statfs() prototype in the system headers (AIX 4)
96 extern "C" int statfs(const char *path
, struct statfs
*buf
);
101 #include <sys/statvfs.h>
103 #define wxStatfs statvfs
104 #endif // HAVE_STATVFS
106 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
107 // WX_STATFS_T is detected by configure
108 #define wxStatfs_t WX_STATFS_T
111 // SGI signal.h defines signal handler arguments differently depending on
112 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
113 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
114 #define _LANGUAGE_C_PLUS_PLUS 1
120 #include <sys/stat.h>
121 #include <sys/types.h>
122 #include <sys/wait.h>
127 #include <fcntl.h> // for O_WRONLY and friends
128 #include <time.h> // nanosleep() and/or usleep()
129 #include <ctype.h> // isspace()
130 #include <sys/time.h> // needed for FD_SETSIZE
133 #include <sys/utsname.h> // for uname()
136 // Used by wxGetFreeMemory().
138 #include <sys/sysmp.h>
139 #include <sys/sysinfo.h> // for SAGET and MINFO structures
142 // ----------------------------------------------------------------------------
143 // conditional compilation
144 // ----------------------------------------------------------------------------
146 // many versions of Unices have this function, but it is not defined in system
147 // headers - please add your system here if it is the case for your OS.
148 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
149 #if !defined(HAVE_USLEEP) && \
150 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
151 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
152 defined(__osf__) || defined(__EMX__))
156 /* I copied this from the XFree86 diffs. AV. */
157 #define INCL_DOSPROCESS
159 inline void usleep(unsigned long delay
)
161 DosSleep(delay
? (delay
/1000l) : 1l);
164 int usleep(unsigned int usec
);
165 #endif // __EMX__/Unix
168 #define HAVE_USLEEP 1
169 #endif // Unices without usleep()
171 // ============================================================================
173 // ============================================================================
175 // ----------------------------------------------------------------------------
177 // ----------------------------------------------------------------------------
179 void wxSleep(int nSecs
)
184 void wxMicroSleep(unsigned long microseconds
)
186 #if defined(HAVE_NANOSLEEP)
188 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
189 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
191 // we're not interested in remaining time nor in return value
192 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
193 #elif defined(HAVE_USLEEP)
194 // uncomment this if you feel brave or if you are sure that your version
195 // of Solaris has a safe usleep() function but please notice that usleep()
196 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
197 // documented as MT-Safe
198 #if defined(__SUN__) && wxUSE_THREADS
199 #error "usleep() cannot be used in MT programs under Solaris."
202 usleep(microseconds
);
203 #elif defined(HAVE_SLEEP)
204 // under BeOS sleep() takes seconds (what about other platforms, if any?)
205 sleep(microseconds
* 1000000);
206 #else // !sleep function
207 #error "usleep() or nanosleep() function required for wxMicroSleep"
208 #endif // sleep function
211 void wxMilliSleep(unsigned long milliseconds
)
213 wxMicroSleep(milliseconds
*1000);
216 // ----------------------------------------------------------------------------
217 // process management
218 // ----------------------------------------------------------------------------
220 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
222 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
225 switch ( err
? errno
: 0 )
232 *rc
= wxKILL_BAD_SIGNAL
;
236 *rc
= wxKILL_ACCESS_DENIED
;
240 *rc
= wxKILL_NO_PROCESS
;
244 // this goes against Unix98 docs so log it
245 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
255 #define WXEXECUTE_NARGS 127
257 #if defined(__DARWIN__)
258 long wxMacExecute(wxChar
**argv
,
263 long wxExecute( const wxString
& command
, int flags
, wxProcess
*process
)
265 wxCHECK_MSG( !command
.empty(), 0, wxT("can't exec empty command") );
267 wxLogTrace(wxT("exec"), wxT("Executing \"%s\""), command
.c_str());
270 // fork() doesn't mix well with POSIX threads: on many systems the program
271 // deadlocks or crashes for some reason. Probably our code is buggy and
272 // doesn't do something which must be done to allow this to work, but I
273 // don't know what yet, so for now just warn the user (this is the least we
275 wxASSERT_MSG( wxThread::IsMain(),
276 _T("wxExecute() can be called only from the main thread") );
277 #endif // wxUSE_THREADS
280 wxChar
*argv
[WXEXECUTE_NARGS
];
282 const wxChar
*cptr
= command
.c_str();
283 wxChar quotechar
= wxT('\0'); // is arg quoted?
284 bool escaped
= false;
286 // split the command line in arguments
289 argument
= wxEmptyString
;
290 quotechar
= wxT('\0');
292 // eat leading whitespace:
293 while ( wxIsspace(*cptr
) )
296 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
301 if ( *cptr
== wxT('\\') && ! escaped
)
308 // all other characters:
312 // have we reached the end of the argument?
313 if ( (*cptr
== quotechar
&& ! escaped
)
314 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
315 || *cptr
== wxT('\0') )
317 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
318 wxT("too many arguments in wxExecute") );
320 argv
[argc
] = new wxChar
[argument
.length() + 1];
321 wxStrcpy(argv
[argc
], argument
.c_str());
324 // if not at end of buffer, swallow last character:
328 break; // done with this one, start over
335 #if defined(__DARWIN__)
336 // wxMacExecute only executes app bundles.
337 // It returns an error code if the target is not an app bundle, thus falling
338 // through to the regular wxExecute for non app bundles.
339 lRc
= wxMacExecute(argv
, flags
, process
);
340 if( lRc
!= ((flags
& wxEXEC_SYNC
) ? -1 : 0))
344 // do execute the command
345 lRc
= wxExecute(argv
, flags
, process
);
350 delete [] argv
[argc
++];
355 // ----------------------------------------------------------------------------
357 // ----------------------------------------------------------------------------
359 static wxString
wxMakeShellCommand(const wxString
& command
)
364 // just an interactive shell
369 // execute command in a shell
370 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
376 bool wxShell(const wxString
& command
)
378 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
381 bool wxShell(const wxString
& command
, wxArrayString
& output
)
383 wxCHECK_MSG( !command
.empty(), false, _T("can't exec shell non interactively") );
385 return wxExecute(wxMakeShellCommand(command
), output
);
388 // Shutdown or reboot the PC
389 bool wxShutdown(wxShutdownFlags wFlags
)
394 case wxSHUTDOWN_POWEROFF
:
398 case wxSHUTDOWN_REBOOT
:
403 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
407 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
410 // ----------------------------------------------------------------------------
411 // wxStream classes to support IO redirection in wxExecute
412 // ----------------------------------------------------------------------------
414 #if HAS_PIPE_INPUT_STREAM
416 bool wxPipeInputStream::CanRead() const
418 if ( m_lasterror
== wxSTREAM_EOF
)
421 // check if there is any input available
426 const int fd
= m_file
->fd();
431 wxFD_SET(fd
, &readfds
);
433 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
436 wxLogSysError(_("Impossible to get child process input"));
443 wxFAIL_MSG(_T("unexpected select() return value"));
444 // still fall through
447 // input available -- or maybe not, as select() returns 1 when a
448 // read() will complete without delay, but it could still not read
454 #endif // HAS_PIPE_INPUT_STREAM
456 // ----------------------------------------------------------------------------
457 // wxExecute: the real worker function
458 // ----------------------------------------------------------------------------
460 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*process
)
462 // for the sync execution, we return -1 to indicate failure, but for async
463 // case we return 0 which is never a valid PID
465 // we define this as a macro, not a variable, to avoid compiler warnings
466 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
467 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
469 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
473 char *mb_argv
[WXEXECUTE_NARGS
];
475 while (argv
[mb_argc
])
477 wxWX2MBbuf mb_arg
= wxSafeConvertWX2MB(argv
[mb_argc
]);
478 mb_argv
[mb_argc
] = strdup(mb_arg
);
481 mb_argv
[mb_argc
] = (char *) NULL
;
483 // this macro will free memory we used above
484 #define ARGS_CLEANUP \
485 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
486 free(mb_argv[mb_argc])
488 // no need for cleanup
491 wxChar
**mb_argv
= argv
;
492 #endif // Unicode/ANSI
494 // we want this function to work even if there is no wxApp so ensure that
495 // we have a valid traits pointer
496 wxConsoleAppTraits traitsConsole
;
497 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
499 traits
= &traitsConsole
;
501 // this struct contains all information which we pass to and from
502 // wxAppTraits methods
503 wxExecuteData execData
;
504 execData
.flags
= flags
;
505 execData
.process
= process
;
508 if ( !traits
->CreateEndProcessPipe(execData
) )
510 wxLogError( _("Failed to execute '%s'\n"), *argv
);
514 return ERROR_RETURN_CODE
;
517 // pipes for inter process communication
518 wxPipe pipeIn
, // stdin
522 if ( process
&& process
->IsRedirected() )
524 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
526 wxLogError( _("Failed to execute '%s'\n"), *argv
);
530 return ERROR_RETURN_CODE
;
536 // NB: do *not* use vfork() here, it completely breaks this code for some
537 // reason under Solaris (and maybe others, although not under Linux)
538 // But on OpenVMS we do not have fork so we have to use vfork and
539 // cross our fingers that it works.
545 if ( pid
== -1 ) // error?
547 wxLogSysError( _("Fork failed") );
551 return ERROR_RETURN_CODE
;
553 else if ( pid
== 0 ) // we're in child
555 // These lines close the open file descriptors to to avoid any
556 // input/output which might block the process or irritate the user. If
557 // one wants proper IO for the subprocess, the right thing to do is to
558 // start an xterm executing it.
559 if ( !(flags
& wxEXEC_SYNC
) )
561 // FD_SETSIZE is unsigned under BSD, signed under other platforms
562 // so we need a cast to avoid warnings on all platforms
563 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
565 if ( fd
== pipeIn
[wxPipe::Read
]
566 || fd
== pipeOut
[wxPipe::Write
]
567 || fd
== pipeErr
[wxPipe::Write
]
568 || traits
->IsWriteFDOfEndProcessPipe(execData
, fd
) )
570 // don't close this one, we still need it
574 // leave stderr opened too, it won't do any harm
575 if ( fd
!= STDERR_FILENO
)
580 #if !defined(__VMS) && !defined(__EMX__)
581 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
583 // Set process group to child process' pid. Then killing -pid
584 // of the parent will kill the process and all of its children.
589 // reading side can be safely closed but we should keep the write one
591 traits
->DetachWriteFDOfEndProcessPipe(execData
);
593 // redirect stdin, stdout and stderr
596 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
597 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
598 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
600 wxLogSysError(_("Failed to redirect child process input/output"));
608 execvp (*mb_argv
, mb_argv
);
610 fprintf(stderr
, "execvp(");
611 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
612 for ( char **ppc_
= mb_argv
; *ppc_
; ppc_
++ )
613 fprintf(stderr
, "%s%s", ppc_
== mb_argv
? "" : ", ", *ppc_
);
614 fprintf(stderr
, ") failed with error %d!\n", errno
);
616 // there is no return after successful exec()
619 // some compilers complain about missing return - of course, they
620 // should know that exit() doesn't return but what else can we do if
623 // and, sure enough, other compilers complain about unreachable code
624 // after exit() call, so we can just always have return here...
625 #if defined(__VMS) || defined(__INTEL_COMPILER)
629 else // we're in parent
633 // save it for WaitForChild() use
636 // prepare for IO redirection
638 #if HAS_PIPE_INPUT_STREAM
639 // the input buffer bufOut is connected to stdout, this is why it is
640 // called bufOut and not bufIn
641 wxStreamTempInputBuffer bufOut
,
643 #endif // HAS_PIPE_INPUT_STREAM
645 if ( process
&& process
->IsRedirected() )
647 #if HAS_PIPE_INPUT_STREAM
648 wxOutputStream
*inStream
=
649 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
651 wxPipeInputStream
*outStream
=
652 new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
654 wxPipeInputStream
*errStream
=
655 new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
657 process
->SetPipeStreams(outStream
, inStream
, errStream
);
659 bufOut
.Init(outStream
);
660 bufErr
.Init(errStream
);
662 execData
.bufOut
= &bufOut
;
663 execData
.bufErr
= &bufErr
;
664 #endif // HAS_PIPE_INPUT_STREAM
674 return traits
->WaitForChild(execData
);
677 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
678 return ERROR_RETURN_CODE
;
682 #undef ERROR_RETURN_CODE
685 // ----------------------------------------------------------------------------
686 // file and directory functions
687 // ----------------------------------------------------------------------------
689 const wxChar
* wxGetHomeDir( wxString
*home
)
691 *home
= wxGetUserHome( wxEmptyString
);
697 if ( tmp
.Last() != wxT(']'))
698 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
700 return home
->c_str();
704 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
705 #else // just for binary compatibility -- there is no 'const' here
706 char *wxGetUserHome( const wxString
&user
)
709 struct passwd
*who
= (struct passwd
*) NULL
;
715 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
718 wxWCharBuffer
buffer( ptr
);
724 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
726 who
= getpwnam(wxSafeConvertWX2MB(ptr
));
729 // We now make sure the the user exists!
732 who
= getpwuid(getuid());
737 who
= getpwnam (user
.mb_str());
740 return wxSafeConvertMB2WX(who
? who
->pw_dir
: 0);
743 // ----------------------------------------------------------------------------
744 // network and user id routines
745 // ----------------------------------------------------------------------------
747 // private utility function which returns output of the given command, removing
748 // the trailing newline
749 static wxString
wxGetCommandOutput(const wxString
&cmd
)
751 FILE *f
= popen(cmd
.ToAscii(), "r");
754 wxLogSysError(_T("Executing \"%s\" failed"), cmd
.c_str());
755 return wxEmptyString
;
762 if ( !fgets(buf
, sizeof(buf
), f
) )
765 s
+= wxString::FromAscii(buf
);
770 if ( !s
.empty() && s
.Last() == _T('\n') )
776 // retrieve either the hostname or FQDN depending on platform (caller must
777 // check whether it's one or the other, this is why this function is for
779 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
781 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
785 // we're using uname() which is POSIX instead of less standard sysinfo()
786 #if defined(HAVE_UNAME)
788 bool ok
= uname(&uts
) != -1;
791 wxStrncpy(buf
, wxSafeConvertMB2WX(uts
.nodename
), sz
- 1);
794 #elif defined(HAVE_GETHOSTNAME)
796 bool ok
= gethostname(cbuf
, sz
) != -1;
799 wxStrncpy(buf
, wxSafeConvertMB2WX(cbuf
), sz
- 1);
802 #else // no uname, no gethostname
803 wxFAIL_MSG(wxT("don't know host name for this machine"));
806 #endif // uname/gethostname
810 wxLogSysError(_("Cannot get the hostname"));
816 bool wxGetHostName(wxChar
*buf
, int sz
)
818 bool ok
= wxGetHostNameInternal(buf
, sz
);
822 // BSD systems return the FQDN, we only want the hostname, so extract
823 // it (we consider that dots are domain separators)
824 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
835 bool wxGetFullHostName(wxChar
*buf
, int sz
)
837 bool ok
= wxGetHostNameInternal(buf
, sz
);
841 if ( !wxStrchr(buf
, wxT('.')) )
843 struct hostent
*host
= gethostbyname(wxSafeConvertWX2MB(buf
));
846 wxLogSysError(_("Cannot get the official hostname"));
852 // the canonical name
853 wxStrncpy(buf
, wxSafeConvertMB2WX(host
->h_name
), sz
);
856 //else: it's already a FQDN (BSD behaves this way)
862 bool wxGetUserId(wxChar
*buf
, int sz
)
867 if ((who
= getpwuid(getuid ())) != NULL
)
869 wxStrncpy (buf
, wxSafeConvertMB2WX(who
->pw_name
), sz
- 1);
876 bool wxGetUserName(wxChar
*buf
, int sz
)
882 if ((who
= getpwuid (getuid ())) != NULL
)
884 char *comma
= strchr(who
->pw_gecos
, ',');
886 *comma
= '\0'; // cut off non-name comment fields
887 wxStrncpy (buf
, wxSafeConvertMB2WX(who
->pw_gecos
), sz
- 1);
892 #else // !HAVE_PW_GECOS
893 return wxGetUserId(buf
, sz
);
894 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
897 bool wxIsPlatform64Bit()
899 wxString machine
= wxGetCommandOutput(wxT("uname -m"));
901 // NOTE: these tests are not 100% reliable!
902 return machine
.Contains(wxT("AMD64")) ||
903 machine
.Contains(wxT("IA64")) ||
904 machine
.Contains(wxT("x64")) ||
905 machine
.Contains(wxT("X64")) ||
906 machine
.Contains(wxT("alpha")) ||
907 machine
.Contains(wxT("hppa64")) ||
908 machine
.Contains(wxT("ppc64"));
911 // these functions are in mac/utils.cpp for wxMac
914 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
918 wxString release
= wxGetCommandOutput(wxT("uname -r"));
919 if ( release
.empty() || wxSscanf(release
, wxT("%d.%d"), &major
, &minor
) != 2 )
921 // failed to get version string or unrecognized format
931 // try to understand which OS are we running
932 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
933 if ( kernel
.empty() )
934 kernel
= wxGetCommandOutput(wxT("uname -o"));
936 if ( kernel
.empty() )
939 return wxPlatformInfo::GetOperatingSystemId(kernel
);
942 wxString
wxGetOsDescription()
944 return wxGetCommandOutput(wxT("uname -s -r -m"));
949 unsigned long wxGetProcessId()
951 return (unsigned long)getpid();
954 wxMemorySize
wxGetFreeMemory()
956 #if defined(__LINUX__)
957 // get it from /proc/meminfo
958 FILE *fp
= fopen("/proc/meminfo", "r");
964 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
966 // /proc/meminfo changed its format in kernel 2.6
967 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
969 unsigned long cached
, buffers
;
970 sscanf(buf
, "MemFree: %ld", &memFree
);
972 fgets(buf
, WXSIZEOF(buf
), fp
);
973 sscanf(buf
, "Buffers: %lu", &buffers
);
975 fgets(buf
, WXSIZEOF(buf
), fp
);
976 sscanf(buf
, "Cached: %lu", &cached
);
978 // add to "MemFree" also the "Buffers" and "Cached" values as
979 // free(1) does as otherwise the value never makes sense: for
980 // kernel 2.6 it's always almost 0
981 memFree
+= buffers
+ cached
;
983 // values here are always expressed in kB and we want bytes
986 else // Linux 2.4 (or < 2.6, anyhow)
988 long memTotal
, memUsed
;
989 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
995 return (wxMemorySize
)memFree
;
997 #elif defined(__SGI__)
998 struct rminfo realmem
;
999 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
1000 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
1001 #elif defined(_SC_AVPHYS_PAGES)
1002 return ((wxMemorySize
)sysconf(_SC_AVPHYS_PAGES
))*sysconf(_SC_PAGESIZE
);
1003 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1006 // can't find it out
1010 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
1012 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1013 // the case to "char *" is needed for AIX 4.3
1015 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
1017 wxLogSysError( wxT("Failed to get file system statistics") );
1022 // under Solaris we also have to use f_frsize field instead of f_bsize
1023 // which is in general a multiple of f_frsize
1025 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1026 #else // HAVE_STATFS
1027 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1028 #endif // HAVE_STATVFS/HAVE_STATFS
1032 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1037 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1041 #else // !HAVE_STATFS && !HAVE_STATVFS
1043 #endif // HAVE_STATFS
1046 // ----------------------------------------------------------------------------
1048 // ----------------------------------------------------------------------------
1050 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1052 // wxGetenv is defined as getenv()
1053 wxChar
*p
= wxGetenv(var
);
1065 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
1067 #if defined(HAVE_SETENV)
1068 return setenv(variable
.mb_str(),
1069 value
? (const char *)wxString(value
).mb_str()
1071 1 /* overwrite */) == 0;
1072 #elif defined(HAVE_PUTENV)
1073 wxString s
= variable
;
1075 s
<< _T('=') << value
;
1077 // transform to ANSI
1078 const wxWX2MBbuf p
= s
.mb_str();
1080 // the string will be free()d by libc
1081 char *buf
= (char *)malloc(strlen(p
) + 1);
1084 return putenv(buf
) == 0;
1085 #else // no way to set an env var
1090 // ----------------------------------------------------------------------------
1092 // ----------------------------------------------------------------------------
1094 #if wxUSE_ON_FATAL_EXCEPTION
1098 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1102 // give the user a chance to do something special about this
1103 wxTheApp
->OnFatalException();
1109 bool wxHandleFatalExceptions(bool doit
)
1112 static bool s_savedHandlers
= false;
1113 static struct sigaction s_handlerFPE
,
1119 if ( doit
&& !s_savedHandlers
)
1121 // install the signal handler
1122 struct sigaction act
;
1124 // some systems extend it with non std fields, so zero everything
1125 memset(&act
, 0, sizeof(act
));
1127 act
.sa_handler
= wxFatalSignalHandler
;
1128 sigemptyset(&act
.sa_mask
);
1131 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1132 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1133 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1134 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1137 wxLogDebug(_T("Failed to install our signal handler."));
1140 s_savedHandlers
= true;
1142 else if ( s_savedHandlers
)
1144 // uninstall the signal handler
1145 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1146 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1147 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1148 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1151 wxLogDebug(_T("Failed to uninstall our signal handler."));
1154 s_savedHandlers
= false;
1156 //else: nothing to do
1161 #endif // wxUSE_ON_FATAL_EXCEPTION
1163 #endif // wxUSE_BASE
1167 // ----------------------------------------------------------------------------
1168 // wxExecute support
1169 // ----------------------------------------------------------------------------
1171 // Darwin doesn't use the same process end detection mechanisms so we don't
1172 // need wxExecute-related helpers for it
1173 #if !(defined(__DARWIN__) && defined(__WXMAC__))
1175 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& execData
)
1177 return execData
.pipeEndProcDetect
.Create();
1180 bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& execData
, int fd
)
1182 return fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
];
1185 void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& execData
)
1187 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
1188 execData
.pipeEndProcDetect
.Close();
1193 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1199 wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
),
1206 wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1208 // nothing to do here, we don't use the pipe
1211 #endif // !Darwin/Darwin
1213 int wxGUIAppTraits::WaitForChild(wxExecuteData
& execData
)
1215 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1217 const int flags
= execData
.flags
;
1219 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1220 // callback function directly if the process terminates before
1221 // the callback can be added to the run loop. Set up the endProcData.
1222 if ( flags
& wxEXEC_SYNC
)
1224 // we may have process for capturing the program output, but it's
1225 // not used in wxEndProcessData in the case of sync execution
1226 endProcData
->process
= NULL
;
1228 // sync execution: indicate it by negating the pid
1229 endProcData
->pid
= -execData
.pid
;
1233 // async execution, nothing special to do -- caller will be
1234 // notified about the process termination if process != NULL, endProcData
1235 // will be deleted in GTK_EndProcessDetector
1236 endProcData
->process
= execData
.process
;
1237 endProcData
->pid
= execData
.pid
;
1241 if ( !(flags
& wxEXEC_NOEVENTS
) )
1243 #if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1244 endProcData
->tag
= wxAddProcessCallbackForPid(endProcData
, execData
.pid
);
1246 endProcData
->tag
= wxAddProcessCallback
1249 execData
.pipeEndProcDetect
.Detach(wxPipe::Read
)
1252 execData
.pipeEndProcDetect
.Close();
1253 #endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1256 if ( flags
& wxEXEC_SYNC
)
1261 wxWindowDisabler
*wd
= flags
& (wxEXEC_NODISABLE
| wxEXEC_NOEVENTS
)
1263 : new wxWindowDisabler
;
1265 if ( flags
& wxEXEC_NOEVENTS
)
1267 // just block waiting for the child to exit
1270 int result
= waitpid(execData
.pid
, &status
, 0);
1274 wxLogLastError(_T("waitpid"));
1279 wxASSERT_MSG( result
== execData
.pid
,
1280 _T("unexpected waitpid() return value") );
1282 if ( WIFEXITED(status
) )
1284 exitcode
= WEXITSTATUS(status
);
1286 else // abnormal termination?
1288 wxASSERT_MSG( WIFSIGNALED(status
),
1289 _T("unexpected child wait status") );
1294 else // !wxEXEC_NOEVENTS
1296 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1297 // process terminates
1298 while ( endProcData
->pid
!= 0 )
1302 #if HAS_PIPE_INPUT_STREAM
1303 if ( execData
.bufOut
)
1305 execData
.bufOut
->Update();
1309 if ( execData
.bufErr
)
1311 execData
.bufErr
->Update();
1314 #endif // HAS_PIPE_INPUT_STREAM
1316 // don't consume 100% of the CPU while we're sitting in this
1321 // give GTK+ a chance to call GTK_EndProcessDetector here and
1322 // also repaint the GUI
1326 exitcode
= endProcData
->exitcode
;
1334 else // async execution
1336 return execData
.pid
;
1343 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
1345 // notify user about termination if required
1346 if ( proc_data
->process
)
1348 proc_data
->process
->OnTerminate(proc_data
->pid
, proc_data
->exitcode
);
1352 if ( proc_data
->pid
> 0 )
1358 // let wxExecute() know that the process has terminated
1363 #endif // wxUSE_BASE