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"
42 #ifdef HAVE_SYS_SELECT_H
43 # include <sys/select.h>
46 #define HAS_PIPE_INPUT_STREAM (wxUSE_STREAMS && wxUSE_FILE)
48 #if HAS_PIPE_INPUT_STREAM
50 // define this to let wxexec.cpp know that we know what we're doing
51 #define _WX_USED_BY_WXEXECUTE_
52 #include "../common/execcmn.cpp"
54 #endif // HAS_PIPE_INPUT_STREAM
58 #if defined(__MWERKS__) && defined(__MACH__)
59 #ifndef WXWIN_OS_DESCRIPTION
60 #define WXWIN_OS_DESCRIPTION "MacOS X"
62 #ifndef HAVE_NANOSLEEP
63 #define HAVE_NANOSLEEP
69 // our configure test believes we can use sigaction() if the function is
70 // available but Metrowekrs with MSL run-time does have the function but
71 // doesn't have sigaction struct so finally we can't use it...
73 #undef wxUSE_ON_FATAL_EXCEPTION
74 #define wxUSE_ON_FATAL_EXCEPTION 0
78 // not only the statfs syscall is called differently depending on platform, but
79 // one of its incarnations, statvfs(), takes different arguments under
80 // different platforms and even different versions of the same system (Solaris
81 // 7 and 8): if you want to test for this, don't forget that the problems only
82 // appear if the large files support is enabled
85 #include <sys/param.h>
86 #include <sys/mount.h>
89 #endif // __BSD__/!__BSD__
91 #define wxStatfs statfs
93 #ifndef HAVE_STATFS_DECL
94 // some systems lack statfs() prototype in the system headers (AIX 4)
95 extern "C" int statfs(const char *path
, struct statfs
*buf
);
100 #include <sys/statvfs.h>
102 #define wxStatfs statvfs
103 #endif // HAVE_STATVFS
105 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
106 // WX_STATFS_T is detected by configure
107 #define wxStatfs_t WX_STATFS_T
110 // SGI signal.h defines signal handler arguments differently depending on
111 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
112 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
113 #define _LANGUAGE_C_PLUS_PLUS 1
119 #include <sys/stat.h>
120 #include <sys/types.h>
121 #include <sys/wait.h>
126 #include <fcntl.h> // for O_WRONLY and friends
127 #include <time.h> // nanosleep() and/or usleep()
128 #include <ctype.h> // isspace()
129 #include <sys/time.h> // needed for FD_SETSIZE
132 #include <sys/utsname.h> // for uname()
135 // Used by wxGetFreeMemory().
137 #include <sys/sysmp.h>
138 #include <sys/sysinfo.h> // for SAGET and MINFO structures
141 // ----------------------------------------------------------------------------
142 // conditional compilation
143 // ----------------------------------------------------------------------------
145 // many versions of Unices have this function, but it is not defined in system
146 // headers - please add your system here if it is the case for your OS.
147 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
148 #if !defined(HAVE_USLEEP) && \
149 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
150 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
151 defined(__osf__) || defined(__EMX__))
155 /* I copied this from the XFree86 diffs. AV. */
156 #define INCL_DOSPROCESS
158 inline void usleep(unsigned long delay
)
160 DosSleep(delay
? (delay
/1000l) : 1l);
163 int usleep(unsigned int usec
);
164 #endif // __EMX__/Unix
167 #define HAVE_USLEEP 1
168 #endif // Unices without usleep()
170 // ============================================================================
172 // ============================================================================
174 // ----------------------------------------------------------------------------
176 // ----------------------------------------------------------------------------
178 void wxSleep(int nSecs
)
183 void wxMicroSleep(unsigned long microseconds
)
185 #if defined(HAVE_NANOSLEEP)
187 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
188 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
190 // we're not interested in remaining time nor in return value
191 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
192 #elif defined(HAVE_USLEEP)
193 // uncomment this if you feel brave or if you are sure that your version
194 // of Solaris has a safe usleep() function but please notice that usleep()
195 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
196 // documented as MT-Safe
197 #if defined(__SUN__) && wxUSE_THREADS
198 #error "usleep() cannot be used in MT programs under Solaris."
201 usleep(microseconds
);
202 #elif defined(HAVE_SLEEP)
203 // under BeOS sleep() takes seconds (what about other platforms, if any?)
204 sleep(microseconds
* 1000000);
205 #else // !sleep function
206 #error "usleep() or nanosleep() function required for wxMicroSleep"
207 #endif // sleep function
210 void wxMilliSleep(unsigned long milliseconds
)
212 wxMicroSleep(milliseconds
*1000);
215 // ----------------------------------------------------------------------------
216 // process management
217 // ----------------------------------------------------------------------------
219 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
221 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
224 switch ( err
? errno
: 0 )
231 *rc
= wxKILL_BAD_SIGNAL
;
235 *rc
= wxKILL_ACCESS_DENIED
;
239 *rc
= wxKILL_NO_PROCESS
;
243 // this goes against Unix98 docs so log it
244 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
254 #define WXEXECUTE_NARGS 127
256 #if defined(__DARWIN__)
257 long wxMacExecute(wxChar
**argv
,
262 long wxExecute( const wxString
& command
, int flags
, wxProcess
*process
)
264 wxCHECK_MSG( !command
.empty(), 0, wxT("can't exec empty command") );
265 wxLogDebug(wxString(wxT("Launching: ")) + command
);
268 // fork() doesn't mix well with POSIX threads: on many systems the program
269 // deadlocks or crashes for some reason. Probably our code is buggy and
270 // doesn't do something which must be done to allow this to work, but I
271 // don't know what yet, so for now just warn the user (this is the least we
273 wxASSERT_MSG( wxThread::IsMain(),
274 _T("wxExecute() can be called only from the main thread") );
275 #endif // wxUSE_THREADS
278 wxChar
*argv
[WXEXECUTE_NARGS
];
280 const wxChar
*cptr
= command
.c_str();
281 wxChar quotechar
= wxT('\0'); // is arg quoted?
282 bool escaped
= false;
284 // split the command line in arguments
287 argument
= wxEmptyString
;
288 quotechar
= wxT('\0');
290 // eat leading whitespace:
291 while ( wxIsspace(*cptr
) )
294 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
299 if ( *cptr
== wxT('\\') && ! escaped
)
306 // all other characters:
310 // have we reached the end of the argument?
311 if ( (*cptr
== quotechar
&& ! escaped
)
312 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
313 || *cptr
== wxT('\0') )
315 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
316 wxT("too many arguments in wxExecute") );
318 argv
[argc
] = new wxChar
[argument
.length() + 1];
319 wxStrcpy(argv
[argc
], argument
.c_str());
322 // if not at end of buffer, swallow last character:
326 break; // done with this one, start over
333 #if defined(__DARWIN__)
334 // wxMacExecute only executes app bundles.
335 // It returns an error code if the target is not an app bundle, thus falling
336 // through to the regular wxExecute for non app bundles.
337 lRc
= wxMacExecute(argv
, flags
, process
);
338 if( lRc
!= ((flags
& wxEXEC_SYNC
) ? -1 : 0))
342 // do execute the command
343 lRc
= wxExecute(argv
, flags
, process
);
348 delete [] argv
[argc
++];
353 // ----------------------------------------------------------------------------
355 // ----------------------------------------------------------------------------
357 static wxString
wxMakeShellCommand(const wxString
& command
)
362 // just an interactive shell
367 // execute command in a shell
368 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
374 bool wxShell(const wxString
& command
)
376 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
379 bool wxShell(const wxString
& command
, wxArrayString
& output
)
381 wxCHECK_MSG( !command
.empty(), false, _T("can't exec shell non interactively") );
383 return wxExecute(wxMakeShellCommand(command
), output
);
386 // Shutdown or reboot the PC
387 bool wxShutdown(wxShutdownFlags wFlags
)
392 case wxSHUTDOWN_POWEROFF
:
396 case wxSHUTDOWN_REBOOT
:
401 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
405 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
408 // ----------------------------------------------------------------------------
409 // wxStream classes to support IO redirection in wxExecute
410 // ----------------------------------------------------------------------------
412 #if HAS_PIPE_INPUT_STREAM
414 bool wxPipeInputStream::CanRead() const
416 if ( m_lasterror
== wxSTREAM_EOF
)
419 // check if there is any input available
424 const int fd
= m_file
->fd();
429 wxFD_SET(fd
, &readfds
);
431 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
434 wxLogSysError(_("Impossible to get child process input"));
441 wxFAIL_MSG(_T("unexpected select() return value"));
442 // still fall through
445 // input available -- or maybe not, as select() returns 1 when a
446 // read() will complete without delay, but it could still not read
452 #endif // HAS_PIPE_INPUT_STREAM
454 // ----------------------------------------------------------------------------
455 // wxExecute: the real worker function
456 // ----------------------------------------------------------------------------
458 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*process
)
460 // for the sync execution, we return -1 to indicate failure, but for async
461 // case we return 0 which is never a valid PID
463 // we define this as a macro, not a variable, to avoid compiler warnings
464 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
465 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
467 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
471 char *mb_argv
[WXEXECUTE_NARGS
];
473 while (argv
[mb_argc
])
475 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
476 mb_argv
[mb_argc
] = strdup(mb_arg
);
479 mb_argv
[mb_argc
] = (char *) NULL
;
481 // this macro will free memory we used above
482 #define ARGS_CLEANUP \
483 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
484 free(mb_argv[mb_argc])
486 // no need for cleanup
489 wxChar
**mb_argv
= argv
;
490 #endif // Unicode/ANSI
492 // we want this function to work even if there is no wxApp so ensure that
493 // we have a valid traits pointer
494 wxConsoleAppTraits traitsConsole
;
495 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
497 traits
= &traitsConsole
;
499 // this struct contains all information which we pass to and from
500 // wxAppTraits methods
501 wxExecuteData execData
;
502 execData
.flags
= flags
;
503 execData
.process
= process
;
506 if ( !traits
->CreateEndProcessPipe(execData
) )
508 wxLogError( _("Failed to execute '%s'\n"), *argv
);
512 return ERROR_RETURN_CODE
;
515 // pipes for inter process communication
516 wxPipe pipeIn
, // stdin
520 if ( process
&& process
->IsRedirected() )
522 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
524 wxLogError( _("Failed to execute '%s'\n"), *argv
);
528 return ERROR_RETURN_CODE
;
534 // NB: do *not* use vfork() here, it completely breaks this code for some
535 // reason under Solaris (and maybe others, although not under Linux)
536 // But on OpenVMS we do not have fork so we have to use vfork and
537 // cross our fingers that it works.
543 if ( pid
== -1 ) // error?
545 wxLogSysError( _("Fork failed") );
549 return ERROR_RETURN_CODE
;
551 else if ( pid
== 0 ) // we're in child
553 // These lines close the open file descriptors to to avoid any
554 // input/output which might block the process or irritate the user. If
555 // one wants proper IO for the subprocess, the right thing to do is to
556 // start an xterm executing it.
557 if ( !(flags
& wxEXEC_SYNC
) )
559 // FD_SETSIZE is unsigned under BSD, signed under other platforms
560 // so we need a cast to avoid warnings on all platforms
561 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
563 if ( fd
== pipeIn
[wxPipe::Read
]
564 || fd
== pipeOut
[wxPipe::Write
]
565 || fd
== pipeErr
[wxPipe::Write
]
566 || traits
->IsWriteFDOfEndProcessPipe(execData
, fd
) )
568 // don't close this one, we still need it
572 // leave stderr opened too, it won't do any harm
573 if ( fd
!= STDERR_FILENO
)
578 #if !defined(__VMS) && !defined(__EMX__)
579 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
581 // Set process group to child process' pid. Then killing -pid
582 // of the parent will kill the process and all of its children.
587 // reading side can be safely closed but we should keep the write one
589 traits
->DetachWriteFDOfEndProcessPipe(execData
);
591 // redirect stdin, stdout and stderr
594 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
595 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
596 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
598 wxLogSysError(_("Failed to redirect child process input/output"));
606 execvp (*mb_argv
, mb_argv
);
608 fprintf(stderr
, "execvp(");
609 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
610 for ( char **ppc_
= mb_argv
; *ppc_
; ppc_
++ )
611 fprintf(stderr
, "%s%s", ppc_
== mb_argv
? "" : ", ", *ppc_
);
612 fprintf(stderr
, ") failed with error %d!\n", errno
);
614 // there is no return after successful exec()
617 // some compilers complain about missing return - of course, they
618 // should know that exit() doesn't return but what else can we do if
621 // and, sure enough, other compilers complain about unreachable code
622 // after exit() call, so we can just always have return here...
623 #if defined(__VMS) || defined(__INTEL_COMPILER)
627 else // we're in parent
631 // save it for WaitForChild() use
634 // prepare for IO redirection
636 #if HAS_PIPE_INPUT_STREAM
637 // the input buffer bufOut is connected to stdout, this is why it is
638 // called bufOut and not bufIn
639 wxStreamTempInputBuffer bufOut
,
641 #endif // HAS_PIPE_INPUT_STREAM
643 if ( process
&& process
->IsRedirected() )
645 #if HAS_PIPE_INPUT_STREAM
646 wxOutputStream
*inStream
=
647 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
649 wxPipeInputStream
*outStream
=
650 new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
652 wxPipeInputStream
*errStream
=
653 new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
655 process
->SetPipeStreams(outStream
, inStream
, errStream
);
657 bufOut
.Init(outStream
);
658 bufErr
.Init(errStream
);
660 execData
.bufOut
= &bufOut
;
661 execData
.bufErr
= &bufErr
;
662 #endif // HAS_PIPE_INPUT_STREAM
672 return traits
->WaitForChild(execData
);
675 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
676 return ERROR_RETURN_CODE
;
680 #undef ERROR_RETURN_CODE
683 // ----------------------------------------------------------------------------
684 // file and directory functions
685 // ----------------------------------------------------------------------------
687 const wxChar
* wxGetHomeDir( wxString
*home
)
689 *home
= wxGetUserHome( wxEmptyString
);
695 if ( tmp
.Last() != wxT(']'))
696 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
698 return home
->c_str();
702 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
703 #else // just for binary compatibility -- there is no 'const' here
704 char *wxGetUserHome( const wxString
&user
)
707 struct passwd
*who
= (struct passwd
*) NULL
;
713 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
716 wxWCharBuffer
buffer( ptr
);
722 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
724 who
= getpwnam(wxConvertWX2MB(ptr
));
727 // We now make sure the the user exists!
730 who
= getpwuid(getuid());
735 who
= getpwnam (user
.mb_str());
738 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
741 // ----------------------------------------------------------------------------
742 // network and user id routines
743 // ----------------------------------------------------------------------------
745 // private utility function which returns output of the given command, removing
746 // the trailing newline
747 static wxString
wxGetCommandOutput(const wxString
&cmd
)
749 FILE *f
= popen(cmd
.ToAscii(), "r");
752 wxLogSysError(_T("Executing \"%s\" failed"), cmd
.c_str());
753 return wxEmptyString
;
760 if ( !fgets(buf
, sizeof(buf
), f
) )
763 s
+= wxString::FromAscii(buf
);
768 if ( !s
.empty() && s
.Last() == _T('\n') )
774 // retrieve either the hostname or FQDN depending on platform (caller must
775 // check whether it's one or the other, this is why this function is for
777 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
779 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
783 // we're using uname() which is POSIX instead of less standard sysinfo()
784 #if defined(HAVE_UNAME)
786 bool ok
= uname(&uts
) != -1;
789 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
792 #elif defined(HAVE_GETHOSTNAME)
793 bool ok
= gethostname(buf
, sz
) != -1;
794 #else // no uname, no gethostname
795 wxFAIL_MSG(wxT("don't know host name for this machine"));
798 #endif // uname/gethostname
802 wxLogSysError(_("Cannot get the hostname"));
808 bool wxGetHostName(wxChar
*buf
, int sz
)
810 bool ok
= wxGetHostNameInternal(buf
, sz
);
814 // BSD systems return the FQDN, we only want the hostname, so extract
815 // it (we consider that dots are domain separators)
816 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
827 bool wxGetFullHostName(wxChar
*buf
, int sz
)
829 bool ok
= wxGetHostNameInternal(buf
, sz
);
833 if ( !wxStrchr(buf
, wxT('.')) )
835 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
838 wxLogSysError(_("Cannot get the official hostname"));
844 // the canonical name
845 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
848 //else: it's already a FQDN (BSD behaves this way)
854 bool wxGetUserId(wxChar
*buf
, int sz
)
859 if ((who
= getpwuid(getuid ())) != NULL
)
861 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
868 bool wxGetUserName(wxChar
*buf
, int sz
)
873 if ((who
= getpwuid (getuid ())) != NULL
)
875 // pw_gecos field in struct passwd is not standard
877 char *comma
= strchr(who
->pw_gecos
, ',');
879 *comma
= '\0'; // cut off non-name comment fields
880 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
881 #else // !HAVE_PW_GECOS
882 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
883 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
890 bool wxIsPlatform64Bit()
892 wxString machine
= wxGetCommandOutput(wxT("uname -m"));
894 // NOTE: these tests are not 100% reliable!
895 return machine
.Contains(wxT("AMD64")) ||
896 machine
.Contains(wxT("IA64")) ||
897 machine
.Contains(wxT("x64")) ||
898 machine
.Contains(wxT("X64")) ||
899 machine
.Contains(wxT("alpha")) ||
900 machine
.Contains(wxT("hppa64")) ||
901 machine
.Contains(wxT("ppc64"));
904 // these functions are in mac/utils.cpp for wxMac
907 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
911 wxString release
= wxGetCommandOutput(wxT("uname -r"));
912 if ( !release
.empty() && wxSscanf(release
, wxT("%d.%d"), &major
, &minor
) != 2 )
914 // unrecognized uname string format
924 // try to understand which OS are we running
925 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
926 if ( kernel
.empty() )
927 kernel
= wxGetCommandOutput(wxT("uname -o"));
929 if ( kernel
.empty() )
932 return wxPlatformInfo::GetOperatingSystemId(kernel
);
935 wxString
wxGetOsDescription()
937 return wxGetCommandOutput(wxT("uname -s -r -m"));
942 unsigned long wxGetProcessId()
944 return (unsigned long)getpid();
947 wxMemorySize
wxGetFreeMemory()
949 #if defined(__LINUX__)
950 // get it from /proc/meminfo
951 FILE *fp
= fopen("/proc/meminfo", "r");
957 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
959 // /proc/meminfo changed its format in kernel 2.6
960 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
962 unsigned long cached
, buffers
;
963 sscanf(buf
, "MemFree: %ld", &memFree
);
965 fgets(buf
, WXSIZEOF(buf
), fp
);
966 sscanf(buf
, "Buffers: %lu", &buffers
);
968 fgets(buf
, WXSIZEOF(buf
), fp
);
969 sscanf(buf
, "Cached: %lu", &cached
);
971 // add to "MemFree" also the "Buffers" and "Cached" values as
972 // free(1) does as otherwise the value never makes sense: for
973 // kernel 2.6 it's always almost 0
974 memFree
+= buffers
+ cached
;
976 // values here are always expressed in kB and we want bytes
979 else // Linux 2.4 (or < 2.6, anyhow)
981 long memTotal
, memUsed
;
982 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
988 return (wxMemorySize
)memFree
;
990 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
991 return (wxMemorySize
)(sysconf(_SC_AVPHYS_PAGES
)*sysconf(_SC_PAGESIZE
));
992 #elif defined(__SGI__)
993 struct rminfo realmem
;
994 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
995 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
996 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1003 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
1005 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1006 // the case to "char *" is needed for AIX 4.3
1008 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
1010 wxLogSysError( wxT("Failed to get file system statistics") );
1015 // under Solaris we also have to use f_frsize field instead of f_bsize
1016 // which is in general a multiple of f_frsize
1018 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1019 #else // HAVE_STATFS
1020 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1021 #endif // HAVE_STATVFS/HAVE_STATFS
1025 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1030 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1034 #else // !HAVE_STATFS && !HAVE_STATVFS
1036 #endif // HAVE_STATFS
1039 // ----------------------------------------------------------------------------
1041 // ----------------------------------------------------------------------------
1043 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1045 // wxGetenv is defined as getenv()
1046 wxChar
*p
= wxGetenv(var
);
1058 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
1060 #if defined(HAVE_SETENV)
1061 return setenv(variable
.mb_str(),
1062 value
? (const char *)wxString(value
).mb_str()
1064 1 /* overwrite */) == 0;
1065 #elif defined(HAVE_PUTENV)
1066 wxString s
= variable
;
1068 s
<< _T('=') << value
;
1070 // transform to ANSI
1071 const wxWX2MBbuf p
= s
.mb_str();
1073 // the string will be free()d by libc
1074 char *buf
= (char *)malloc(strlen(p
) + 1);
1077 return putenv(buf
) == 0;
1078 #else // no way to set an env var
1083 // ----------------------------------------------------------------------------
1085 // ----------------------------------------------------------------------------
1087 #if wxUSE_ON_FATAL_EXCEPTION
1091 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1095 // give the user a chance to do something special about this
1096 wxTheApp
->OnFatalException();
1102 bool wxHandleFatalExceptions(bool doit
)
1105 static bool s_savedHandlers
= false;
1106 static struct sigaction s_handlerFPE
,
1112 if ( doit
&& !s_savedHandlers
)
1114 // install the signal handler
1115 struct sigaction act
;
1117 // some systems extend it with non std fields, so zero everything
1118 memset(&act
, 0, sizeof(act
));
1120 act
.sa_handler
= wxFatalSignalHandler
;
1121 sigemptyset(&act
.sa_mask
);
1124 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1125 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1126 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1127 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1130 wxLogDebug(_T("Failed to install our signal handler."));
1133 s_savedHandlers
= true;
1135 else if ( s_savedHandlers
)
1137 // uninstall the signal handler
1138 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1139 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1140 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1141 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1144 wxLogDebug(_T("Failed to uninstall our signal handler."));
1147 s_savedHandlers
= false;
1149 //else: nothing to do
1154 #endif // wxUSE_ON_FATAL_EXCEPTION
1156 #endif // wxUSE_BASE
1160 // ----------------------------------------------------------------------------
1161 // wxExecute support
1162 // ----------------------------------------------------------------------------
1164 // Darwin doesn't use the same process end detection mechanisms so we don't
1165 // need wxExecute-related helpers for it
1166 #if !(defined(__DARWIN__) && defined(__WXMAC__))
1168 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& execData
)
1170 return execData
.pipeEndProcDetect
.Create();
1173 bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& execData
, int fd
)
1175 return fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
];
1178 void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& execData
)
1180 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
1181 execData
.pipeEndProcDetect
.Close();
1186 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1192 wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
),
1199 wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1201 // nothing to do here, we don't use the pipe
1204 #endif // !Darwin/Darwin
1206 int wxGUIAppTraits::WaitForChild(wxExecuteData
& execData
)
1208 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1210 const int flags
= execData
.flags
;
1212 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1213 // callback function directly if the process terminates before
1214 // the callback can be added to the run loop. Set up the endProcData.
1215 if ( flags
& wxEXEC_SYNC
)
1217 // we may have process for capturing the program output, but it's
1218 // not used in wxEndProcessData in the case of sync execution
1219 endProcData
->process
= NULL
;
1221 // sync execution: indicate it by negating the pid
1222 endProcData
->pid
= -execData
.pid
;
1226 // async execution, nothing special to do -- caller will be
1227 // notified about the process termination if process != NULL, endProcData
1228 // will be deleted in GTK_EndProcessDetector
1229 endProcData
->process
= execData
.process
;
1230 endProcData
->pid
= execData
.pid
;
1234 #if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1235 endProcData
->tag
= wxAddProcessCallbackForPid(endProcData
, execData
.pid
);
1237 endProcData
->tag
= wxAddProcessCallback
1240 execData
.pipeEndProcDetect
.Detach(wxPipe::Read
)
1243 execData
.pipeEndProcDetect
.Close();
1244 #endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1246 if ( flags
& wxEXEC_SYNC
)
1249 wxWindowDisabler
*wd
= flags
& wxEXEC_NODISABLE
? NULL
1250 : new wxWindowDisabler
;
1252 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1253 // process terminates
1254 while ( endProcData
->pid
!= 0 )
1258 #if HAS_PIPE_INPUT_STREAM
1259 if ( execData
.bufOut
)
1261 execData
.bufOut
->Update();
1265 if ( execData
.bufErr
)
1267 execData
.bufErr
->Update();
1270 #endif // HAS_PIPE_INPUT_STREAM
1272 // don't consume 100% of the CPU while we're sitting in this
1277 // give GTK+ a chance to call GTK_EndProcessDetector here and
1278 // also repaint the GUI
1282 int exitcode
= endProcData
->exitcode
;
1289 else // async execution
1291 return execData
.pid
;
1298 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
1300 // notify user about termination if required
1301 if ( proc_data
->process
)
1303 proc_data
->process
->OnTerminate(proc_data
->pid
, proc_data
->exitcode
);
1307 if ( proc_data
->pid
> 0 )
1313 // let wxExecute() know that the process has terminated
1318 #endif // wxUSE_BASE