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 int usleep(unsigned int usec
);
158 /* I copied this from the XFree86 diffs. AV. */
159 #define INCL_DOSPROCESS
161 inline void usleep(unsigned long delay
)
163 DosSleep(delay
? (delay
/1000l) : 1l);
165 #else // !Sun && !EMX
166 void usleep(unsigned long usec
);
168 #endif // Sun/EMX/Something else
171 #define HAVE_USLEEP 1
172 #endif // Unices without usleep()
174 // ============================================================================
176 // ============================================================================
178 // ----------------------------------------------------------------------------
180 // ----------------------------------------------------------------------------
182 void wxSleep(int nSecs
)
187 void wxMicroSleep(unsigned long microseconds
)
189 #if defined(HAVE_NANOSLEEP)
191 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
192 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
194 // we're not interested in remaining time nor in return value
195 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
196 #elif defined(HAVE_USLEEP)
197 // uncomment this if you feel brave or if you are sure that your version
198 // of Solaris has a safe usleep() function but please notice that usleep()
199 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
200 // documented as MT-Safe
201 #if defined(__SUN__) && wxUSE_THREADS
202 #error "usleep() cannot be used in MT programs under Solaris."
205 usleep(microseconds
);
206 #elif defined(HAVE_SLEEP)
207 // under BeOS sleep() takes seconds (what about other platforms, if any?)
208 sleep(microseconds
* 1000000);
209 #else // !sleep function
210 #error "usleep() or nanosleep() function required for wxMicroSleep"
211 #endif // sleep function
214 void wxMilliSleep(unsigned long milliseconds
)
216 wxMicroSleep(milliseconds
*1000);
219 // ----------------------------------------------------------------------------
220 // process management
221 // ----------------------------------------------------------------------------
223 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
225 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
228 switch ( err
? errno
: 0 )
235 *rc
= wxKILL_BAD_SIGNAL
;
239 *rc
= wxKILL_ACCESS_DENIED
;
243 *rc
= wxKILL_NO_PROCESS
;
247 // this goes against Unix98 docs so log it
248 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
258 #define WXEXECUTE_NARGS 127
260 #if defined(__DARWIN__)
261 long wxMacExecute(wxChar
**argv
,
266 long wxExecute( const wxString
& command
, int flags
, wxProcess
*process
)
268 wxCHECK_MSG( !command
.empty(), 0, wxT("can't exec empty command") );
269 wxLogDebug(wxString(wxT("Launching: ")) + command
);
272 // fork() doesn't mix well with POSIX threads: on many systems the program
273 // deadlocks or crashes for some reason. Probably our code is buggy and
274 // doesn't do something which must be done to allow this to work, but I
275 // don't know what yet, so for now just warn the user (this is the least we
277 wxASSERT_MSG( wxThread::IsMain(),
278 _T("wxExecute() can be called only from the main thread") );
279 #endif // wxUSE_THREADS
282 wxChar
*argv
[WXEXECUTE_NARGS
];
284 const wxChar
*cptr
= command
.c_str();
285 wxChar quotechar
= wxT('\0'); // is arg quoted?
286 bool escaped
= false;
288 // split the command line in arguments
291 argument
= wxEmptyString
;
292 quotechar
= wxT('\0');
294 // eat leading whitespace:
295 while ( wxIsspace(*cptr
) )
298 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
303 if ( *cptr
== wxT('\\') && ! escaped
)
310 // all other characters:
314 // have we reached the end of the argument?
315 if ( (*cptr
== quotechar
&& ! escaped
)
316 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
317 || *cptr
== wxT('\0') )
319 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
320 wxT("too many arguments in wxExecute") );
322 argv
[argc
] = new wxChar
[argument
.length() + 1];
323 wxStrcpy(argv
[argc
], argument
.c_str());
326 // if not at end of buffer, swallow last character:
330 break; // done with this one, start over
337 #if defined(__DARWIN__)
338 // wxMacExecute only executes app bundles.
339 // It returns an error code if the target is not an app bundle, thus falling
340 // through to the regular wxExecute for non app bundles.
341 lRc
= wxMacExecute(argv
, flags
, process
);
342 if( lRc
!= ((flags
& wxEXEC_SYNC
) ? -1 : 0))
346 // do execute the command
347 lRc
= wxExecute(argv
, flags
, process
);
352 delete [] argv
[argc
++];
357 // ----------------------------------------------------------------------------
359 // ----------------------------------------------------------------------------
361 static wxString
wxMakeShellCommand(const wxString
& command
)
366 // just an interactive shell
371 // execute command in a shell
372 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
378 bool wxShell(const wxString
& command
)
380 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
383 bool wxShell(const wxString
& command
, wxArrayString
& output
)
385 wxCHECK_MSG( !command
.empty(), false, _T("can't exec shell non interactively") );
387 return wxExecute(wxMakeShellCommand(command
), output
);
390 // Shutdown or reboot the PC
391 bool wxShutdown(wxShutdownFlags wFlags
)
396 case wxSHUTDOWN_POWEROFF
:
400 case wxSHUTDOWN_REBOOT
:
405 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
409 return system(wxString::Format(_T("init %c"), level
).mb_str()) == 0;
412 // ----------------------------------------------------------------------------
413 // wxStream classes to support IO redirection in wxExecute
414 // ----------------------------------------------------------------------------
416 #if HAS_PIPE_INPUT_STREAM
418 bool wxPipeInputStream::CanRead() const
420 if ( m_lasterror
== wxSTREAM_EOF
)
423 // check if there is any input available
428 const int fd
= m_file
->fd();
433 wxFD_SET(fd
, &readfds
);
435 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
438 wxLogSysError(_("Impossible to get child process input"));
445 wxFAIL_MSG(_T("unexpected select() return value"));
446 // still fall through
449 // input available -- or maybe not, as select() returns 1 when a
450 // read() will complete without delay, but it could still not read
456 #endif // HAS_PIPE_INPUT_STREAM
458 // ----------------------------------------------------------------------------
459 // wxExecute: the real worker function
460 // ----------------------------------------------------------------------------
462 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*process
)
464 // for the sync execution, we return -1 to indicate failure, but for async
465 // case we return 0 which is never a valid PID
467 // we define this as a macro, not a variable, to avoid compiler warnings
468 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
469 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
471 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
475 char *mb_argv
[WXEXECUTE_NARGS
];
477 while (argv
[mb_argc
])
479 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
480 mb_argv
[mb_argc
] = strdup(mb_arg
);
483 mb_argv
[mb_argc
] = (char *) NULL
;
485 // this macro will free memory we used above
486 #define ARGS_CLEANUP \
487 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
488 free(mb_argv[mb_argc])
490 // no need for cleanup
493 wxChar
**mb_argv
= argv
;
494 #endif // Unicode/ANSI
496 // we want this function to work even if there is no wxApp so ensure that
497 // we have a valid traits pointer
498 wxConsoleAppTraits traitsConsole
;
499 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
501 traits
= &traitsConsole
;
503 // this struct contains all information which we pass to and from
504 // wxAppTraits methods
505 wxExecuteData execData
;
506 execData
.flags
= flags
;
507 execData
.process
= process
;
510 if ( !traits
->CreateEndProcessPipe(execData
) )
512 wxLogError( _("Failed to execute '%s'\n"), *argv
);
516 return ERROR_RETURN_CODE
;
519 // pipes for inter process communication
520 wxPipe pipeIn
, // stdin
524 if ( process
&& process
->IsRedirected() )
526 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
528 wxLogError( _("Failed to execute '%s'\n"), *argv
);
532 return ERROR_RETURN_CODE
;
538 // NB: do *not* use vfork() here, it completely breaks this code for some
539 // reason under Solaris (and maybe others, although not under Linux)
540 // But on OpenVMS we do not have fork so we have to use vfork and
541 // cross our fingers that it works.
547 if ( pid
== -1 ) // error?
549 wxLogSysError( _("Fork failed") );
553 return ERROR_RETURN_CODE
;
555 else if ( pid
== 0 ) // we're in child
557 // These lines close the open file descriptors to to avoid any
558 // input/output which might block the process or irritate the user. If
559 // one wants proper IO for the subprocess, the right thing to do is to
560 // start an xterm executing it.
561 if ( !(flags
& wxEXEC_SYNC
) )
563 // FD_SETSIZE is unsigned under BSD, signed under other platforms
564 // so we need a cast to avoid warnings on all platforms
565 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; fd
++ )
567 if ( fd
== pipeIn
[wxPipe::Read
]
568 || fd
== pipeOut
[wxPipe::Write
]
569 || fd
== pipeErr
[wxPipe::Write
]
570 || traits
->IsWriteFDOfEndProcessPipe(execData
, fd
) )
572 // don't close this one, we still need it
576 // leave stderr opened too, it won't do any harm
577 if ( fd
!= STDERR_FILENO
)
582 #if !defined(__VMS) && !defined(__EMX__)
583 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
585 // Set process group to child process' pid. Then killing -pid
586 // of the parent will kill the process and all of its children.
591 // reading side can be safely closed but we should keep the write one
593 traits
->DetachWriteFDOfEndProcessPipe(execData
);
595 // redirect stdin, stdout and stderr
598 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
599 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
600 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
602 wxLogSysError(_("Failed to redirect child process input/output"));
610 execvp (*mb_argv
, mb_argv
);
612 fprintf(stderr
, "execvp(");
613 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
614 for ( char **ppc_
= mb_argv
; *ppc_
; ppc_
++ )
615 fprintf(stderr
, "%s%s", ppc_
== mb_argv
? "" : ", ", *ppc_
);
616 fprintf(stderr
, ") failed with error %d!\n", errno
);
618 // there is no return after successful exec()
621 // some compilers complain about missing return - of course, they
622 // should know that exit() doesn't return but what else can we do if
625 // and, sure enough, other compilers complain about unreachable code
626 // after exit() call, so we can just always have return here...
627 #if defined(__VMS) || defined(__INTEL_COMPILER)
631 else // we're in parent
635 // save it for WaitForChild() use
638 // prepare for IO redirection
640 #if HAS_PIPE_INPUT_STREAM
641 // the input buffer bufOut is connected to stdout, this is why it is
642 // called bufOut and not bufIn
643 wxStreamTempInputBuffer bufOut
,
645 #endif // HAS_PIPE_INPUT_STREAM
647 if ( process
&& process
->IsRedirected() )
649 #if HAS_PIPE_INPUT_STREAM
650 wxOutputStream
*inStream
=
651 new wxFileOutputStream(pipeIn
.Detach(wxPipe::Write
));
653 wxPipeInputStream
*outStream
=
654 new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
656 wxPipeInputStream
*errStream
=
657 new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
659 process
->SetPipeStreams(outStream
, inStream
, errStream
);
661 bufOut
.Init(outStream
);
662 bufErr
.Init(errStream
);
664 execData
.bufOut
= &bufOut
;
665 execData
.bufErr
= &bufErr
;
666 #endif // HAS_PIPE_INPUT_STREAM
676 return traits
->WaitForChild(execData
);
679 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
680 return ERROR_RETURN_CODE
;
684 #undef ERROR_RETURN_CODE
687 // ----------------------------------------------------------------------------
688 // file and directory functions
689 // ----------------------------------------------------------------------------
691 const wxChar
* wxGetHomeDir( wxString
*home
)
693 *home
= wxGetUserHome( wxEmptyString
);
699 if ( tmp
.Last() != wxT(']'))
700 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
702 return home
->c_str();
706 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
707 #else // just for binary compatibility -- there is no 'const' here
708 char *wxGetUserHome( const wxString
&user
)
711 struct passwd
*who
= (struct passwd
*) NULL
;
717 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
720 wxWCharBuffer
buffer( ptr
);
726 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
728 who
= getpwnam(wxConvertWX2MB(ptr
));
731 // We now make sure the the user exists!
734 who
= getpwuid(getuid());
739 who
= getpwnam (user
.mb_str());
742 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
745 // ----------------------------------------------------------------------------
746 // network and user id routines
747 // ----------------------------------------------------------------------------
749 // private utility function which returns output of the given command, removing
750 // the trailing newline
751 static wxString
wxGetCommandOutput(const wxString
&cmd
)
753 FILE *f
= popen(cmd
.ToAscii(), "r");
756 wxLogSysError(_T("Executing \"%s\" failed"), cmd
.c_str());
757 return wxEmptyString
;
764 if ( !fgets(buf
, sizeof(buf
), f
) )
767 s
+= wxString::FromAscii(buf
);
772 if ( !s
.empty() && s
.Last() == _T('\n') )
778 // retrieve either the hostname or FQDN depending on platform (caller must
779 // check whether it's one or the other, this is why this function is for
781 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
783 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
787 // we're using uname() which is POSIX instead of less standard sysinfo()
788 #if defined(HAVE_UNAME)
790 bool ok
= uname(&uts
) != -1;
793 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
796 #elif defined(HAVE_GETHOSTNAME)
797 bool ok
= gethostname(buf
, sz
) != -1;
798 #else // no uname, no gethostname
799 wxFAIL_MSG(wxT("don't know host name for this machine"));
802 #endif // uname/gethostname
806 wxLogSysError(_("Cannot get the hostname"));
812 bool wxGetHostName(wxChar
*buf
, int sz
)
814 bool ok
= wxGetHostNameInternal(buf
, sz
);
818 // BSD systems return the FQDN, we only want the hostname, so extract
819 // it (we consider that dots are domain separators)
820 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
831 bool wxGetFullHostName(wxChar
*buf
, int sz
)
833 bool ok
= wxGetHostNameInternal(buf
, sz
);
837 if ( !wxStrchr(buf
, wxT('.')) )
839 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
842 wxLogSysError(_("Cannot get the official hostname"));
848 // the canonical name
849 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
852 //else: it's already a FQDN (BSD behaves this way)
858 bool wxGetUserId(wxChar
*buf
, int sz
)
863 if ((who
= getpwuid(getuid ())) != NULL
)
865 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
872 bool wxGetUserName(wxChar
*buf
, int sz
)
877 if ((who
= getpwuid (getuid ())) != NULL
)
879 // pw_gecos field in struct passwd is not standard
881 char *comma
= strchr(who
->pw_gecos
, ',');
883 *comma
= '\0'; // cut off non-name comment fields
884 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
885 #else // !HAVE_PW_GECOS
886 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
887 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
894 bool wxIsPlatform64Bit()
896 wxString machine
= wxGetCommandOutput(wxT("uname -m"));
898 // NOTE: these tests are not 100% reliable!
899 return machine
.Contains(wxT("AMD64")) ||
900 machine
.Contains(wxT("IA64")) ||
901 machine
.Contains(wxT("x64")) ||
902 machine
.Contains(wxT("X64")) ||
903 machine
.Contains(wxT("alpha")) ||
904 machine
.Contains(wxT("hppa64")) ||
905 machine
.Contains(wxT("ppc64"));
908 // these functions are in mac/utils.cpp for wxMac
911 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
915 wxString release
= wxGetCommandOutput(wxT("uname -r"));
916 if ( !release
.empty() && wxSscanf(release
, wxT("%d.%d"), &major
, &minor
) != 2 )
918 // unrecognized uname string format
928 // try to understand which OS are we running
929 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
930 if ( kernel
.empty() )
931 kernel
= wxGetCommandOutput(wxT("uname -o"));
933 if ( kernel
.empty() )
936 return wxPlatformInfo::GetOperatingSystemId(kernel
);
939 wxString
wxGetOsDescription()
941 return wxGetCommandOutput(wxT("uname -s -r -m"));
946 unsigned long wxGetProcessId()
948 return (unsigned long)getpid();
951 wxMemorySize
wxGetFreeMemory()
953 #if defined(__LINUX__)
954 // get it from /proc/meminfo
955 FILE *fp
= fopen("/proc/meminfo", "r");
961 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
963 long memTotal
, memUsed
;
964 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
969 return (wxMemorySize
)memFree
;
971 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
972 return (wxMemorySize
)(sysconf(_SC_AVPHYS_PAGES
)*sysconf(_SC_PAGESIZE
));
973 #elif defined(__SGI__)
974 struct rminfo realmem
;
975 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
976 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
977 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
984 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
986 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
987 // the case to "char *" is needed for AIX 4.3
989 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
991 wxLogSysError( wxT("Failed to get file system statistics") );
996 // under Solaris we also have to use f_frsize field instead of f_bsize
997 // which is in general a multiple of f_frsize
999 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1000 #else // HAVE_STATFS
1001 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1002 #endif // HAVE_STATVFS/HAVE_STATFS
1006 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1011 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1015 #else // !HAVE_STATFS && !HAVE_STATVFS
1017 #endif // HAVE_STATFS
1020 // ----------------------------------------------------------------------------
1022 // ----------------------------------------------------------------------------
1024 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1026 // wxGetenv is defined as getenv()
1027 wxChar
*p
= wxGetenv(var
);
1039 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
1041 #if defined(HAVE_SETENV)
1042 return setenv(variable
.mb_str(),
1043 value
? (const char *)wxString(value
).mb_str()
1045 1 /* overwrite */) == 0;
1046 #elif defined(HAVE_PUTENV)
1047 wxString s
= variable
;
1049 s
<< _T('=') << value
;
1051 // transform to ANSI
1052 const wxWX2MBbuf p
= s
.mb_str();
1054 // the string will be free()d by libc
1055 char *buf
= (char *)malloc(strlen(p
) + 1);
1058 return putenv(buf
) == 0;
1059 #else // no way to set an env var
1064 // ----------------------------------------------------------------------------
1066 // ----------------------------------------------------------------------------
1068 #if wxUSE_ON_FATAL_EXCEPTION
1072 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1076 // give the user a chance to do something special about this
1077 wxTheApp
->OnFatalException();
1083 bool wxHandleFatalExceptions(bool doit
)
1086 static bool s_savedHandlers
= false;
1087 static struct sigaction s_handlerFPE
,
1093 if ( doit
&& !s_savedHandlers
)
1095 // install the signal handler
1096 struct sigaction act
;
1098 // some systems extend it with non std fields, so zero everything
1099 memset(&act
, 0, sizeof(act
));
1101 act
.sa_handler
= wxFatalSignalHandler
;
1102 sigemptyset(&act
.sa_mask
);
1105 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1106 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1107 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1108 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1111 wxLogDebug(_T("Failed to install our signal handler."));
1114 s_savedHandlers
= true;
1116 else if ( s_savedHandlers
)
1118 // uninstall the signal handler
1119 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1120 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1121 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1122 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1125 wxLogDebug(_T("Failed to uninstall our signal handler."));
1128 s_savedHandlers
= false;
1130 //else: nothing to do
1135 #endif // wxUSE_ON_FATAL_EXCEPTION
1137 #endif // wxUSE_BASE
1141 // ----------------------------------------------------------------------------
1142 // wxExecute support
1143 // ----------------------------------------------------------------------------
1145 // Darwin doesn't use the same process end detection mechanisms so we don't
1146 // need wxExecute-related helpers for it
1147 #if !(defined(__DARWIN__) && defined(__WXMAC__))
1149 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& execData
)
1151 return execData
.pipeEndProcDetect
.Create();
1154 bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& execData
, int fd
)
1156 return fd
== (execData
.pipeEndProcDetect
)[wxPipe::Write
];
1159 void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& execData
)
1161 execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
1162 execData
.pipeEndProcDetect
.Close();
1167 bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1173 wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
),
1180 wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData
& WXUNUSED(execData
))
1182 // nothing to do here, we don't use the pipe
1185 #endif // !Darwin/Darwin
1187 int wxGUIAppTraits::WaitForChild(wxExecuteData
& execData
)
1189 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1191 const int flags
= execData
.flags
;
1193 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1194 // callback function directly if the process terminates before
1195 // the callback can be added to the run loop. Set up the endProcData.
1196 if ( flags
& wxEXEC_SYNC
)
1198 // we may have process for capturing the program output, but it's
1199 // not used in wxEndProcessData in the case of sync execution
1200 endProcData
->process
= NULL
;
1202 // sync execution: indicate it by negating the pid
1203 endProcData
->pid
= -execData
.pid
;
1207 // async execution, nothing special to do -- caller will be
1208 // notified about the process termination if process != NULL, endProcData
1209 // will be deleted in GTK_EndProcessDetector
1210 endProcData
->process
= execData
.process
;
1211 endProcData
->pid
= execData
.pid
;
1215 #if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1216 endProcData
->tag
= wxAddProcessCallbackForPid(endProcData
, execData
.pid
);
1218 endProcData
->tag
= wxAddProcessCallback
1221 execData
.pipeEndProcDetect
.Detach(wxPipe::Read
)
1224 execData
.pipeEndProcDetect
.Close();
1225 #endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1227 if ( flags
& wxEXEC_SYNC
)
1230 wxWindowDisabler
*wd
= flags
& wxEXEC_NODISABLE
? NULL
1231 : new wxWindowDisabler
;
1233 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1234 // process terminates
1235 while ( endProcData
->pid
!= 0 )
1239 #if HAS_PIPE_INPUT_STREAM
1240 if ( execData
.bufOut
)
1242 execData
.bufOut
->Update();
1246 if ( execData
.bufErr
)
1248 execData
.bufErr
->Update();
1251 #endif // HAS_PIPE_INPUT_STREAM
1253 // don't consume 100% of the CPU while we're sitting in this
1258 // give GTK+ a chance to call GTK_EndProcessDetector here and
1259 // also repaint the GUI
1263 int exitcode
= endProcData
->exitcode
;
1270 else // async execution
1272 return execData
.pid
;
1279 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
1281 // notify user about termination if required
1282 if ( proc_data
->process
)
1284 proc_data
->process
->OnTerminate(proc_data
->pid
, proc_data
->exitcode
);
1288 if ( proc_data
->pid
> 0 )
1294 // let wxExecute() know that the process has terminated
1299 #endif // wxUSE_BASE