1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/utilsunx.cpp
3 // Purpose: generic Unix implementation of many wx functions (for wxBase)
4 // Author: Vadim Zeitlin
5 // Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
6 // (c) 2013 Rob Bresalier, 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/scopedptr.h"
41 #include "wx/thread.h"
43 #include "wx/cmdline.h"
45 #include "wx/wfstream.h"
47 #include "wx/private/selectdispatcher.h"
48 #include "wx/private/fdiodispatcher.h"
49 #include "wx/unix/execute.h"
50 #include "wx/unix/pipe.h"
51 #include "wx/unix/private.h"
53 #include "wx/evtloop.h"
54 #include "wx/mstream.h"
55 #include "wx/private/fdioeventloopsourcehandler.h"
58 #include <sys/wait.h> // waitpid()
60 #ifdef HAVE_SYS_SELECT_H
61 # include <sys/select.h>
64 #define HAS_PIPE_STREAMS (wxUSE_STREAMS && wxUSE_FILE)
68 #include "wx/private/pipestream.h"
69 #include "wx/private/streamtempinput.h"
70 #include "wx/unix/private/executeiohandler.h"
72 #endif // HAS_PIPE_STREAMS
74 // not only the statfs syscall is called differently depending on platform, but
75 // one of its incarnations, statvfs(), takes different arguments under
76 // different platforms and even different versions of the same system (Solaris
77 // 7 and 8): if you want to test for this, don't forget that the problems only
78 // appear if the large files support is enabled
81 #include <sys/param.h>
82 #include <sys/mount.h>
85 #endif // __BSD__/!__BSD__
87 #define wxStatfs statfs
89 #ifndef HAVE_STATFS_DECL
90 // some systems lack statfs() prototype in the system headers (AIX 4)
91 extern "C" int statfs(const char *path
, struct statfs
*buf
);
96 #include <sys/statvfs.h>
98 #define wxStatfs statvfs
99 #endif // HAVE_STATVFS
101 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
102 // WX_STATFS_T is detected by configure
103 #define wxStatfs_t WX_STATFS_T
106 // SGI signal.h defines signal handler arguments differently depending on
107 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
108 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
109 #define _LANGUAGE_C_PLUS_PLUS 1
115 #include <sys/stat.h>
116 #include <sys/types.h>
117 #include <sys/wait.h>
122 #include <time.h> // nanosleep() and/or usleep()
123 #include <ctype.h> // isspace()
124 #include <sys/time.h> // needed for FD_SETSIZE
127 #include <sys/utsname.h> // for uname()
130 // Used by wxGetFreeMemory().
132 #include <sys/sysmp.h>
133 #include <sys/sysinfo.h> // for SAGET and MINFO structures
136 #ifdef HAVE_SETPRIORITY
137 #include <sys/resource.h> // for setpriority()
140 // ----------------------------------------------------------------------------
141 // conditional compilation
142 // ----------------------------------------------------------------------------
144 // many versions of Unices have this function, but it is not defined in system
145 // headers - please add your system here if it is the case for your OS.
146 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
147 #if !defined(HAVE_USLEEP) && \
148 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
149 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
150 defined(__osf__) || defined(__EMX__))
154 /* I copied this from the XFree86 diffs. AV. */
155 #define INCL_DOSPROCESS
157 inline void usleep(unsigned long delay
)
159 DosSleep(delay
? (delay
/1000l) : 1l);
162 int usleep(unsigned int usec
);
163 #endif // __EMX__/Unix
166 #define HAVE_USLEEP 1
167 #endif // Unices without usleep()
169 // ============================================================================
171 // ============================================================================
173 // ----------------------------------------------------------------------------
175 // ----------------------------------------------------------------------------
177 void wxSleep(int nSecs
)
182 void wxMicroSleep(unsigned long microseconds
)
184 #if defined(HAVE_NANOSLEEP)
186 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
187 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
189 // we're not interested in remaining time nor in return value
190 (void)nanosleep(&tmReq
, NULL
);
191 #elif defined(HAVE_USLEEP)
192 // uncomment this if you feel brave or if you are sure that your version
193 // of Solaris has a safe usleep() function but please notice that usleep()
194 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
195 // documented as MT-Safe
196 #if defined(__SUN__) && wxUSE_THREADS
197 #error "usleep() cannot be used in MT programs under Solaris."
200 usleep(microseconds
);
201 #elif defined(HAVE_SLEEP)
202 // under BeOS sleep() takes seconds (what about other platforms, if any?)
203 sleep(microseconds
* 1000000);
204 #else // !sleep function
205 #error "usleep() or nanosleep() function required for wxMicroSleep"
206 #endif // sleep function
209 void wxMilliSleep(unsigned long milliseconds
)
211 wxMicroSleep(milliseconds
*1000);
214 // ----------------------------------------------------------------------------
215 // process management
216 // ----------------------------------------------------------------------------
218 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
220 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
223 switch ( err
? errno
: 0 )
230 *rc
= wxKILL_BAD_SIGNAL
;
234 *rc
= wxKILL_ACCESS_DENIED
;
238 *rc
= wxKILL_NO_PROCESS
;
242 // this goes against Unix98 docs so log it
243 wxLogDebug(wxT("unexpected kill(2) return value %d"), err
);
253 // Shutdown or reboot the PC
254 bool wxShutdown(int flags
)
256 flags
&= ~wxSHUTDOWN_FORCE
;
261 case wxSHUTDOWN_POWEROFF
:
265 case wxSHUTDOWN_REBOOT
:
269 case wxSHUTDOWN_LOGOFF
:
270 // TODO: use dcop to log off?
274 wxFAIL_MSG( wxT("unknown wxShutdown() flag") );
278 return system(wxString::Format("init %c", level
).mb_str()) == 0;
281 // ----------------------------------------------------------------------------
282 // wxStream classes to support IO redirection in wxExecute
283 // ----------------------------------------------------------------------------
287 bool wxPipeInputStream::CanRead() const
289 if ( m_lasterror
== wxSTREAM_EOF
)
292 // check if there is any input available
297 const int fd
= m_file
->fd();
302 wxFD_SET(fd
, &readfds
);
304 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
307 wxLogSysError(_("Impossible to get child process input"));
314 wxFAIL_MSG(wxT("unexpected select() return value"));
315 // still fall through
318 // input available -- or maybe not, as select() returns 1 when a
319 // read() will complete without delay, but it could still not read
325 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t size
)
327 // We need to suppress error logging here, because on writing to a pipe
328 // which is full, wxFile::Write reports a system error. However, this is
329 // not an extraordinary situation, and it should not be reported to the
330 // user (but if really needed, the program can recognize it by checking
331 // whether LastRead() == 0.) Other errors will be reported below.
335 ret
= m_file
->Write(buffer
, size
);
338 switch ( m_file
->GetLastError() )
344 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
347 // do not treat it as an error
348 m_file
->ClearLastError();
357 wxLogSysError(_("Can't write to child process's stdin"));
358 m_lasterror
= wxSTREAM_WRITE_ERROR
;
364 #endif // HAS_PIPE_STREAMS
366 // ----------------------------------------------------------------------------
368 // ----------------------------------------------------------------------------
370 static wxString
wxMakeShellCommand(const wxString
& command
)
375 // just an interactive shell
380 // execute command in a shell
381 cmd
<< wxT("/bin/sh -c '") << command
<< wxT('\'');
387 bool wxShell(const wxString
& command
)
389 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
392 bool wxShell(const wxString
& command
, wxArrayString
& output
)
394 wxCHECK_MSG( !command
.empty(), false, wxT("can't exec shell non interactively") );
396 return wxExecute(wxMakeShellCommand(command
), output
);
402 // helper class for storing arguments as char** array suitable for passing to
403 // execvp(), whatever form they were passed to us
407 ArgsArray(const wxArrayString
& args
)
411 for ( int i
= 0; i
< m_argc
; i
++ )
413 m_argv
[i
] = wxStrdup(args
[i
]);
418 ArgsArray(wchar_t **wargv
)
421 while ( wargv
[argc
] )
426 for ( int i
= 0; i
< m_argc
; i
++ )
428 m_argv
[i
] = wxSafeConvertWX2MB(wargv
[i
]).release();
431 #endif // wxUSE_UNICODE
435 for ( int i
= 0; i
< m_argc
; i
++ )
443 operator char**() const { return m_argv
; }
449 m_argv
= new char *[m_argc
+ 1];
450 m_argv
[m_argc
] = NULL
;
456 wxDECLARE_NO_COPY_CLASS(ArgsArray
);
459 } // anonymous namespace
461 // ----------------------------------------------------------------------------
462 // wxExecute implementations
463 // ----------------------------------------------------------------------------
465 #if defined(__DARWIN__)
466 bool wxMacLaunch(char **argv
);
469 long wxExecute(const wxString
& command
, int flags
, wxProcess
*process
,
470 const wxExecuteEnv
*env
)
472 ArgsArray
argv(wxCmdLineParser::ConvertStringToArgs(command
,
473 wxCMD_LINE_SPLIT_UNIX
));
475 return wxExecute(argv
, flags
, process
, env
);
480 long wxExecute(wchar_t **wargv
, int flags
, wxProcess
*process
,
481 const wxExecuteEnv
*env
)
483 ArgsArray
argv(wargv
);
485 return wxExecute(argv
, flags
, process
, env
);
488 #endif // wxUSE_UNICODE
493 // Helper function of wxExecute(): wait for the process termination without
494 // dispatching any events.
496 // This is used in wxEXEC_NOEVENTS case.
497 int BlockUntilChildExit(wxExecuteData
& execData
)
499 wxCHECK_MSG( wxTheApp
, -1,
500 wxS("Can't block until child exit without wxTheApp") );
502 #if wxUSE_SELECT_DISPATCHER
504 // Even if we don't want to dispatch events, we still need to handle
505 // child IO notifications and process termination concurrently, i.e.
506 // we can't simply block waiting for the child to terminate as we would
507 // dead lock if it writes more than the pipe buffer size (typically
508 // 4KB) bytes of output -- it would then block waiting for us to read
509 // the data while we'd block waiting for it to terminate.
511 // So while we don't use the full blown event loop, we still do use a
512 // dispatcher with which we register just the 3 FDs we're interested
513 // in: the child stdout and stderr and the pipe written to by the
514 // signal handler so that we could react to the child process
517 // Notice that we must create a new dispatcher object here instead of
518 // reusing the global wxFDIODispatcher::Get() because we want to
519 // monitor only the events on the FDs explicitly registered with this
520 // one and not all the other ones that could be registered with the
521 // global dispatcher (think about the case of nested wxExecute() calls).
522 wxSelectDispatcher dispatcher
;
524 // Do register all the FDs we want to monitor here: first, the one used to
525 // handle the signals asynchronously.
526 wxScopedPtr
<wxFDIOHandler
>
527 signalHandler(wxTheApp
->RegisterSignalWakeUpPipe(dispatcher
));
530 // And then the two for the child output and error streams if necessary.
531 wxScopedPtr
<wxFDIOHandler
>
534 if ( execData
.IsRedirected() )
536 stdoutHandler
.reset(new wxExecuteFDIOHandler
542 stderrHandler
.reset(new wxExecuteFDIOHandler
549 #endif // wxUSE_STREAMS
551 // And dispatch until the PID is reset from wxExecuteData::OnExit().
552 while ( execData
.pid
)
554 dispatcher
.Dispatch();
557 return execData
.exitcode
;
558 #else // !wxUSE_SELECT_DISPATCHER
559 wxFAIL_MSG( wxS("Can't block until child exit without wxSelectDispatcher") );
562 #endif // wxUSE_SELECT_DISPATCHER/!wxUSE_SELECT_DISPATCHER
565 } // anonymous namespace
567 // wxExecute: the real worker function
568 long wxExecute(char **argv
, int flags
, wxProcess
*process
,
569 const wxExecuteEnv
*env
)
571 // for the sync execution, we return -1 to indicate failure, but for async
572 // case we return 0 which is never a valid PID
574 // we define this as a macro, not a variable, to avoid compiler warnings
575 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
576 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
578 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
581 // fork() doesn't mix well with POSIX threads: on many systems the program
582 // deadlocks or crashes for some reason. Probably our code is buggy and
583 // doesn't do something which must be done to allow this to work, but I
584 // don't know what yet, so for now just warn the user (this is the least we
586 wxASSERT_MSG( wxThread::IsMain(),
587 wxT("wxExecute() can be called only from the main thread") );
588 #endif // wxUSE_THREADS
590 #if defined(__WXCOCOA__) || ( defined(__WXOSX_MAC__) && wxOSX_USE_COCOA_OR_CARBON )
591 // wxMacLaunch() only executes app bundles and only does it asynchronously.
592 // It returns false if the target is not an app bundle, thus falling
593 // through to the regular code for non app bundles.
594 if ( !(flags
& wxEXEC_SYNC
) && wxMacLaunch(argv
) )
596 // we don't have any PID to return so just make up something non null
601 // this struct contains all information which we use for housekeeping
602 wxScopedPtr
<wxExecuteData
> execDataPtr(new wxExecuteData
);
603 wxExecuteData
& execData
= *execDataPtr
;
605 execData
.flags
= flags
;
606 execData
.process
= process
;
608 // create pipes for inter process communication
609 wxPipe pipeIn
, // stdin
613 if ( process
&& process
->IsRedirected() )
615 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
617 wxLogError( _("Failed to execute '%s'\n"), *argv
);
619 return ERROR_RETURN_CODE
;
623 // priority: we need to map wxWidgets priority which is in the range 0..100
624 // to Unix nice value which is in the range -20..19. As there is an odd
625 // number of elements in our range and an even number in the Unix one, we
626 // have to do it in this rather ugly way to guarantee that:
627 // 1. wxPRIORITY_{MIN,DEFAULT,MAX} map to -20, 0 and 19 respectively.
628 // 2. The mapping is monotonously increasing.
629 // 3. The mapping is onto the target range.
630 int prio
= process
? process
->GetPriority() : 0;
632 prio
= (2*prio
)/5 - 20;
633 else if ( prio
< 55 )
636 prio
= (2*prio
)/5 - 21;
640 // NB: do *not* use vfork() here, it completely breaks this code for some
641 // reason under Solaris (and maybe others, although not under Linux)
642 // But on OpenVMS we do not have fork so we have to use vfork and
643 // cross our fingers that it works.
649 if ( pid
== -1 ) // error?
651 wxLogSysError( _("Fork failed") );
653 return ERROR_RETURN_CODE
;
655 else if ( pid
== 0 ) // we're in child
657 // NB: we used to close all the unused descriptors of the child here
658 // but this broke some programs which relied on e.g. FD 1 being
659 // always opened so don't do it any more, after all there doesn't
660 // seem to be any real problem with keeping them opened
662 #if !defined(__VMS) && !defined(__EMX__)
663 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
665 // Set process group to child process' pid. Then killing -pid
666 // of the parent will kill the process and all of its children.
671 #if defined(HAVE_SETPRIORITY)
672 if ( prio
&& setpriority(PRIO_PROCESS
, 0, prio
) != 0 )
674 wxLogSysError(_("Failed to set process priority"));
676 #endif // HAVE_SETPRIORITY
678 // redirect stdin, stdout and stderr
681 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
682 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
683 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
685 wxLogSysError(_("Failed to redirect child process input/output"));
693 // Close all (presumably accidentally) inherited file descriptors to
694 // avoid descriptor leaks. This means that we don't allow inheriting
695 // them purposefully but this seems like a lesser evil in wx code.
696 // Ideally we'd provide some flag to indicate that none (or some?) of
697 // the descriptors do not need to be closed but for now this is better
698 // than never closing them at all as wx code never used FD_CLOEXEC.
700 // TODO: Iterating up to FD_SETSIZE is both inefficient (because it may
701 // be quite big) and incorrect (because in principle we could
702 // have more opened descriptions than this number). Unfortunately
703 // there is no good portable solution for closing all descriptors
704 // above a certain threshold but non-portable solutions exist for
705 // most platforms, see [http://stackoverflow.com/questions/899038/
706 // getting-the-highest-allocated-file-descriptor]
707 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; ++fd
)
709 if ( fd
!= STDIN_FILENO
&&
710 fd
!= STDOUT_FILENO
&&
711 fd
!= STDERR_FILENO
)
718 // Process additional options if we have any
721 // Change working directory if it is specified
722 if ( !env
->cwd
.empty() )
723 wxSetWorkingDirectory(env
->cwd
);
725 // Change environment if needed.
727 // NB: We can't use execve() currently because we allow using
728 // non full paths to wxExecute(), i.e. we want to search for
729 // the program in PATH. However it just might be simpler/better
730 // to do the search manually and use execve() envp parameter to
731 // set up the environment of the child process explicitly
732 // instead of doing what we do below.
733 if ( !env
->env
.empty() )
735 wxEnvVariableHashMap oldenv
;
736 wxGetEnvMap(&oldenv
);
738 // Remove unwanted variables
739 wxEnvVariableHashMap::const_iterator it
;
740 for ( it
= oldenv
.begin(); it
!= oldenv
.end(); ++it
)
742 if ( env
->env
.find(it
->first
) == env
->env
.end() )
743 wxUnsetEnv(it
->first
);
746 // And add the new ones (possibly replacing the old values)
747 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
748 wxSetEnv(it
->first
, it
->second
);
754 fprintf(stderr
, "execvp(");
755 for ( char **a
= argv
; *a
; a
++ )
756 fprintf(stderr
, "%s%s", a
== argv
? "" : ", ", *a
);
757 fprintf(stderr
, ") failed with error %d!\n", errno
);
759 // there is no return after successful exec()
762 // some compilers complain about missing return - of course, they
763 // should know that exit() doesn't return but what else can we do if
766 // and, sure enough, other compilers complain about unreachable code
767 // after exit() call, so we can just always have return here...
768 #if defined(__VMS) || defined(__INTEL_COMPILER)
772 else // we're in parent
774 execData
.OnStart(pid
);
776 // prepare for IO redirection
780 if ( process
&& process
->IsRedirected() )
782 // Avoid deadlocks which could result from trying to write to the
783 // child input pipe end while the child itself is writing to its
784 // output end and waiting for us to read from it.
785 if ( !pipeIn
.MakeNonBlocking(wxPipe::Write
) )
787 // This message is not terrible useful for the user but what
788 // else can we do? Also, should we fail here or take the risk
789 // to continue and deadlock? Currently we choose the latter but
790 // it might not be the best idea.
791 wxLogSysError(_("Failed to set up non-blocking pipe, "
792 "the program might hang."));
794 wxLog::FlushActive();
798 wxOutputStream
*inStream
=
799 new wxPipeOutputStream(pipeIn
.Detach(wxPipe::Write
));
801 const int fdOut
= pipeOut
.Detach(wxPipe::Read
);
802 wxPipeInputStream
*outStream
= new wxPipeInputStream(fdOut
);
804 const int fdErr
= pipeErr
.Detach(wxPipe::Read
);
805 wxPipeInputStream
*errStream
= new wxPipeInputStream(fdErr
);
807 process
->SetPipeStreams(outStream
, inStream
, errStream
);
809 if ( flags
& wxEXEC_SYNC
)
811 execData
.bufOut
.Init(outStream
);
812 execData
.bufErr
.Init(errStream
);
814 execData
.fdOut
= fdOut
;
815 execData
.fdErr
= fdErr
;
818 #endif // HAS_PIPE_STREAMS
827 // For the asynchronous case we don't have to do anything else, just
828 // let the process run.
829 if ( !(flags
& wxEXEC_SYNC
) )
831 // Ensure that the housekeeping data is kept alive, it will be
832 // destroyed only when the child terminates.
833 execDataPtr
.release();
839 // If we don't need to dispatch any events, things are relatively
840 // simple and we don't need to delegate to wxAppTraits.
841 if ( flags
& wxEXEC_NOEVENTS
)
843 return BlockUntilChildExit(execData
);
847 // If we do need to dispatch events, enter a local event loop waiting
848 // until the child exits. As the exact kind of event loop depends on
849 // the sort of application we're in (console or GUI), we delegate this
850 // to wxAppTraits which virtualizes all the differences between the
851 // console and the GUI programs.
852 return wxApp::GetValidTraits().WaitForChild(execData
);
855 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
856 return ERROR_RETURN_CODE
;
860 #undef ERROR_RETURN_CODE
862 // ----------------------------------------------------------------------------
863 // file and directory functions
864 // ----------------------------------------------------------------------------
866 const wxChar
* wxGetHomeDir( wxString
*home
)
868 *home
= wxGetUserHome();
874 if ( tmp
.Last() != wxT(']'))
875 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
877 return home
->c_str();
880 wxString
wxGetUserHome( const wxString
&user
)
882 struct passwd
*who
= (struct passwd
*) NULL
;
888 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
893 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
||
894 (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
896 who
= getpwnam(wxSafeConvertWX2MB(ptr
));
899 // make sure the user exists!
902 who
= getpwuid(getuid());
907 who
= getpwnam (user
.mb_str());
910 return wxSafeConvertMB2WX(who
? who
->pw_dir
: 0);
913 // ----------------------------------------------------------------------------
914 // network and user id routines
915 // ----------------------------------------------------------------------------
917 // private utility function which returns output of the given command, removing
918 // the trailing newline
919 static wxString
wxGetCommandOutput(const wxString
&cmd
)
921 // Suppress stderr from the shell to avoid outputting errors if the command
923 FILE *f
= popen((cmd
+ " 2>/dev/null").ToAscii(), "r");
926 // Notice that this doesn't happen simply if the command doesn't exist,
927 // but only in case of some really catastrophic failure inside popen()
928 // so we should really notify the user about this as this is not normal.
929 wxLogSysError(wxT("Executing \"%s\" failed"), cmd
);
937 if ( !fgets(buf
, sizeof(buf
), f
) )
940 s
+= wxString::FromAscii(buf
);
945 if ( !s
.empty() && s
.Last() == wxT('\n') )
951 // retrieve either the hostname or FQDN depending on platform (caller must
952 // check whether it's one or the other, this is why this function is for
954 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
956 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
960 // we're using uname() which is POSIX instead of less standard sysinfo()
961 #if defined(HAVE_UNAME)
963 bool ok
= uname(&uts
) != -1;
966 wxStrlcpy(buf
, wxSafeConvertMB2WX(uts
.nodename
), sz
);
968 #elif defined(HAVE_GETHOSTNAME)
970 bool ok
= gethostname(cbuf
, sz
) != -1;
973 wxStrlcpy(buf
, wxSafeConvertMB2WX(cbuf
), sz
);
975 #else // no uname, no gethostname
976 wxFAIL_MSG(wxT("don't know host name for this machine"));
979 #endif // uname/gethostname
983 wxLogSysError(_("Cannot get the hostname"));
989 bool wxGetHostName(wxChar
*buf
, int sz
)
991 bool ok
= wxGetHostNameInternal(buf
, sz
);
995 // BSD systems return the FQDN, we only want the hostname, so extract
996 // it (we consider that dots are domain separators)
997 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
1008 bool wxGetFullHostName(wxChar
*buf
, int sz
)
1010 bool ok
= wxGetHostNameInternal(buf
, sz
);
1014 if ( !wxStrchr(buf
, wxT('.')) )
1016 struct hostent
*host
= gethostbyname(wxSafeConvertWX2MB(buf
));
1019 wxLogSysError(_("Cannot get the official hostname"));
1025 // the canonical name
1026 wxStrlcpy(buf
, wxSafeConvertMB2WX(host
->h_name
), sz
);
1029 //else: it's already a FQDN (BSD behaves this way)
1035 bool wxGetUserId(wxChar
*buf
, int sz
)
1040 if ((who
= getpwuid(getuid ())) != NULL
)
1042 wxStrlcpy (buf
, wxSafeConvertMB2WX(who
->pw_name
), sz
);
1049 bool wxGetUserName(wxChar
*buf
, int sz
)
1051 #ifdef HAVE_PW_GECOS
1055 if ((who
= getpwuid (getuid ())) != NULL
)
1057 char *comma
= strchr(who
->pw_gecos
, ',');
1059 *comma
= '\0'; // cut off non-name comment fields
1060 wxStrlcpy(buf
, wxSafeConvertMB2WX(who
->pw_gecos
), sz
);
1065 #else // !HAVE_PW_GECOS
1066 return wxGetUserId(buf
, sz
);
1067 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
1070 bool wxIsPlatform64Bit()
1072 const wxString machine
= wxGetCommandOutput(wxT("uname -m"));
1074 // the test for "64" is obviously not 100% reliable but seems to work fine
1076 return machine
.Contains(wxT("64")) ||
1077 machine
.Contains(wxT("alpha"));
1081 wxLinuxDistributionInfo
wxGetLinuxDistributionInfo()
1083 const wxString id
= wxGetCommandOutput(wxT("lsb_release --id"));
1084 const wxString desc
= wxGetCommandOutput(wxT("lsb_release --description"));
1085 const wxString rel
= wxGetCommandOutput(wxT("lsb_release --release"));
1086 const wxString codename
= wxGetCommandOutput(wxT("lsb_release --codename"));
1088 wxLinuxDistributionInfo ret
;
1090 id
.StartsWith("Distributor ID:\t", &ret
.Id
);
1091 desc
.StartsWith("Description:\t", &ret
.Description
);
1092 rel
.StartsWith("Release:\t", &ret
.Release
);
1093 codename
.StartsWith("Codename:\t", &ret
.CodeName
);
1099 // these functions are in src/osx/utilsexc_base.cpp for wxMac
1102 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
1106 wxString release
= wxGetCommandOutput(wxT("uname -r"));
1107 if ( release
.empty() ||
1108 wxSscanf(release
.c_str(), wxT("%d.%d"), &major
, &minor
) != 2 )
1110 // failed to get version string or unrecognized format
1120 // try to understand which OS are we running
1121 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
1122 if ( kernel
.empty() )
1123 kernel
= wxGetCommandOutput(wxT("uname -o"));
1125 if ( kernel
.empty() )
1126 return wxOS_UNKNOWN
;
1128 return wxPlatformInfo::GetOperatingSystemId(kernel
);
1131 wxString
wxGetOsDescription()
1133 return wxGetCommandOutput(wxT("uname -s -r -m"));
1136 #endif // !__DARWIN__
1138 unsigned long wxGetProcessId()
1140 return (unsigned long)getpid();
1143 wxMemorySize
wxGetFreeMemory()
1145 #if defined(__LINUX__)
1146 // get it from /proc/meminfo
1147 FILE *fp
= fopen("/proc/meminfo", "r");
1153 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
1155 // /proc/meminfo changed its format in kernel 2.6
1156 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
1158 unsigned long cached
, buffers
;
1159 sscanf(buf
, "MemFree: %ld", &memFree
);
1161 fgets(buf
, WXSIZEOF(buf
), fp
);
1162 sscanf(buf
, "Buffers: %lu", &buffers
);
1164 fgets(buf
, WXSIZEOF(buf
), fp
);
1165 sscanf(buf
, "Cached: %lu", &cached
);
1167 // add to "MemFree" also the "Buffers" and "Cached" values as
1168 // free(1) does as otherwise the value never makes sense: for
1169 // kernel 2.6 it's always almost 0
1170 memFree
+= buffers
+ cached
;
1172 // values here are always expressed in kB and we want bytes
1175 else // Linux 2.4 (or < 2.6, anyhow)
1177 long memTotal
, memUsed
;
1178 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
1184 return (wxMemorySize
)memFree
;
1186 #elif defined(__SGI__)
1187 struct rminfo realmem
;
1188 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
1189 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
1190 #elif defined(_SC_AVPHYS_PAGES)
1191 return ((wxMemorySize
)sysconf(_SC_AVPHYS_PAGES
))*sysconf(_SC_PAGESIZE
);
1192 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1195 // can't find it out
1199 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
1201 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1202 // the case to "char *" is needed for AIX 4.3
1204 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
1206 wxLogSysError( wxT("Failed to get file system statistics") );
1211 // under Solaris we also have to use f_frsize field instead of f_bsize
1212 // which is in general a multiple of f_frsize
1214 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1215 #else // HAVE_STATFS
1216 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1217 #endif // HAVE_STATVFS/HAVE_STATFS
1221 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1226 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1230 #else // !HAVE_STATFS && !HAVE_STATVFS
1232 #endif // HAVE_STATFS
1235 // ----------------------------------------------------------------------------
1237 // ----------------------------------------------------------------------------
1241 WX_DECLARE_STRING_HASH_MAP(char *, wxEnvVars
);
1243 static wxEnvVars gs_envVars
;
1245 class wxSetEnvModule
: public wxModule
1248 virtual bool OnInit() { return true; }
1249 virtual void OnExit()
1251 for ( wxEnvVars::const_iterator i
= gs_envVars
.begin();
1252 i
!= gs_envVars
.end();
1261 DECLARE_DYNAMIC_CLASS(wxSetEnvModule
)
1264 IMPLEMENT_DYNAMIC_CLASS(wxSetEnvModule
, wxModule
)
1266 #endif // USE_PUTENV
1268 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1270 // wxGetenv is defined as getenv()
1271 char *p
= wxGetenv(var
);
1283 static bool wxDoSetEnv(const wxString
& variable
, const char *value
)
1285 #if defined(HAVE_SETENV)
1288 #ifdef HAVE_UNSETENV
1289 // don't test unsetenv() return value: it's void on some systems (at
1291 unsetenv(variable
.mb_str());
1294 value
= ""; // we can't pass NULL to setenv()
1298 return setenv(variable
.mb_str(), value
, 1 /* overwrite */) == 0;
1299 #elif defined(HAVE_PUTENV)
1300 wxString s
= variable
;
1302 s
<< wxT('=') << value
;
1304 // transform to ANSI
1305 const wxWX2MBbuf p
= s
.mb_str();
1307 char *buf
= (char *)malloc(strlen(p
) + 1);
1310 // store the string to free() it later
1311 wxEnvVars::iterator i
= gs_envVars
.find(variable
);
1312 if ( i
!= gs_envVars
.end() )
1317 else // this variable hadn't been set before
1319 gs_envVars
[variable
] = buf
;
1322 return putenv(buf
) == 0;
1323 #else // no way to set an env var
1328 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
1330 return wxDoSetEnv(variable
, value
.mb_str());
1333 bool wxUnsetEnv(const wxString
& variable
)
1335 return wxDoSetEnv(variable
, NULL
);
1338 // ----------------------------------------------------------------------------
1340 // ----------------------------------------------------------------------------
1342 #if wxUSE_ON_FATAL_EXCEPTION
1346 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1350 // give the user a chance to do something special about this
1351 wxTheApp
->OnFatalException();
1357 bool wxHandleFatalExceptions(bool doit
)
1360 static bool s_savedHandlers
= false;
1361 static struct sigaction s_handlerFPE
,
1367 if ( doit
&& !s_savedHandlers
)
1369 // install the signal handler
1370 struct sigaction act
;
1372 // some systems extend it with non std fields, so zero everything
1373 memset(&act
, 0, sizeof(act
));
1375 act
.sa_handler
= wxFatalSignalHandler
;
1376 sigemptyset(&act
.sa_mask
);
1379 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1380 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1381 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1382 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1385 wxLogDebug(wxT("Failed to install our signal handler."));
1388 s_savedHandlers
= true;
1390 else if ( s_savedHandlers
)
1392 // uninstall the signal handler
1393 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1394 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1395 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1396 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1399 wxLogDebug(wxT("Failed to uninstall our signal handler."));
1402 s_savedHandlers
= false;
1404 //else: nothing to do
1409 #endif // wxUSE_ON_FATAL_EXCEPTION
1411 // ----------------------------------------------------------------------------
1412 // wxExecute support
1413 // ----------------------------------------------------------------------------
1415 int wxAppTraits::WaitForChild(wxExecuteData
& execData
)
1417 #if wxUSE_CONSOLE_EVENTLOOP
1418 wxConsoleEventLoop loop
;
1419 return RunLoopUntilChildExit(execData
, loop
);
1420 #else // !wxUSE_CONSOLE_EVENTLOOP
1421 wxFAIL_MSG( wxS("Can't wait for child process without wxConsoleEventLoop") );
1424 #endif // wxUSE_CONSOLE_EVENTLOOP/!wxUSE_CONSOLE_EVENTLOOP
1427 // This function is common code for both console and GUI applications and used
1428 // by wxExecute() to wait for the child exit while dispatching events.
1430 // Notice that it should not be used for all the other cases, e.g. when we
1431 // don't need to wait for the child (wxEXEC_ASYNC) or when the events must not
1432 // dispatched (wxEXEC_NOEVENTS).
1434 wxAppTraits::RunLoopUntilChildExit(wxExecuteData
& execData
,
1435 wxEventLoopBase
& loop
)
1437 // It is possible that wxExecuteData::OnExit() had already been called
1438 // and reset the PID to 0, in which case we don't need to do anything
1440 if ( !execData
.pid
)
1441 return execData
.exitcode
;
1444 // Monitor the child streams if necessary.
1445 wxScopedPtr
<wxEventLoopSourceHandler
>
1448 if ( execData
.IsRedirected() )
1450 stdoutHandler
.reset(new wxExecuteEventLoopSourceHandler
1452 execData
.fdOut
, execData
.bufOut
1454 stderrHandler
.reset(new wxExecuteEventLoopSourceHandler
1456 execData
.fdErr
, execData
.bufErr
1459 #endif // wxUSE_STREAMS
1461 // Store the event loop in the data associated with the child
1462 // process so that it could exit the loop when the child exits.
1463 execData
.syncEventLoop
= &loop
;
1468 // The exit code will have been set when the child termination was detected.
1469 return execData
.exitcode
;
1472 // ----------------------------------------------------------------------------
1474 // ----------------------------------------------------------------------------
1479 // Helper function that checks whether the child with the given PID has exited
1480 // and fills the provided parameter with its return code if it did.
1481 bool CheckForChildExit(int pid
, int* exitcodeOut
)
1483 wxASSERT_MSG( pid
> 0, "invalid PID" );
1487 // loop while we're getting EINTR
1490 rc
= waitpid(pid
, &status
, WNOHANG
);
1492 if ( rc
!= -1 || errno
!= EINTR
)
1499 // No error but the child is still running.
1503 // Checking child status failed. Invalid PID?
1504 wxLogLastError(wxString::Format("waitpid(%d)", pid
));
1508 // Child did terminate.
1509 wxASSERT_MSG( rc
== pid
, "unexpected waitpid() return value" );
1511 // notice that the caller expects the exit code to be signed, e.g. -1
1512 // instead of 255 so don't assign WEXITSTATUS() to an int
1513 signed char exitcode
;
1514 if ( WIFEXITED(status
) )
1515 exitcode
= WEXITSTATUS(status
);
1516 else if ( WIFSIGNALED(status
) )
1517 exitcode
= -WTERMSIG(status
);
1520 wxLogError("Child process (PID %d) exited for unknown reason, "
1521 "status = %d", pid
, status
);
1526 *exitcodeOut
= exitcode
;
1532 } // anonymous namespace
1534 wxExecuteData::ChildProcessesData
wxExecuteData::ms_childProcesses
;
1537 void wxExecuteData::OnSomeChildExited(int WXUNUSED(sig
))
1539 // We know that some child process has terminated, but we don't know which
1540 // one, so check all of them (notice that more than one could have exited).
1542 // An alternative approach would be to call waitpid(-1, &status, WNOHANG)
1543 // (in a loop to take care of the multiple children exiting case) and
1544 // perhaps this would be more efficient. But for now this seems to work.
1547 // Make a copy of the list before iterating over it to avoid problems due
1548 // to deleting entries from it in the process.
1549 const ChildProcessesData allChildProcesses
= ms_childProcesses
;
1550 for ( ChildProcessesData::const_iterator it
= allChildProcesses
.begin();
1551 it
!= allChildProcesses
.end();
1554 const int pid
= it
->first
;
1556 // Check whether this child exited.
1558 if ( !CheckForChildExit(pid
, &exitcode
) )
1561 // And handle its termination if it did.
1563 // Notice that this will implicitly remove it from ms_childProcesses.
1564 it
->second
->OnExit(exitcode
);
1568 void wxExecuteData::OnStart(int pid_
)
1570 wxCHECK_RET( wxTheApp
,
1571 wxS("Ensure wxTheApp is set before calling wxExecute()") );
1573 // Setup the signal handler for SIGCHLD to be able to detect the child
1576 // Notice that SetSignalHandler() is idempotent, so it's fine to call
1577 // it more than once with the same handler.
1578 wxTheApp
->SetSignalHandler(SIGCHLD
, OnSomeChildExited
);
1581 // Remember the child PID to be able to wait for it later.
1584 // Also save it in wxProcess where it will be accessible to the user code.
1586 process
->SetPid(pid
);
1588 // Finally, add this object itself to the list of child processes so that
1589 // we can check for its termination the next time we get SIGCHLD.
1590 ms_childProcesses
[pid
] = this;
1593 void wxExecuteData::OnExit(int exitcode_
)
1595 // Remove this process from the hash list of child processes that are
1596 // still open as soon as possible to ensure we don't process it again even
1597 // if another SIGCHLD happens.
1598 if ( !ms_childProcesses
.erase(pid
) )
1600 wxFAIL_MSG(wxString::Format(wxS("Data for PID %d not in the list?"), pid
));
1604 exitcode
= exitcode_
;
1607 if ( IsRedirected() )
1609 // Read the remaining data in a blocking way: this is fine because the
1610 // child has already exited and hence all the data must be already
1611 // available in the streams buffers.
1615 #endif // wxUSE_STREAMS
1617 // Notify user about termination if required
1618 if ( !(flags
& wxEXEC_SYNC
) )
1621 process
->OnTerminate(pid
, exitcode
);
1623 // in case of asynchronous execution we don't need this object any more
1624 // after the child terminates
1627 else // sync execution
1629 // let wxExecute() know that the process has terminated
1632 // Stop the event loop for synchronous wxExecute() if we're running one.
1633 if ( syncEventLoop
)
1634 syncEventLoop
->ScheduleExit();