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"
28 #include "wx/wxcrtvararg.h"
31 #include "wx/apptrait.h"
33 #include "wx/process.h"
34 #include "wx/thread.h"
36 #include "wx/wfstream.h"
38 #include "wx/unix/execute.h"
39 #include "wx/unix/private.h"
42 #include <sys/wait.h> // waitpid()
44 #ifdef HAVE_SYS_SELECT_H
45 # include <sys/select.h>
48 #define HAS_PIPE_INPUT_STREAM (wxUSE_STREAMS && wxUSE_FILE)
50 #if HAS_PIPE_INPUT_STREAM
52 // define this to let wxexec.cpp know that we know what we're doing
53 #define _WX_USED_BY_WXEXECUTE_
54 #include "../common/execcmn.cpp"
56 #endif // HAS_PIPE_INPUT_STREAM
60 #if defined(__MWERKS__) && defined(__MACH__)
61 #ifndef WXWIN_OS_DESCRIPTION
62 #define WXWIN_OS_DESCRIPTION "MacOS X"
64 #ifndef HAVE_NANOSLEEP
65 #define HAVE_NANOSLEEP
71 // our configure test believes we can use sigaction() if the function is
72 // available but Metrowekrs with MSL run-time does have the function but
73 // doesn't have sigaction struct so finally we can't use it...
75 #undef wxUSE_ON_FATAL_EXCEPTION
76 #define wxUSE_ON_FATAL_EXCEPTION 0
80 // not only the statfs syscall is called differently depending on platform, but
81 // one of its incarnations, statvfs(), takes different arguments under
82 // different platforms and even different versions of the same system (Solaris
83 // 7 and 8): if you want to test for this, don't forget that the problems only
84 // appear if the large files support is enabled
87 #include <sys/param.h>
88 #include <sys/mount.h>
91 #endif // __BSD__/!__BSD__
93 #define wxStatfs statfs
95 #ifndef HAVE_STATFS_DECL
96 // some systems lack statfs() prototype in the system headers (AIX 4)
97 extern "C" int statfs(const char *path
, struct statfs
*buf
);
102 #include <sys/statvfs.h>
104 #define wxStatfs statvfs
105 #endif // HAVE_STATVFS
107 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
108 // WX_STATFS_T is detected by configure
109 #define wxStatfs_t WX_STATFS_T
112 // SGI signal.h defines signal handler arguments differently depending on
113 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
114 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
115 #define _LANGUAGE_C_PLUS_PLUS 1
121 #include <sys/stat.h>
122 #include <sys/types.h>
123 #include <sys/wait.h>
128 #include <fcntl.h> // for O_WRONLY and friends
129 #include <time.h> // nanosleep() and/or usleep()
130 #include <ctype.h> // isspace()
131 #include <sys/time.h> // needed for FD_SETSIZE
134 #include <sys/utsname.h> // for uname()
137 // Used by wxGetFreeMemory().
139 #include <sys/sysmp.h>
140 #include <sys/sysinfo.h> // for SAGET and MINFO structures
143 // ----------------------------------------------------------------------------
144 // conditional compilation
145 // ----------------------------------------------------------------------------
147 // many versions of Unices have this function, but it is not defined in system
148 // headers - please add your system here if it is the case for your OS.
149 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
150 #if !defined(HAVE_USLEEP) && \
151 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
152 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
153 defined(__osf__) || defined(__EMX__))
157 /* I copied this from the XFree86 diffs. AV. */
158 #define INCL_DOSPROCESS
160 inline void usleep(unsigned long delay
)
162 DosSleep(delay
? (delay
/1000l) : 1l);
165 int usleep(unsigned int usec
);
166 #endif // __EMX__/Unix
169 #define HAVE_USLEEP 1
170 #endif // Unices without usleep()
172 // ============================================================================
174 // ============================================================================
176 // ----------------------------------------------------------------------------
178 // ----------------------------------------------------------------------------
180 void wxSleep(int nSecs
)
185 void wxMicroSleep(unsigned long microseconds
)
187 #if defined(HAVE_NANOSLEEP)
189 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
190 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
192 // we're not interested in remaining time nor in return value
193 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
194 #elif defined(HAVE_USLEEP)
195 // uncomment this if you feel brave or if you are sure that your version
196 // of Solaris has a safe usleep() function but please notice that usleep()
197 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
198 // documented as MT-Safe
199 #if defined(__SUN__) && wxUSE_THREADS
200 #error "usleep() cannot be used in MT programs under Solaris."
203 usleep(microseconds
);
204 #elif defined(HAVE_SLEEP)
205 // under BeOS sleep() takes seconds (what about other platforms, if any?)
206 sleep(microseconds
* 1000000);
207 #else // !sleep function
208 #error "usleep() or nanosleep() function required for wxMicroSleep"
209 #endif // sleep function
212 void wxMilliSleep(unsigned long milliseconds
)
214 wxMicroSleep(milliseconds
*1000);
217 // ----------------------------------------------------------------------------
218 // process management
219 // ----------------------------------------------------------------------------
221 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
223 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
226 switch ( err
? errno
: 0 )
233 *rc
= wxKILL_BAD_SIGNAL
;
237 *rc
= wxKILL_ACCESS_DENIED
;
241 *rc
= wxKILL_NO_PROCESS
;
245 // this goes against Unix98 docs so log it
246 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
256 #define WXEXECUTE_NARGS 127
258 #if defined(__DARWIN__)
259 long wxMacExecute(wxChar
**argv
,
264 long wxExecute( const wxString
& command
, int flags
, wxProcess
*process
)
266 wxCHECK_MSG( !command
.empty(), 0, wxT("can't exec empty command") );
268 wxLogTrace(wxT("exec"), wxT("Executing \"%s\""), command
.c_str());
271 // fork() doesn't mix well with POSIX threads: on many systems the program
272 // deadlocks or crashes for some reason. Probably our code is buggy and
273 // doesn't do something which must be done to allow this to work, but I
274 // don't know what yet, so for now just warn the user (this is the least we
276 wxASSERT_MSG( wxThread::IsMain(),
277 _T("wxExecute() can be called only from the main thread") );
278 #endif // wxUSE_THREADS
281 wxChar
*argv
[WXEXECUTE_NARGS
];
283 const wxChar
*cptr
= command
.c_str();
284 wxChar quotechar
= wxT('\0'); // is arg quoted?
285 bool escaped
= false;
287 // split the command line in arguments
290 argument
= wxEmptyString
;
291 quotechar
= wxT('\0');
293 // eat leading whitespace:
294 while ( wxIsspace(*cptr
) )
297 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
302 if ( *cptr
== wxT('\\') && ! escaped
)
309 // all other characters:
313 // have we reached the end of the argument?
314 if ( (*cptr
== quotechar
&& ! escaped
)
315 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
316 || *cptr
== wxT('\0') )
318 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
319 wxT("too many arguments in wxExecute") );
321 argv
[argc
] = new wxChar
[argument
.length() + 1];
322 wxStrcpy(argv
[argc
], argument
.c_str());
325 // if not at end of buffer, swallow last character:
329 break; // done with this one, start over
336 #if defined(__DARWIN__)
337 // wxMacExecute only executes app bundles.
338 // It returns an error code if the target is not an app bundle, thus falling
339 // through to the regular wxExecute for non app bundles.
340 lRc
= wxMacExecute(argv
, flags
, process
);
341 if( lRc
!= ((flags
& wxEXEC_SYNC
) ? -1 : 0))
345 // do execute the command
346 lRc
= wxExecute(argv
, flags
, process
);
351 delete [] argv
[argc
++];
356 // ----------------------------------------------------------------------------
358 // ----------------------------------------------------------------------------
360 static wxString
wxMakeShellCommand(const wxString
& command
)
365 // just an interactive shell
370 // execute command in a shell
371 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
377 bool wxShell(const wxString
& command
)
379 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
382 bool wxShell(const wxString
& command
, wxArrayString
& output
)
384 wxCHECK_MSG( !command
.empty(), false, _T("can't exec shell non interactively") );
386 return wxExecute(wxMakeShellCommand(command
), output
);
389 // Shutdown or reboot the PC
390 bool wxShutdown(wxShutdownFlags wFlags
)
395 case wxSHUTDOWN_POWEROFF
:
399 case wxSHUTDOWN_REBOOT
:
404 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
408 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
411 // ----------------------------------------------------------------------------
412 // wxStream classes to support IO redirection in wxExecute
413 // ----------------------------------------------------------------------------
415 #if HAS_PIPE_INPUT_STREAM
417 bool wxPipeInputStream::CanRead() const
419 if ( m_lasterror
== wxSTREAM_EOF
)
422 // check if there is any input available
427 const int fd
= m_file
->fd();
432 wxFD_SET(fd
, &readfds
);
434 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
437 wxLogSysError(_("Impossible to get child process input"));
444 wxFAIL_MSG(_T("unexpected select() return value"));
445 // still fall through
448 // input available -- or maybe not, as select() returns 1 when a
449 // read() will complete without delay, but it could still not read
455 #endif // HAS_PIPE_INPUT_STREAM
457 // ----------------------------------------------------------------------------
458 // wxExecute: the real worker function
459 // ----------------------------------------------------------------------------
461 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*process
)
463 // for the sync execution, we return -1 to indicate failure, but for async
464 // case we return 0 which is never a valid PID
466 // we define this as a macro, not a variable, to avoid compiler warnings
467 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
468 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
470 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
474 char *mb_argv
[WXEXECUTE_NARGS
];
476 while (argv
[mb_argc
])
478 wxWX2MBbuf mb_arg
= wxSafeConvertWX2MB(argv
[mb_argc
]);
479 mb_argv
[mb_argc
] = strdup(mb_arg
);
482 mb_argv
[mb_argc
] = (char *) NULL
;
484 // this macro will free memory we used above
485 #define ARGS_CLEANUP \
486 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
487 free(mb_argv[mb_argc])
489 // no need for cleanup
492 wxChar
**mb_argv
= argv
;
493 #endif // Unicode/ANSI
495 // we want this function to work even if there is no wxApp so ensure that
496 // we have a valid traits pointer
497 wxConsoleAppTraits traitsConsole
;
498 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
500 traits
= &traitsConsole
;
502 // this struct contains all information which we pass to and from
503 // wxAppTraits methods
504 wxExecuteData execData
;
505 execData
.flags
= flags
;
506 execData
.process
= process
;
509 if ( !traits
->CreateEndProcessPipe(execData
) )
511 wxLogError( _("Failed to execute '%s'\n"), *argv
);
515 return ERROR_RETURN_CODE
;
518 // pipes for inter process communication
519 wxPipe pipeIn
, // stdin
523 if ( process
&& process
->IsRedirected() )
525 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
527 wxLogError( _("Failed to execute '%s'\n"), *argv
);
531 return ERROR_RETURN_CODE
;
537 // NB: do *not* use vfork() here, it completely breaks this code for some
538 // reason under Solaris (and maybe others, although not under Linux)
539 // But on OpenVMS we do not have fork so we have to use vfork and
540 // cross our fingers that it works.
546 if ( pid
== -1 ) // error?
548 wxLogSysError( _("Fork failed") );
552 return ERROR_RETURN_CODE
;
554 else if ( pid
== 0 ) // we're in child
556 // These lines close the open file descriptors to to avoid any
557 // input/output which might block the process or irritate the user. If
558 // one wants proper IO for the subprocess, the right thing to do is to
559 // start an xterm executing it.
560 if ( !(flags
& wxEXEC_SYNC
) )
562 // FD_SETSIZE is unsigned under BSD, signed under other platforms
563 // so we need a cast to avoid warnings on all platforms
564 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
566 if ( fd
== pipeIn
[wxPipe::Read
]
567 || fd
== pipeOut
[wxPipe::Write
]
568 || fd
== pipeErr
[wxPipe::Write
]
569 || traits
->IsWriteFDOfEndProcessPipe(execData
, fd
) )
571 // don't close this one, we still need it
575 // leave stderr opened too, it won't do any harm
576 if ( fd
!= STDERR_FILENO
)
581 #if !defined(__VMS) && !defined(__EMX__)
582 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
584 // Set process group to child process' pid. Then killing -pid
585 // of the parent will kill the process and all of its children.
590 // reading side can be safely closed but we should keep the write one
592 traits
->DetachWriteFDOfEndProcessPipe(execData
);
594 // redirect stdin, stdout and stderr
597 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
598 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
599 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
601 wxLogSysError(_("Failed to redirect child process input/output"));
609 execvp (*mb_argv
, mb_argv
);
611 fprintf(stderr
, "execvp(");
612 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
613 for ( char **ppc_
= mb_argv
; *ppc_
; ppc_
++ )
614 fprintf(stderr
, "%s%s", ppc_
== mb_argv
? "" : ", ", *ppc_
);
615 fprintf(stderr
, ") failed with error %d!\n", errno
);
617 // there is no return after successful exec()
620 // some compilers complain about missing return - of course, they
621 // should know that exit() doesn't return but what else can we do if
624 // and, sure enough, other compilers complain about unreachable code
625 // after exit() call, so we can just always have return here...
626 #if defined(__VMS) || defined(__INTEL_COMPILER)
630 else // we're in parent
634 // save it for WaitForChild() use
637 // prepare for IO redirection
639 #if HAS_PIPE_INPUT_STREAM
640 // the input buffer bufOut is connected to stdout, this is why it is
641 // called bufOut and not bufIn
642 wxStreamTempInputBuffer bufOut
,
644 #endif // HAS_PIPE_INPUT_STREAM
646 if ( process
&& process
->IsRedirected() )
648 #if HAS_PIPE_INPUT_STREAM
649 wxOutputStream
*inStream
=
650 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
652 wxPipeInputStream
*outStream
=
653 new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
655 wxPipeInputStream
*errStream
=
656 new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
658 process
->SetPipeStreams(outStream
, inStream
, errStream
);
660 bufOut
.Init(outStream
);
661 bufErr
.Init(errStream
);
663 execData
.bufOut
= &bufOut
;
664 execData
.bufErr
= &bufErr
;
665 #endif // HAS_PIPE_INPUT_STREAM
675 return traits
->WaitForChild(execData
);
678 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
679 return ERROR_RETURN_CODE
;
683 #undef ERROR_RETURN_CODE
686 // ----------------------------------------------------------------------------
687 // file and directory functions
688 // ----------------------------------------------------------------------------
690 const wxChar
* wxGetHomeDir( wxString
*home
)
692 *home
= wxGetUserHome( wxEmptyString
);
698 if ( tmp
.Last() != wxT(']'))
699 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
701 return home
->c_str();
705 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
706 #else // just for binary compatibility -- there is no 'const' here
707 char *wxGetUserHome( const wxString
&user
)
710 struct passwd
*who
= (struct passwd
*) NULL
;
716 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
719 wxWCharBuffer
buffer( ptr
);
725 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
727 who
= getpwnam(wxSafeConvertWX2MB(ptr
));
730 // We now make sure the the user exists!
733 who
= getpwuid(getuid());
738 who
= getpwnam (user
.mb_str());
741 return wxSafeConvertMB2WX(who
? who
->pw_dir
: 0);
744 // ----------------------------------------------------------------------------
745 // network and user id routines
746 // ----------------------------------------------------------------------------
748 // private utility function which returns output of the given command, removing
749 // the trailing newline
750 static wxString
wxGetCommandOutput(const wxString
&cmd
)
752 FILE *f
= popen(cmd
.ToAscii(), "r");
755 wxLogSysError(_T("Executing \"%s\" failed"), cmd
.c_str());
756 return wxEmptyString
;
763 if ( !fgets(buf
, sizeof(buf
), f
) )
766 s
+= wxString::FromAscii(buf
);
771 if ( !s
.empty() && s
.Last() == _T('\n') )
777 // retrieve either the hostname or FQDN depending on platform (caller must
778 // check whether it's one or the other, this is why this function is for
780 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
782 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
786 // we're using uname() which is POSIX instead of less standard sysinfo()
787 #if defined(HAVE_UNAME)
789 bool ok
= uname(&uts
) != -1;
792 wxStrncpy(buf
, wxSafeConvertMB2WX(uts
.nodename
), sz
- 1);
795 #elif defined(HAVE_GETHOSTNAME)
797 bool ok
= gethostname(cbuf
, sz
) != -1;
800 wxStrncpy(buf
, wxSafeConvertMB2WX(cbuf
), sz
- 1);
803 #else // no uname, no gethostname
804 wxFAIL_MSG(wxT("don't know host name for this machine"));
807 #endif // uname/gethostname
811 wxLogSysError(_("Cannot get the hostname"));
817 bool wxGetHostName(wxChar
*buf
, int sz
)
819 bool ok
= wxGetHostNameInternal(buf
, sz
);
823 // BSD systems return the FQDN, we only want the hostname, so extract
824 // it (we consider that dots are domain separators)
825 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
836 bool wxGetFullHostName(wxChar
*buf
, int sz
)
838 bool ok
= wxGetHostNameInternal(buf
, sz
);
842 if ( !wxStrchr(buf
, wxT('.')) )
844 struct hostent
*host
= gethostbyname(wxSafeConvertWX2MB(buf
));
847 wxLogSysError(_("Cannot get the official hostname"));
853 // the canonical name
854 wxStrncpy(buf
, wxSafeConvertMB2WX(host
->h_name
), sz
);
857 //else: it's already a FQDN (BSD behaves this way)
863 bool wxGetUserId(wxChar
*buf
, int sz
)
868 if ((who
= getpwuid(getuid ())) != NULL
)
870 wxStrncpy (buf
, wxSafeConvertMB2WX(who
->pw_name
), sz
- 1);
877 bool wxGetUserName(wxChar
*buf
, int sz
)
883 if ((who
= getpwuid (getuid ())) != NULL
)
885 char *comma
= strchr(who
->pw_gecos
, ',');
887 *comma
= '\0'; // cut off non-name comment fields
888 wxStrncpy (buf
, wxSafeConvertMB2WX(who
->pw_gecos
), sz
- 1);
893 #else // !HAVE_PW_GECOS
894 return wxGetUserId(buf
, sz
);
895 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
898 bool wxIsPlatform64Bit()
900 wxString machine
= wxGetCommandOutput(wxT("uname -m"));
902 // NOTE: these tests are not 100% reliable!
903 return machine
.Contains(wxT("AMD64")) ||
904 machine
.Contains(wxT("IA64")) ||
905 machine
.Contains(wxT("x64")) ||
906 machine
.Contains(wxT("X64")) ||
907 machine
.Contains(wxT("alpha")) ||
908 machine
.Contains(wxT("hppa64")) ||
909 machine
.Contains(wxT("ppc64"));
912 // these functions are in mac/utils.cpp for wxMac
915 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
919 wxString release
= wxGetCommandOutput(wxT("uname -r"));
920 if ( release
.empty() || wxSscanf(release
, wxT("%d.%d"), &major
, &minor
) != 2 )
922 // failed to get version string or unrecognized format
932 // try to understand which OS are we running
933 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
934 if ( kernel
.empty() )
935 kernel
= wxGetCommandOutput(wxT("uname -o"));
937 if ( kernel
.empty() )
940 return wxPlatformInfo::GetOperatingSystemId(kernel
);
943 wxString
wxGetOsDescription()
945 return wxGetCommandOutput(wxT("uname -s -r -m"));
950 unsigned long wxGetProcessId()
952 return (unsigned long)getpid();
955 wxMemorySize
wxGetFreeMemory()
957 #if defined(__LINUX__)
958 // get it from /proc/meminfo
959 FILE *fp
= fopen("/proc/meminfo", "r");
965 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
967 // /proc/meminfo changed its format in kernel 2.6
968 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
970 unsigned long cached
, buffers
;
971 sscanf(buf
, "MemFree: %ld", &memFree
);
973 fgets(buf
, WXSIZEOF(buf
), fp
);
974 sscanf(buf
, "Buffers: %lu", &buffers
);
976 fgets(buf
, WXSIZEOF(buf
), fp
);
977 sscanf(buf
, "Cached: %lu", &cached
);
979 // add to "MemFree" also the "Buffers" and "Cached" values as
980 // free(1) does as otherwise the value never makes sense: for
981 // kernel 2.6 it's always almost 0
982 memFree
+= buffers
+ cached
;
984 // values here are always expressed in kB and we want bytes
987 else // Linux 2.4 (or < 2.6, anyhow)
989 long memTotal
, memUsed
;
990 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
996 return (wxMemorySize
)memFree
;
998 #elif defined(__SGI__)
999 struct rminfo realmem
;
1000 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
1001 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
1002 #elif defined(_SC_AVPHYS_PAGES)
1003 return ((wxMemorySize
)sysconf(_SC_AVPHYS_PAGES
))*sysconf(_SC_PAGESIZE
);
1004 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1007 // can't find it out
1011 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
1013 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1014 // the case to "char *" is needed for AIX 4.3
1016 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
1018 wxLogSysError( wxT("Failed to get file system statistics") );
1023 // under Solaris we also have to use f_frsize field instead of f_bsize
1024 // which is in general a multiple of f_frsize
1026 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1027 #else // HAVE_STATFS
1028 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1029 #endif // HAVE_STATVFS/HAVE_STATFS
1033 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1038 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1042 #else // !HAVE_STATFS && !HAVE_STATVFS
1044 #endif // HAVE_STATFS
1047 // ----------------------------------------------------------------------------
1049 // ----------------------------------------------------------------------------
1051 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1053 // wxGetenv is defined as getenv()
1054 wxChar
*p
= wxGetenv(var
);
1066 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
1068 #if defined(HAVE_SETENV)
1069 return setenv(variable
.mb_str(),
1070 value
? (const char *)wxString(value
).mb_str()
1072 1 /* overwrite */) == 0;
1073 #elif defined(HAVE_PUTENV)
1074 wxString s
= variable
;
1076 s
<< _T('=') << value
;
1078 // transform to ANSI
1079 const wxWX2MBbuf p
= s
.mb_str();
1081 // the string will be free()d by libc
1082 char *buf
= (char *)malloc(strlen(p
) + 1);
1085 return putenv(buf
) == 0;
1086 #else // no way to set an env var
1091 // ----------------------------------------------------------------------------
1093 // ----------------------------------------------------------------------------
1095 #if wxUSE_ON_FATAL_EXCEPTION
1099 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1103 // give the user a chance to do something special about this
1104 wxTheApp
->OnFatalException();
1110 bool wxHandleFatalExceptions(bool doit
)
1113 static bool s_savedHandlers
= false;
1114 static struct sigaction s_handlerFPE
,
1120 if ( doit
&& !s_savedHandlers
)
1122 // install the signal handler
1123 struct sigaction act
;
1125 // some systems extend it with non std fields, so zero everything
1126 memset(&act
, 0, sizeof(act
));
1128 act
.sa_handler
= wxFatalSignalHandler
;
1129 sigemptyset(&act
.sa_mask
);
1132 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1133 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1134 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1135 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1138 wxLogDebug(_T("Failed to install our signal handler."));
1141 s_savedHandlers
= true;
1143 else if ( s_savedHandlers
)
1145 // uninstall the signal handler
1146 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1147 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1148 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1149 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1152 wxLogDebug(_T("Failed to uninstall our signal handler."));
1155 s_savedHandlers
= false;
1157 //else: nothing to do
1162 #endif // wxUSE_ON_FATAL_EXCEPTION
1164 #endif // wxUSE_BASE
1168 // ----------------------------------------------------------------------------
1169 // wxExecute support
1170 // ----------------------------------------------------------------------------
1172 // Darwin doesn't use the same process end detection mechanisms so we don't
1173 // need wxExecute-related helpers for it
1174 #if !(defined(__DARWIN__) && defined(__WXMAC__))
1176 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& execData
)
1178 return execData
.pipeEndProcDetect
.Create();
1181 bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& execData
, int fd
)
1183 return fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
];
1186 void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& execData
)
1188 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
1189 execData
.pipeEndProcDetect
.Close();
1194 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1200 wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
),
1207 wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1209 // nothing to do here, we don't use the pipe
1212 #endif // !Darwin/Darwin
1214 int wxGUIAppTraits::WaitForChild(wxExecuteData
& execData
)
1216 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1218 const int flags
= execData
.flags
;
1220 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1221 // callback function directly if the process terminates before
1222 // the callback can be added to the run loop. Set up the endProcData.
1223 if ( flags
& wxEXEC_SYNC
)
1225 // we may have process for capturing the program output, but it's
1226 // not used in wxEndProcessData in the case of sync execution
1227 endProcData
->process
= NULL
;
1229 // sync execution: indicate it by negating the pid
1230 endProcData
->pid
= -execData
.pid
;
1234 // async execution, nothing special to do -- caller will be
1235 // notified about the process termination if process != NULL, endProcData
1236 // will be deleted in GTK_EndProcessDetector
1237 endProcData
->process
= execData
.process
;
1238 endProcData
->pid
= execData
.pid
;
1242 if ( !(flags
& wxEXEC_NOEVENTS
) )
1244 #if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1245 endProcData
->tag
= wxAddProcessCallbackForPid(endProcData
, execData
.pid
);
1247 endProcData
->tag
= wxAddProcessCallback
1250 execData
.pipeEndProcDetect
.Detach(wxPipe::Read
)
1253 execData
.pipeEndProcDetect
.Close();
1254 #endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1257 if ( flags
& wxEXEC_SYNC
)
1262 wxWindowDisabler
*wd
= flags
& (wxEXEC_NODISABLE
| wxEXEC_NOEVENTS
)
1264 : new wxWindowDisabler
;
1266 if ( flags
& wxEXEC_NOEVENTS
)
1268 // just block waiting for the child to exit
1271 int result
= waitpid(execData
.pid
, &status
, 0);
1275 wxLogLastError(_T("waitpid"));
1280 wxASSERT_MSG( result
== execData
.pid
,
1281 _T("unexpected waitpid() return value") );
1283 if ( WIFEXITED(status
) )
1285 exitcode
= WEXITSTATUS(status
);
1287 else // abnormal termination?
1289 wxASSERT_MSG( WIFSIGNALED(status
),
1290 _T("unexpected child wait status") );
1295 else // !wxEXEC_NOEVENTS
1297 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1298 // process terminates
1299 while ( endProcData
->pid
!= 0 )
1303 #if HAS_PIPE_INPUT_STREAM
1304 if ( execData
.bufOut
)
1306 execData
.bufOut
->Update();
1310 if ( execData
.bufErr
)
1312 execData
.bufErr
->Update();
1315 #endif // HAS_PIPE_INPUT_STREAM
1317 // don't consume 100% of the CPU while we're sitting in this
1322 // give GTK+ a chance to call GTK_EndProcessDetector here and
1323 // also repaint the GUI
1327 exitcode
= endProcData
->exitcode
;
1335 else // async execution
1337 return execData
.pid
;
1344 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
1346 // notify user about termination if required
1347 if ( proc_data
->process
)
1349 proc_data
->process
->OnTerminate(proc_data
->pid
, proc_data
->exitcode
);
1353 if ( proc_data
->pid
> 0 )
1359 // let wxExecute() know that the process has terminated
1364 #endif // wxUSE_BASE