1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/utilsunx.cpp
3 // Purpose: generic Unix implementation of many wx functions (for wxBase)
4 // Author: Vadim Zeitlin
6 // Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 // ============================================================================
12 // ============================================================================
14 // ----------------------------------------------------------------------------
16 // ----------------------------------------------------------------------------
18 // for compilers that support precompilation, includes "wx.h".
19 #include "wx/wxprec.h"
23 #define USE_PUTENV (!defined(HAVE_SETENV) && defined(HAVE_PUTENV))
26 #include "wx/string.h"
30 #include "wx/wxcrtvararg.h"
32 #include "wx/module.h"
33 #include "wx/hashmap.h"
37 #include "wx/apptrait.h"
39 #include "wx/process.h"
40 #include "wx/thread.h"
42 #include "wx/cmdline.h"
44 #include "wx/wfstream.h"
46 #include "wx/private/selectdispatcher.h"
47 #include "wx/private/fdiodispatcher.h"
48 #include "wx/unix/execute.h"
49 #include "wx/unix/private.h"
51 #ifdef wxHAS_GENERIC_PROCESS_CALLBACK
52 #include "wx/private/fdiodispatcher.h"
56 #include <sys/wait.h> // waitpid()
58 #ifdef HAVE_SYS_SELECT_H
59 # include <sys/select.h>
62 #define HAS_PIPE_STREAMS (wxUSE_STREAMS && wxUSE_FILE)
66 #include "wx/private/pipestream.h"
67 #include "wx/private/streamtempinput.h"
69 #endif // HAS_PIPE_STREAMS
71 // not only the statfs syscall is called differently depending on platform, but
72 // one of its incarnations, statvfs(), takes different arguments under
73 // different platforms and even different versions of the same system (Solaris
74 // 7 and 8): if you want to test for this, don't forget that the problems only
75 // appear if the large files support is enabled
78 #include <sys/param.h>
79 #include <sys/mount.h>
82 #endif // __BSD__/!__BSD__
84 #define wxStatfs statfs
86 #ifndef HAVE_STATFS_DECL
87 // some systems lack statfs() prototype in the system headers (AIX 4)
88 extern "C" int statfs(const char *path
, struct statfs
*buf
);
93 #include <sys/statvfs.h>
95 #define wxStatfs statvfs
96 #endif // HAVE_STATVFS
98 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
99 // WX_STATFS_T is detected by configure
100 #define wxStatfs_t WX_STATFS_T
103 // SGI signal.h defines signal handler arguments differently depending on
104 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
105 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
106 #define _LANGUAGE_C_PLUS_PLUS 1
112 #include <sys/stat.h>
113 #include <sys/types.h>
114 #include <sys/wait.h>
119 #include <time.h> // nanosleep() and/or usleep()
120 #include <ctype.h> // isspace()
121 #include <sys/time.h> // needed for FD_SETSIZE
124 #include <sys/utsname.h> // for uname()
127 // Used by wxGetFreeMemory().
129 #include <sys/sysmp.h>
130 #include <sys/sysinfo.h> // for SAGET and MINFO structures
133 #ifdef HAVE_SETPRIORITY
134 #include <sys/resource.h> // for setpriority()
137 // ----------------------------------------------------------------------------
138 // conditional compilation
139 // ----------------------------------------------------------------------------
141 // many versions of Unices have this function, but it is not defined in system
142 // headers - please add your system here if it is the case for your OS.
143 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
144 #if !defined(HAVE_USLEEP) && \
145 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
146 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
147 defined(__osf__) || defined(__EMX__))
151 /* I copied this from the XFree86 diffs. AV. */
152 #define INCL_DOSPROCESS
154 inline void usleep(unsigned long delay
)
156 DosSleep(delay
? (delay
/1000l) : 1l);
159 int usleep(unsigned int usec
);
160 #endif // __EMX__/Unix
163 #define HAVE_USLEEP 1
164 #endif // Unices without usleep()
166 // ============================================================================
168 // ============================================================================
170 // ----------------------------------------------------------------------------
172 // ----------------------------------------------------------------------------
174 void wxSleep(int nSecs
)
179 void wxMicroSleep(unsigned long microseconds
)
181 #if defined(HAVE_NANOSLEEP)
183 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
184 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
186 // we're not interested in remaining time nor in return value
187 (void)nanosleep(&tmReq
, NULL
);
188 #elif defined(HAVE_USLEEP)
189 // uncomment this if you feel brave or if you are sure that your version
190 // of Solaris has a safe usleep() function but please notice that usleep()
191 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
192 // documented as MT-Safe
193 #if defined(__SUN__) && wxUSE_THREADS
194 #error "usleep() cannot be used in MT programs under Solaris."
197 usleep(microseconds
);
198 #elif defined(HAVE_SLEEP)
199 // under BeOS sleep() takes seconds (what about other platforms, if any?)
200 sleep(microseconds
* 1000000);
201 #else // !sleep function
202 #error "usleep() or nanosleep() function required for wxMicroSleep"
203 #endif // sleep function
206 void wxMilliSleep(unsigned long milliseconds
)
208 wxMicroSleep(milliseconds
*1000);
211 // ----------------------------------------------------------------------------
212 // process management
213 // ----------------------------------------------------------------------------
215 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
217 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
220 switch ( err
? errno
: 0 )
227 *rc
= wxKILL_BAD_SIGNAL
;
231 *rc
= wxKILL_ACCESS_DENIED
;
235 *rc
= wxKILL_NO_PROCESS
;
239 // this goes against Unix98 docs so log it
240 wxLogDebug(wxT("unexpected kill(2) return value %d"), err
);
250 // Shutdown or reboot the PC
251 bool wxShutdown(int flags
)
253 flags
&= ~wxSHUTDOWN_FORCE
;
258 case wxSHUTDOWN_POWEROFF
:
262 case wxSHUTDOWN_REBOOT
:
266 case wxSHUTDOWN_LOGOFF
:
267 // TODO: use dcop to log off?
271 wxFAIL_MSG( wxT("unknown wxShutdown() flag") );
275 return system(wxString::Format("init %c", level
).mb_str()) == 0;
278 // ----------------------------------------------------------------------------
279 // wxStream classes to support IO redirection in wxExecute
280 // ----------------------------------------------------------------------------
284 bool wxPipeInputStream::CanRead() const
286 if ( m_lasterror
== wxSTREAM_EOF
)
289 // check if there is any input available
294 const int fd
= m_file
->fd();
299 wxFD_SET(fd
, &readfds
);
301 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
304 wxLogSysError(_("Impossible to get child process input"));
311 wxFAIL_MSG(wxT("unexpected select() return value"));
312 // still fall through
315 // input available -- or maybe not, as select() returns 1 when a
316 // read() will complete without delay, but it could still not read
322 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t size
)
324 // We need to suppress error logging here, because on writing to a pipe
325 // which is full, wxFile::Write reports a system error. However, this is
326 // not an extraordinary situation, and it should not be reported to the
327 // user (but if really needed, the program can recognize it by checking
328 // whether LastRead() == 0.) Other errors will be reported below.
332 ret
= m_file
->Write(buffer
, size
);
335 switch ( m_file
->GetLastError() )
341 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
344 // do not treat it as an error
345 m_file
->ClearLastError();
354 wxLogSysError(_("Can't write to child process's stdin"));
355 m_lasterror
= wxSTREAM_WRITE_ERROR
;
361 #endif // HAS_PIPE_STREAMS
363 // ----------------------------------------------------------------------------
365 // ----------------------------------------------------------------------------
367 static wxString
wxMakeShellCommand(const wxString
& command
)
372 // just an interactive shell
377 // execute command in a shell
378 cmd
<< wxT("/bin/sh -c '") << command
<< wxT('\'');
384 bool wxShell(const wxString
& command
)
386 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
389 bool wxShell(const wxString
& command
, wxArrayString
& output
)
391 wxCHECK_MSG( !command
.empty(), false, wxT("can't exec shell non interactively") );
393 return wxExecute(wxMakeShellCommand(command
), output
);
399 // helper class for storing arguments as char** array suitable for passing to
400 // execvp(), whatever form they were passed to us
404 ArgsArray(const wxArrayString
& args
)
408 for ( int i
= 0; i
< m_argc
; i
++ )
410 m_argv
[i
] = wxStrdup(args
[i
]);
415 ArgsArray(wchar_t **wargv
)
418 while ( wargv
[argc
] )
423 for ( int i
= 0; i
< m_argc
; i
++ )
425 m_argv
[i
] = wxSafeConvertWX2MB(wargv
[i
]).release();
428 #endif // wxUSE_UNICODE
432 for ( int i
= 0; i
< m_argc
; i
++ )
440 operator char**() const { return m_argv
; }
446 m_argv
= new char *[m_argc
+ 1];
447 m_argv
[m_argc
] = NULL
;
453 wxDECLARE_NO_COPY_CLASS(ArgsArray
);
456 } // anonymous namespace
458 // ----------------------------------------------------------------------------
459 // wxExecute implementations
460 // ----------------------------------------------------------------------------
462 #if defined(__DARWIN__)
463 bool wxMacLaunch(char **argv
);
466 long wxExecute(const wxString
& command
, int flags
, wxProcess
*process
,
467 const wxExecuteEnv
*env
)
469 ArgsArray
argv(wxCmdLineParser::ConvertStringToArgs(command
,
470 wxCMD_LINE_SPLIT_UNIX
));
472 return wxExecute(argv
, flags
, process
, env
);
477 long wxExecute(wchar_t **wargv
, int flags
, wxProcess
*process
,
478 const wxExecuteEnv
*env
)
480 ArgsArray
argv(wargv
);
482 return wxExecute(argv
, flags
, process
, env
);
485 #endif // wxUSE_UNICODE
487 // wxExecute: the real worker function
488 long wxExecute(char **argv
, int flags
, wxProcess
*process
,
489 const wxExecuteEnv
*env
)
491 // for the sync execution, we return -1 to indicate failure, but for async
492 // case we return 0 which is never a valid PID
494 // we define this as a macro, not a variable, to avoid compiler warnings
495 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
496 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
498 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
501 // fork() doesn't mix well with POSIX threads: on many systems the program
502 // deadlocks or crashes for some reason. Probably our code is buggy and
503 // doesn't do something which must be done to allow this to work, but I
504 // don't know what yet, so for now just warn the user (this is the least we
506 wxASSERT_MSG( wxThread::IsMain(),
507 wxT("wxExecute() can be called only from the main thread") );
508 #endif // wxUSE_THREADS
510 #if defined(__WXCOCOA__) || ( defined(__WXOSX_MAC__) && wxOSX_USE_COCOA_OR_CARBON )
511 // wxMacLaunch() only executes app bundles and only does it asynchronously.
512 // It returns false if the target is not an app bundle, thus falling
513 // through to the regular code for non app bundles.
514 if ( !(flags
& wxEXEC_SYNC
) && wxMacLaunch(argv
) )
516 // we don't have any PID to return so just make up something non null
522 // this struct contains all information which we use for housekeeping
523 wxExecuteData execData
;
524 execData
.flags
= flags
;
525 execData
.process
= process
;
528 if ( !execData
.pipeEndProcDetect
.Create() )
530 wxLogError( _("Failed to execute '%s'\n"), *argv
);
532 return ERROR_RETURN_CODE
;
535 // pipes for inter process communication
536 wxPipe pipeIn
, // stdin
540 if ( process
&& process
->IsRedirected() )
542 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
544 wxLogError( _("Failed to execute '%s'\n"), *argv
);
546 return ERROR_RETURN_CODE
;
550 // priority: we need to map wxWidgets priority which is in the range 0..100
551 // to Unix nice value which is in the range -20..19. As there is an odd
552 // number of elements in our range and an even number in the Unix one, we
553 // have to do it in this rather ugly way to guarantee that:
554 // 1. wxPRIORITY_{MIN,DEFAULT,MAX} map to -20, 0 and 19 respectively.
555 // 2. The mapping is monotonously increasing.
556 // 3. The mapping is onto the target range.
557 int prio
= process
? process
->GetPriority() : 0;
559 prio
= (2*prio
)/5 - 20;
560 else if ( prio
< 55 )
563 prio
= (2*prio
)/5 - 21;
567 // NB: do *not* use vfork() here, it completely breaks this code for some
568 // reason under Solaris (and maybe others, although not under Linux)
569 // But on OpenVMS we do not have fork so we have to use vfork and
570 // cross our fingers that it works.
576 if ( pid
== -1 ) // error?
578 wxLogSysError( _("Fork failed") );
580 return ERROR_RETURN_CODE
;
582 else if ( pid
== 0 ) // we're in child
584 // NB: we used to close all the unused descriptors of the child here
585 // but this broke some programs which relied on e.g. FD 1 being
586 // always opened so don't do it any more, after all there doesn't
587 // seem to be any real problem with keeping them opened
589 #if !defined(__VMS) && !defined(__EMX__)
590 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
592 // Set process group to child process' pid. Then killing -pid
593 // of the parent will kill the process and all of its children.
598 #if defined(HAVE_SETPRIORITY)
599 if ( prio
&& setpriority(PRIO_PROCESS
, 0, prio
) != 0 )
601 wxLogSysError(_("Failed to set process priority"));
603 #endif // HAVE_SETPRIORITY
605 // redirect stdin, stdout and stderr
608 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
609 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
610 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
612 wxLogSysError(_("Failed to redirect child process input/output"));
620 // Close all (presumably accidentally) inherited file descriptors to
621 // avoid descriptor leaks. This means that we don't allow inheriting
622 // them purposefully but this seems like a lesser evil in wx code.
623 // Ideally we'd provide some flag to indicate that none (or some?) of
624 // the descriptors do not need to be closed but for now this is better
625 // than never closing them at all as wx code never used FD_CLOEXEC.
627 // Note that while the reading side of the end process detection pipe
628 // can be safely closed, we should keep the write one opened, it will
629 // be only closed when the process terminates resulting in a read
630 // notification to the parent
631 const int fdEndProc
= execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
632 execData
.pipeEndProcDetect
.Close();
634 // TODO: Iterating up to FD_SETSIZE is both inefficient (because it may
635 // be quite big) and incorrect (because in principle we could
636 // have more opened descriptions than this number). Unfortunately
637 // there is no good portable solution for closing all descriptors
638 // above a certain threshold but non-portable solutions exist for
639 // most platforms, see [http://stackoverflow.com/questions/899038/
640 // getting-the-highest-allocated-file-descriptor]
641 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; ++fd
)
643 if ( fd
!= STDIN_FILENO
&&
644 fd
!= STDOUT_FILENO
&&
645 fd
!= STDERR_FILENO
&&
653 // Process additional options if we have any
656 // Change working directory if it is specified
657 if ( !env
->cwd
.empty() )
658 wxSetWorkingDirectory(env
->cwd
);
660 // Change environment if needed.
662 // NB: We can't use execve() currently because we allow using
663 // non full paths to wxExecute(), i.e. we want to search for
664 // the program in PATH. However it just might be simpler/better
665 // to do the search manually and use execve() envp parameter to
666 // set up the environment of the child process explicitly
667 // instead of doing what we do below.
668 if ( !env
->env
.empty() )
670 wxEnvVariableHashMap oldenv
;
671 wxGetEnvMap(&oldenv
);
673 // Remove unwanted variables
674 wxEnvVariableHashMap::const_iterator it
;
675 for ( it
= oldenv
.begin(); it
!= oldenv
.end(); ++it
)
677 if ( env
->env
.find(it
->first
) == env
->env
.end() )
678 wxUnsetEnv(it
->first
);
681 // And add the new ones (possibly replacing the old values)
682 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
683 wxSetEnv(it
->first
, it
->second
);
689 fprintf(stderr
, "execvp(");
690 for ( char **a
= argv
; *a
; a
++ )
691 fprintf(stderr
, "%s%s", a
== argv
? "" : ", ", *a
);
692 fprintf(stderr
, ") failed with error %d!\n", errno
);
694 // there is no return after successful exec()
697 // some compilers complain about missing return - of course, they
698 // should know that exit() doesn't return but what else can we do if
701 // and, sure enough, other compilers complain about unreachable code
702 // after exit() call, so we can just always have return here...
703 #if defined(__VMS) || defined(__INTEL_COMPILER)
707 else // we're in parent
709 // save it for WaitForChild() use
711 if (execData
.process
)
712 execData
.process
->SetPid(pid
); // and also in the wxProcess
714 // prepare for IO redirection
717 // the input buffer bufOut is connected to stdout, this is why it is
718 // called bufOut and not bufIn
719 wxStreamTempInputBuffer bufOut
,
722 if ( process
&& process
->IsRedirected() )
724 // Avoid deadlocks which could result from trying to write to the
725 // child input pipe end while the child itself is writing to its
726 // output end and waiting for us to read from it.
727 if ( !pipeIn
.MakeNonBlocking(wxPipe::Write
) )
729 // This message is not terrible useful for the user but what
730 // else can we do? Also, should we fail here or take the risk
731 // to continue and deadlock? Currently we choose the latter but
732 // it might not be the best idea.
733 wxLogSysError(_("Failed to set up non-blocking pipe, "
734 "the program might hang."));
736 wxLog::FlushActive();
740 wxOutputStream
*inStream
=
741 new wxPipeOutputStream(pipeIn
.Detach(wxPipe::Write
));
743 const int fdOut
= pipeOut
.Detach(wxPipe::Read
);
744 wxPipeInputStream
*outStream
= new wxPipeInputStream(fdOut
);
746 const int fdErr
= pipeErr
.Detach(wxPipe::Read
);
747 wxPipeInputStream
*errStream
= new wxPipeInputStream(fdErr
);
749 process
->SetPipeStreams(outStream
, inStream
, errStream
);
751 bufOut
.Init(outStream
);
752 bufErr
.Init(errStream
);
754 execData
.bufOut
= &bufOut
;
755 execData
.bufErr
= &bufErr
;
757 execData
.fdOut
= fdOut
;
758 execData
.fdErr
= fdErr
;
760 #endif // HAS_PIPE_STREAMS
769 // we want this function to work even if there is no wxApp so ensure
770 // that we have a valid traits pointer
771 wxConsoleAppTraits traitsConsole
;
772 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
774 traits
= &traitsConsole
;
776 return traits
->WaitForChild(execData
);
779 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
780 return ERROR_RETURN_CODE
;
784 #undef ERROR_RETURN_CODE
786 // ----------------------------------------------------------------------------
787 // file and directory functions
788 // ----------------------------------------------------------------------------
790 const wxChar
* wxGetHomeDir( wxString
*home
)
792 *home
= wxGetUserHome();
798 if ( tmp
.Last() != wxT(']'))
799 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
801 return home
->c_str();
804 wxString
wxGetUserHome( const wxString
&user
)
806 struct passwd
*who
= (struct passwd
*) NULL
;
812 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
817 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
||
818 (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
820 who
= getpwnam(wxSafeConvertWX2MB(ptr
));
823 // make sure the user exists!
826 who
= getpwuid(getuid());
831 who
= getpwnam (user
.mb_str());
834 return wxSafeConvertMB2WX(who
? who
->pw_dir
: 0);
837 // ----------------------------------------------------------------------------
838 // network and user id routines
839 // ----------------------------------------------------------------------------
841 // private utility function which returns output of the given command, removing
842 // the trailing newline
843 static wxString
wxGetCommandOutput(const wxString
&cmd
)
845 // Suppress stderr from the shell to avoid outputting errors if the command
847 FILE *f
= popen((cmd
+ " 2>/dev/null").ToAscii(), "r");
850 // Notice that this doesn't happen simply if the command doesn't exist,
851 // but only in case of some really catastrophic failure inside popen()
852 // so we should really notify the user about this as this is not normal.
853 wxLogSysError(wxT("Executing \"%s\" failed"), cmd
);
861 if ( !fgets(buf
, sizeof(buf
), f
) )
864 s
+= wxString::FromAscii(buf
);
869 if ( !s
.empty() && s
.Last() == wxT('\n') )
875 // retrieve either the hostname or FQDN depending on platform (caller must
876 // check whether it's one or the other, this is why this function is for
878 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
880 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
884 // we're using uname() which is POSIX instead of less standard sysinfo()
885 #if defined(HAVE_UNAME)
887 bool ok
= uname(&uts
) != -1;
890 wxStrlcpy(buf
, wxSafeConvertMB2WX(uts
.nodename
), sz
);
892 #elif defined(HAVE_GETHOSTNAME)
894 bool ok
= gethostname(cbuf
, sz
) != -1;
897 wxStrlcpy(buf
, wxSafeConvertMB2WX(cbuf
), sz
);
899 #else // no uname, no gethostname
900 wxFAIL_MSG(wxT("don't know host name for this machine"));
903 #endif // uname/gethostname
907 wxLogSysError(_("Cannot get the hostname"));
913 bool wxGetHostName(wxChar
*buf
, int sz
)
915 bool ok
= wxGetHostNameInternal(buf
, sz
);
919 // BSD systems return the FQDN, we only want the hostname, so extract
920 // it (we consider that dots are domain separators)
921 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
932 bool wxGetFullHostName(wxChar
*buf
, int sz
)
934 bool ok
= wxGetHostNameInternal(buf
, sz
);
938 if ( !wxStrchr(buf
, wxT('.')) )
940 struct hostent
*host
= gethostbyname(wxSafeConvertWX2MB(buf
));
943 wxLogSysError(_("Cannot get the official hostname"));
949 // the canonical name
950 wxStrlcpy(buf
, wxSafeConvertMB2WX(host
->h_name
), sz
);
953 //else: it's already a FQDN (BSD behaves this way)
959 bool wxGetUserId(wxChar
*buf
, int sz
)
964 if ((who
= getpwuid(getuid ())) != NULL
)
966 wxStrlcpy (buf
, wxSafeConvertMB2WX(who
->pw_name
), sz
);
973 bool wxGetUserName(wxChar
*buf
, int sz
)
979 if ((who
= getpwuid (getuid ())) != NULL
)
981 char *comma
= strchr(who
->pw_gecos
, ',');
983 *comma
= '\0'; // cut off non-name comment fields
984 wxStrlcpy(buf
, wxSafeConvertMB2WX(who
->pw_gecos
), sz
);
989 #else // !HAVE_PW_GECOS
990 return wxGetUserId(buf
, sz
);
991 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
994 bool wxIsPlatform64Bit()
996 const wxString machine
= wxGetCommandOutput(wxT("uname -m"));
998 // the test for "64" is obviously not 100% reliable but seems to work fine
1000 return machine
.Contains(wxT("64")) ||
1001 machine
.Contains(wxT("alpha"));
1005 wxLinuxDistributionInfo
wxGetLinuxDistributionInfo()
1007 const wxString id
= wxGetCommandOutput(wxT("lsb_release --id"));
1008 const wxString desc
= wxGetCommandOutput(wxT("lsb_release --description"));
1009 const wxString rel
= wxGetCommandOutput(wxT("lsb_release --release"));
1010 const wxString codename
= wxGetCommandOutput(wxT("lsb_release --codename"));
1012 wxLinuxDistributionInfo ret
;
1014 id
.StartsWith("Distributor ID:\t", &ret
.Id
);
1015 desc
.StartsWith("Description:\t", &ret
.Description
);
1016 rel
.StartsWith("Release:\t", &ret
.Release
);
1017 codename
.StartsWith("Codename:\t", &ret
.CodeName
);
1023 // these functions are in src/osx/utilsexc_base.cpp for wxMac
1026 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
1030 wxString release
= wxGetCommandOutput(wxT("uname -r"));
1031 if ( release
.empty() ||
1032 wxSscanf(release
.c_str(), wxT("%d.%d"), &major
, &minor
) != 2 )
1034 // failed to get version string or unrecognized format
1044 // try to understand which OS are we running
1045 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
1046 if ( kernel
.empty() )
1047 kernel
= wxGetCommandOutput(wxT("uname -o"));
1049 if ( kernel
.empty() )
1050 return wxOS_UNKNOWN
;
1052 return wxPlatformInfo::GetOperatingSystemId(kernel
);
1055 wxString
wxGetOsDescription()
1057 return wxGetCommandOutput(wxT("uname -s -r -m"));
1060 #endif // !__DARWIN__
1062 unsigned long wxGetProcessId()
1064 return (unsigned long)getpid();
1067 wxMemorySize
wxGetFreeMemory()
1069 #if defined(__LINUX__)
1070 // get it from /proc/meminfo
1071 FILE *fp
= fopen("/proc/meminfo", "r");
1077 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
1079 // /proc/meminfo changed its format in kernel 2.6
1080 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
1082 unsigned long cached
, buffers
;
1083 sscanf(buf
, "MemFree: %ld", &memFree
);
1085 fgets(buf
, WXSIZEOF(buf
), fp
);
1086 sscanf(buf
, "Buffers: %lu", &buffers
);
1088 fgets(buf
, WXSIZEOF(buf
), fp
);
1089 sscanf(buf
, "Cached: %lu", &cached
);
1091 // add to "MemFree" also the "Buffers" and "Cached" values as
1092 // free(1) does as otherwise the value never makes sense: for
1093 // kernel 2.6 it's always almost 0
1094 memFree
+= buffers
+ cached
;
1096 // values here are always expressed in kB and we want bytes
1099 else // Linux 2.4 (or < 2.6, anyhow)
1101 long memTotal
, memUsed
;
1102 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
1108 return (wxMemorySize
)memFree
;
1110 #elif defined(__SGI__)
1111 struct rminfo realmem
;
1112 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
1113 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
1114 #elif defined(_SC_AVPHYS_PAGES)
1115 return ((wxMemorySize
)sysconf(_SC_AVPHYS_PAGES
))*sysconf(_SC_PAGESIZE
);
1116 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1119 // can't find it out
1123 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
1125 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1126 // the case to "char *" is needed for AIX 4.3
1128 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
1130 wxLogSysError( wxT("Failed to get file system statistics") );
1135 // under Solaris we also have to use f_frsize field instead of f_bsize
1136 // which is in general a multiple of f_frsize
1138 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1139 #else // HAVE_STATFS
1140 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1141 #endif // HAVE_STATVFS/HAVE_STATFS
1145 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1150 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1154 #else // !HAVE_STATFS && !HAVE_STATVFS
1156 #endif // HAVE_STATFS
1159 // ----------------------------------------------------------------------------
1161 // ----------------------------------------------------------------------------
1165 WX_DECLARE_STRING_HASH_MAP(char *, wxEnvVars
);
1167 static wxEnvVars gs_envVars
;
1169 class wxSetEnvModule
: public wxModule
1172 virtual bool OnInit() { return true; }
1173 virtual void OnExit()
1175 for ( wxEnvVars::const_iterator i
= gs_envVars
.begin();
1176 i
!= gs_envVars
.end();
1185 DECLARE_DYNAMIC_CLASS(wxSetEnvModule
)
1188 IMPLEMENT_DYNAMIC_CLASS(wxSetEnvModule
, wxModule
)
1190 #endif // USE_PUTENV
1192 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1194 // wxGetenv is defined as getenv()
1195 char *p
= wxGetenv(var
);
1207 static bool wxDoSetEnv(const wxString
& variable
, const char *value
)
1209 #if defined(HAVE_SETENV)
1212 #ifdef HAVE_UNSETENV
1213 // don't test unsetenv() return value: it's void on some systems (at
1215 unsetenv(variable
.mb_str());
1218 value
= ""; // we can't pass NULL to setenv()
1222 return setenv(variable
.mb_str(), value
, 1 /* overwrite */) == 0;
1223 #elif defined(HAVE_PUTENV)
1224 wxString s
= variable
;
1226 s
<< wxT('=') << value
;
1228 // transform to ANSI
1229 const wxWX2MBbuf p
= s
.mb_str();
1231 char *buf
= (char *)malloc(strlen(p
) + 1);
1234 // store the string to free() it later
1235 wxEnvVars::iterator i
= gs_envVars
.find(variable
);
1236 if ( i
!= gs_envVars
.end() )
1241 else // this variable hadn't been set before
1243 gs_envVars
[variable
] = buf
;
1246 return putenv(buf
) == 0;
1247 #else // no way to set an env var
1252 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
1254 return wxDoSetEnv(variable
, value
.mb_str());
1257 bool wxUnsetEnv(const wxString
& variable
)
1259 return wxDoSetEnv(variable
, NULL
);
1262 // ----------------------------------------------------------------------------
1264 // ----------------------------------------------------------------------------
1266 #if wxUSE_ON_FATAL_EXCEPTION
1270 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1274 // give the user a chance to do something special about this
1275 wxTheApp
->OnFatalException();
1281 bool wxHandleFatalExceptions(bool doit
)
1284 static bool s_savedHandlers
= false;
1285 static struct sigaction s_handlerFPE
,
1291 if ( doit
&& !s_savedHandlers
)
1293 // install the signal handler
1294 struct sigaction act
;
1296 // some systems extend it with non std fields, so zero everything
1297 memset(&act
, 0, sizeof(act
));
1299 act
.sa_handler
= wxFatalSignalHandler
;
1300 sigemptyset(&act
.sa_mask
);
1303 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1304 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1305 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1306 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1309 wxLogDebug(wxT("Failed to install our signal handler."));
1312 s_savedHandlers
= true;
1314 else if ( s_savedHandlers
)
1316 // uninstall the signal handler
1317 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1318 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1319 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1320 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1323 wxLogDebug(wxT("Failed to uninstall our signal handler."));
1326 s_savedHandlers
= false;
1328 //else: nothing to do
1333 #endif // wxUSE_ON_FATAL_EXCEPTION
1335 // ----------------------------------------------------------------------------
1336 // wxExecute support
1337 // ----------------------------------------------------------------------------
1339 int wxAppTraits::AddProcessCallback(wxEndProcessData
*data
, int fd
)
1341 // define a custom handler processing only the closure of the descriptor
1342 struct wxEndProcessFDIOHandler
: public wxFDIOHandler
1344 wxEndProcessFDIOHandler(wxEndProcessData
*data
, int fd
)
1345 : m_data(data
), m_fd(fd
)
1349 virtual void OnReadWaiting()
1351 wxFDIODispatcher::Get()->UnregisterFD(m_fd
);
1354 wxHandleProcessTermination(m_data
);
1359 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1360 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1362 wxEndProcessData
* const m_data
;
1366 wxFDIODispatcher::Get()->RegisterFD
1369 new wxEndProcessFDIOHandler(data
, fd
),
1372 return fd
; // unused, but return something unique for the tag
1375 bool wxAppTraits::CheckForRedirectedIO(wxExecuteData
& execData
)
1377 #if HAS_PIPE_STREAMS
1380 if ( execData
.bufOut
&& execData
.bufOut
->Update() )
1383 if ( execData
.bufErr
&& execData
.bufErr
->Update() )
1387 #else // !HAS_PIPE_STREAMS
1388 wxUnusedVar(execData
);
1391 #endif // HAS_PIPE_STREAMS/!HAS_PIPE_STREAMS
1394 // helper classes/functions used by WaitForChild()
1398 // convenient base class for IO handlers which are registered for read
1399 // notifications only and which also stores the FD we're reading from
1401 // the derived classes still have to implement OnReadWaiting()
1402 class wxReadFDIOHandler
: public wxFDIOHandler
1405 wxReadFDIOHandler(wxFDIODispatcher
& disp
, int fd
) : m_fd(fd
)
1408 disp
.RegisterFD(fd
, this, wxFDIO_INPUT
);
1411 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1412 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1417 wxDECLARE_NO_COPY_CLASS(wxReadFDIOHandler
);
1420 // class for monitoring our end of the process detection pipe, simply sets a
1421 // flag when input on the pipe (which must be due to EOF) is detected
1422 class wxEndHandler
: public wxReadFDIOHandler
1425 wxEndHandler(wxFDIODispatcher
& disp
, int fd
)
1426 : wxReadFDIOHandler(disp
, fd
)
1428 m_terminated
= false;
1431 bool Terminated() const { return m_terminated
; }
1433 virtual void OnReadWaiting() { m_terminated
= true; }
1438 wxDECLARE_NO_COPY_CLASS(wxEndHandler
);
1441 #if HAS_PIPE_STREAMS
1443 // class for monitoring our ends of child stdout/err, should be constructed
1444 // with the FD and stream from wxExecuteData and will do nothing if they're
1447 // unlike wxEndHandler this class registers itself with the provided dispatcher
1448 class wxRedirectedIOHandler
: public wxReadFDIOHandler
1451 wxRedirectedIOHandler(wxFDIODispatcher
& disp
,
1453 wxStreamTempInputBuffer
*buf
)
1454 : wxReadFDIOHandler(disp
, fd
),
1459 virtual void OnReadWaiting()
1465 wxStreamTempInputBuffer
* const m_buf
;
1467 wxDECLARE_NO_COPY_CLASS(wxRedirectedIOHandler
);
1470 #endif // HAS_PIPE_STREAMS
1472 // helper function which calls waitpid() and analyzes the result
1473 int DoWaitForChild(int pid
, int flags
= 0)
1475 wxASSERT_MSG( pid
> 0, "invalid PID" );
1479 // loop while we're getting EINTR
1482 rc
= waitpid(pid
, &status
, flags
);
1484 if ( rc
!= -1 || errno
!= EINTR
)
1490 // This can only happen if the child application closes our dummy pipe
1491 // that is used to monitor its lifetime; in that case, our best bet is
1492 // to pretend the process did terminate, because otherwise wxExecute()
1493 // would hang indefinitely (OnReadWaiting() won't be called again, the
1494 // descriptor is closed now).
1495 wxLogDebug("Child process (PID %d) still alive but pipe closed so "
1496 "generating a close notification", pid
);
1498 else if ( rc
== -1 )
1500 wxLogLastError(wxString::Format("waitpid(%d)", pid
));
1502 else // child did terminate
1504 wxASSERT_MSG( rc
== pid
, "unexpected waitpid() return value" );
1506 // notice that the caller expects the exit code to be signed, e.g. -1
1507 // instead of 255 so don't assign WEXITSTATUS() to an int
1508 signed char exitcode
;
1509 if ( WIFEXITED(status
) )
1510 exitcode
= WEXITSTATUS(status
);
1511 else if ( WIFSIGNALED(status
) )
1512 exitcode
= -WTERMSIG(status
);
1515 wxLogError("Child process (PID %d) exited for unknown reason, "
1516 "status = %d", pid
, status
);
1526 } // anonymous namespace
1528 int wxAppTraits::WaitForChild(wxExecuteData
& execData
)
1530 if ( !(execData
.flags
& wxEXEC_SYNC
) )
1532 // asynchronous execution: just launch the process and return,
1533 // endProcData will be destroyed when it terminates (currently we leak
1534 // it if the process doesn't terminate before we do and this should be
1535 // fixed but it's not a real leak so it's not really very high
1537 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1538 endProcData
->process
= execData
.process
;
1539 endProcData
->pid
= execData
.pid
;
1540 endProcData
->tag
= AddProcessCallback
1543 execData
.GetEndProcReadFD()
1545 endProcData
->async
= true;
1547 return execData
.pid
;
1549 //else: synchronous execution case
1551 #if HAS_PIPE_STREAMS && wxUSE_SOCKETS
1552 wxProcess
* const process
= execData
.process
;
1553 if ( process
&& process
->IsRedirected() )
1555 // we can't simply block waiting for the child to terminate as we would
1556 // dead lock if it writes more than the pipe buffer size (typically
1557 // 4KB) bytes of output -- it would then block waiting for us to read
1558 // the data while we'd block waiting for it to terminate
1560 // so multiplex here waiting for any input from the child or closure of
1561 // the pipe used to indicate its termination
1562 wxSelectDispatcher disp
;
1564 wxEndHandler
endHandler(disp
, execData
.GetEndProcReadFD());
1566 wxRedirectedIOHandler
outHandler(disp
, execData
.fdOut
, execData
.bufOut
),
1567 errHandler(disp
, execData
.fdErr
, execData
.bufErr
);
1569 while ( !endHandler
.Terminated() )
1574 //else: no IO redirection, just block waiting for the child to exit
1575 #endif // HAS_PIPE_STREAMS
1577 return DoWaitForChild(execData
.pid
);
1580 void wxHandleProcessTermination(wxEndProcessData
*data
)
1582 data
->exitcode
= DoWaitForChild(data
->pid
, WNOHANG
);
1584 // notify user about termination if required
1585 if ( data
->process
)
1587 data
->process
->OnTerminate(data
->pid
, data
->exitcode
);
1592 // in case of asynchronous execution we don't need this data any more
1593 // after the child terminates
1596 else // sync execution
1598 // let wxExecute() know that the process has terminated