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 <fcntl.h> // for O_WRONLY and friends
120 #include <time.h> // nanosleep() and/or usleep()
121 #include <ctype.h> // isspace()
122 #include <sys/time.h> // needed for FD_SETSIZE
125 #include <sys/utsname.h> // for uname()
128 // Used by wxGetFreeMemory().
130 #include <sys/sysmp.h>
131 #include <sys/sysinfo.h> // for SAGET and MINFO structures
134 #ifdef HAVE_SETPRIORITY
135 #include <sys/resource.h> // for setpriority()
138 // ----------------------------------------------------------------------------
139 // conditional compilation
140 // ----------------------------------------------------------------------------
142 // many versions of Unices have this function, but it is not defined in system
143 // headers - please add your system here if it is the case for your OS.
144 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
145 #if !defined(HAVE_USLEEP) && \
146 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
147 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
148 defined(__osf__) || defined(__EMX__))
152 /* I copied this from the XFree86 diffs. AV. */
153 #define INCL_DOSPROCESS
155 inline void usleep(unsigned long delay
)
157 DosSleep(delay
? (delay
/1000l) : 1l);
160 int usleep(unsigned int usec
);
161 #endif // __EMX__/Unix
164 #define HAVE_USLEEP 1
165 #endif // Unices without usleep()
167 // ============================================================================
169 // ============================================================================
171 // ----------------------------------------------------------------------------
173 // ----------------------------------------------------------------------------
175 void wxSleep(int nSecs
)
180 void wxMicroSleep(unsigned long microseconds
)
182 #if defined(HAVE_NANOSLEEP)
184 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
185 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
187 // we're not interested in remaining time nor in return value
188 (void)nanosleep(&tmReq
, NULL
);
189 #elif defined(HAVE_USLEEP)
190 // uncomment this if you feel brave or if you are sure that your version
191 // of Solaris has a safe usleep() function but please notice that usleep()
192 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
193 // documented as MT-Safe
194 #if defined(__SUN__) && wxUSE_THREADS
195 #error "usleep() cannot be used in MT programs under Solaris."
198 usleep(microseconds
);
199 #elif defined(HAVE_SLEEP)
200 // under BeOS sleep() takes seconds (what about other platforms, if any?)
201 sleep(microseconds
* 1000000);
202 #else // !sleep function
203 #error "usleep() or nanosleep() function required for wxMicroSleep"
204 #endif // sleep function
207 void wxMilliSleep(unsigned long milliseconds
)
209 wxMicroSleep(milliseconds
*1000);
212 // ----------------------------------------------------------------------------
213 // process management
214 // ----------------------------------------------------------------------------
216 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
218 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
221 switch ( err
? errno
: 0 )
228 *rc
= wxKILL_BAD_SIGNAL
;
232 *rc
= wxKILL_ACCESS_DENIED
;
236 *rc
= wxKILL_NO_PROCESS
;
240 // this goes against Unix98 docs so log it
241 wxLogDebug(wxT("unexpected kill(2) return value %d"), err
);
251 // Shutdown or reboot the PC
252 bool wxShutdown(int flags
)
254 flags
&= ~wxSHUTDOWN_FORCE
;
259 case wxSHUTDOWN_POWEROFF
:
263 case wxSHUTDOWN_REBOOT
:
267 case wxSHUTDOWN_LOGOFF
:
268 // TODO: use dcop to log off?
272 wxFAIL_MSG( wxT("unknown wxShutdown() flag") );
276 return system(wxString::Format("init %c", level
).mb_str()) == 0;
279 // ----------------------------------------------------------------------------
280 // wxStream classes to support IO redirection in wxExecute
281 // ----------------------------------------------------------------------------
285 bool wxPipeInputStream::CanRead() const
287 if ( m_lasterror
== wxSTREAM_EOF
)
290 // check if there is any input available
295 const int fd
= m_file
->fd();
300 wxFD_SET(fd
, &readfds
);
302 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
305 wxLogSysError(_("Impossible to get child process input"));
312 wxFAIL_MSG(wxT("unexpected select() return value"));
313 // still fall through
316 // input available -- or maybe not, as select() returns 1 when a
317 // read() will complete without delay, but it could still not read
323 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t size
)
325 // We need to suppress error logging here, because on writing to a pipe
326 // which is full, wxFile::Write reports a system error. However, this is
327 // not an extraordinary situation, and it should not be reported to the
328 // user (but if really needed, the program can recognize it by checking
329 // whether LastRead() == 0.) Other errors will be reported below.
333 ret
= m_file
->Write(buffer
, size
);
336 switch ( m_file
->GetLastError() )
342 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
345 // do not treat it as an error
346 m_file
->ClearLastError();
355 wxLogSysError(_("Can't write to child process's stdin"));
356 m_lasterror
= wxSTREAM_WRITE_ERROR
;
362 #endif // HAS_PIPE_STREAMS
364 // ----------------------------------------------------------------------------
366 // ----------------------------------------------------------------------------
368 static wxString
wxMakeShellCommand(const wxString
& command
)
373 // just an interactive shell
378 // execute command in a shell
379 cmd
<< wxT("/bin/sh -c '") << command
<< wxT('\'');
385 bool wxShell(const wxString
& command
)
387 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
390 bool wxShell(const wxString
& command
, wxArrayString
& output
)
392 wxCHECK_MSG( !command
.empty(), false, wxT("can't exec shell non interactively") );
394 return wxExecute(wxMakeShellCommand(command
), output
);
400 // helper class for storing arguments as char** array suitable for passing to
401 // execvp(), whatever form they were passed to us
405 ArgsArray(const wxArrayString
& args
)
409 for ( int i
= 0; i
< m_argc
; i
++ )
411 m_argv
[i
] = wxStrdup(args
[i
]);
416 ArgsArray(wchar_t **wargv
)
419 while ( wargv
[argc
] )
424 for ( int i
= 0; i
< m_argc
; i
++ )
426 m_argv
[i
] = wxSafeConvertWX2MB(wargv
[i
]).release();
429 #endif // wxUSE_UNICODE
433 for ( int i
= 0; i
< m_argc
; i
++ )
441 operator char**() const { return m_argv
; }
447 m_argv
= new char *[m_argc
+ 1];
448 m_argv
[m_argc
] = NULL
;
454 wxDECLARE_NO_COPY_CLASS(ArgsArray
);
457 } // anonymous namespace
459 // ----------------------------------------------------------------------------
460 // wxExecute implementations
461 // ----------------------------------------------------------------------------
463 #if defined(__DARWIN__)
464 bool wxMacLaunch(char **argv
);
467 long wxExecute(const wxString
& command
, int flags
, wxProcess
*process
,
468 const wxExecuteEnv
*env
)
470 ArgsArray
argv(wxCmdLineParser::ConvertStringToArgs(command
,
471 wxCMD_LINE_SPLIT_UNIX
));
473 return wxExecute(argv
, flags
, process
, env
);
478 long wxExecute(wchar_t **wargv
, int flags
, wxProcess
*process
,
479 const wxExecuteEnv
*env
)
481 ArgsArray
argv(wargv
);
483 return wxExecute(argv
, flags
, process
, env
);
486 #endif // wxUSE_UNICODE
488 // wxExecute: the real worker function
489 long wxExecute(char **argv
, int flags
, wxProcess
*process
,
490 const wxExecuteEnv
*env
)
492 // for the sync execution, we return -1 to indicate failure, but for async
493 // case we return 0 which is never a valid PID
495 // we define this as a macro, not a variable, to avoid compiler warnings
496 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
497 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
499 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
502 // fork() doesn't mix well with POSIX threads: on many systems the program
503 // deadlocks or crashes for some reason. Probably our code is buggy and
504 // doesn't do something which must be done to allow this to work, but I
505 // don't know what yet, so for now just warn the user (this is the least we
507 wxASSERT_MSG( wxThread::IsMain(),
508 wxT("wxExecute() can be called only from the main thread") );
509 #endif // wxUSE_THREADS
511 #if defined(__WXCOCOA__) || ( defined(__WXOSX_MAC__) && wxOSX_USE_COCOA_OR_CARBON )
512 // wxMacLaunch() only executes app bundles and only does it asynchronously.
513 // It returns false if the target is not an app bundle, thus falling
514 // through to the regular code for non app bundles.
515 if ( !(flags
& wxEXEC_SYNC
) && wxMacLaunch(argv
) )
517 // we don't have any PID to return so just make up something non null
523 // this struct contains all information which we use for housekeeping
524 wxExecuteData execData
;
525 execData
.flags
= flags
;
526 execData
.process
= process
;
529 if ( !execData
.pipeEndProcDetect
.Create() )
531 wxLogError( _("Failed to execute '%s'\n"), *argv
);
533 return ERROR_RETURN_CODE
;
536 // pipes for inter process communication
537 wxPipe pipeIn
, // stdin
541 if ( process
&& process
->IsRedirected() )
543 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
545 wxLogError( _("Failed to execute '%s'\n"), *argv
);
547 return ERROR_RETURN_CODE
;
551 // priority: we need to map wxWidgets priority which is in the range 0..100
552 // to Unix nice value which is in the range -20..19. As there is an odd
553 // number of elements in our range and an even number in the Unix one, we
554 // have to do it in this rather ugly way to guarantee that:
555 // 1. wxPRIORITY_{MIN,DEFAULT,MAX} map to -20, 0 and 19 respectively.
556 // 2. The mapping is monotonously increasing.
557 // 3. The mapping is onto the target range.
558 int prio
= process
? process
->GetPriority() : 0;
560 prio
= (2*prio
)/5 - 20;
561 else if ( prio
< 55 )
564 prio
= (2*prio
)/5 - 21;
568 // NB: do *not* use vfork() here, it completely breaks this code for some
569 // reason under Solaris (and maybe others, although not under Linux)
570 // But on OpenVMS we do not have fork so we have to use vfork and
571 // cross our fingers that it works.
577 if ( pid
== -1 ) // error?
579 wxLogSysError( _("Fork failed") );
581 return ERROR_RETURN_CODE
;
583 else if ( pid
== 0 ) // we're in child
585 // NB: we used to close all the unused descriptors of the child here
586 // but this broke some programs which relied on e.g. FD 1 being
587 // always opened so don't do it any more, after all there doesn't
588 // seem to be any real problem with keeping them opened
590 #if !defined(__VMS) && !defined(__EMX__)
591 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
593 // Set process group to child process' pid. Then killing -pid
594 // of the parent will kill the process and all of its children.
599 #if defined(HAVE_SETPRIORITY)
600 if ( prio
&& setpriority(PRIO_PROCESS
, 0, prio
) != 0 )
602 wxLogSysError(_("Failed to set process priority"));
604 #endif // HAVE_SETPRIORITY
606 // redirect stdin, stdout and stderr
609 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
610 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
611 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
613 wxLogSysError(_("Failed to redirect child process input/output"));
621 // Close all (presumably accidentally) inherited file descriptors to
622 // avoid descriptor leaks. This means that we don't allow inheriting
623 // them purposefully but this seems like a lesser evil in wx code.
624 // Ideally we'd provide some flag to indicate that none (or some?) of
625 // the descriptors do not need to be closed but for now this is better
626 // than never closing them at all as wx code never used FD_CLOEXEC.
628 // Note that while the reading side of the end process detection pipe
629 // can be safely closed, we should keep the write one opened, it will
630 // be only closed when the process terminates resulting in a read
631 // notification to the parent
632 const int fdEndProc
= execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
633 execData
.pipeEndProcDetect
.Close();
635 // TODO: Iterating up to FD_SETSIZE is both inefficient (because it may
636 // be quite big) and incorrect (because in principle we could
637 // have more opened descriptions than this number). Unfortunately
638 // there is no good portable solution for closing all descriptors
639 // above a certain threshold but non-portable solutions exist for
640 // most platforms, see [http://stackoverflow.com/questions/899038/
641 // getting-the-highest-allocated-file-descriptor]
642 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; ++fd
)
644 if ( fd
!= STDIN_FILENO
&&
645 fd
!= STDOUT_FILENO
&&
646 fd
!= STDERR_FILENO
&&
654 // Process additional options if we have any
657 // Change working directory if it is specified
658 if ( !env
->cwd
.empty() )
659 wxSetWorkingDirectory(env
->cwd
);
661 // Change environment if needed.
663 // NB: We can't use execve() currently because we allow using
664 // non full paths to wxExecute(), i.e. we want to search for
665 // the program in PATH. However it just might be simpler/better
666 // to do the search manually and use execve() envp parameter to
667 // set up the environment of the child process explicitly
668 // instead of doing what we do below.
669 if ( !env
->env
.empty() )
671 wxEnvVariableHashMap oldenv
;
672 wxGetEnvMap(&oldenv
);
674 // Remove unwanted variables
675 wxEnvVariableHashMap::const_iterator it
;
676 for ( it
= oldenv
.begin(); it
!= oldenv
.end(); ++it
)
678 if ( env
->env
.find(it
->first
) == env
->env
.end() )
679 wxUnsetEnv(it
->first
);
682 // And add the new ones (possibly replacing the old values)
683 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
684 wxSetEnv(it
->first
, it
->second
);
690 fprintf(stderr
, "execvp(");
691 for ( char **a
= argv
; *a
; a
++ )
692 fprintf(stderr
, "%s%s", a
== argv
? "" : ", ", *a
);
693 fprintf(stderr
, ") failed with error %d!\n", errno
);
695 // there is no return after successful exec()
698 // some compilers complain about missing return - of course, they
699 // should know that exit() doesn't return but what else can we do if
702 // and, sure enough, other compilers complain about unreachable code
703 // after exit() call, so we can just always have return here...
704 #if defined(__VMS) || defined(__INTEL_COMPILER)
708 else // we're in parent
710 // save it for WaitForChild() use
712 if (execData
.process
)
713 execData
.process
->SetPid(pid
); // and also in the wxProcess
715 // prepare for IO redirection
718 // the input buffer bufOut is connected to stdout, this is why it is
719 // called bufOut and not bufIn
720 wxStreamTempInputBuffer bufOut
,
723 if ( process
&& process
->IsRedirected() )
725 // Avoid deadlocks which could result from trying to write to the
726 // child input pipe end while the child itself is writing to its
727 // output end and waiting for us to read from it.
728 if ( !pipeIn
.MakeNonBlocking(wxPipe::Write
) )
730 // This message is not terrible useful for the user but what
731 // else can we do? Also, should we fail here or take the risk
732 // to continue and deadlock? Currently we choose the latter but
733 // it might not be the best idea.
734 wxLogSysError(_("Failed to set up non-blocking pipe, "
735 "the program might hang."));
737 wxLog::FlushActive();
741 wxOutputStream
*inStream
=
742 new wxPipeOutputStream(pipeIn
.Detach(wxPipe::Write
));
744 const int fdOut
= pipeOut
.Detach(wxPipe::Read
);
745 wxPipeInputStream
*outStream
= new wxPipeInputStream(fdOut
);
747 const int fdErr
= pipeErr
.Detach(wxPipe::Read
);
748 wxPipeInputStream
*errStream
= new wxPipeInputStream(fdErr
);
750 process
->SetPipeStreams(outStream
, inStream
, errStream
);
752 bufOut
.Init(outStream
);
753 bufErr
.Init(errStream
);
755 execData
.bufOut
= &bufOut
;
756 execData
.bufErr
= &bufErr
;
758 execData
.fdOut
= fdOut
;
759 execData
.fdErr
= fdErr
;
761 #endif // HAS_PIPE_STREAMS
770 // we want this function to work even if there is no wxApp so ensure
771 // that we have a valid traits pointer
772 wxConsoleAppTraits traitsConsole
;
773 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
775 traits
= &traitsConsole
;
777 return traits
->WaitForChild(execData
);
780 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
781 return ERROR_RETURN_CODE
;
785 #undef ERROR_RETURN_CODE
787 // ----------------------------------------------------------------------------
788 // file and directory functions
789 // ----------------------------------------------------------------------------
791 const wxChar
* wxGetHomeDir( wxString
*home
)
793 *home
= wxGetUserHome();
799 if ( tmp
.Last() != wxT(']'))
800 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
802 return home
->c_str();
805 wxString
wxGetUserHome( const wxString
&user
)
807 struct passwd
*who
= (struct passwd
*) NULL
;
813 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
818 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
||
819 (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
821 who
= getpwnam(wxSafeConvertWX2MB(ptr
));
824 // make sure the user exists!
827 who
= getpwuid(getuid());
832 who
= getpwnam (user
.mb_str());
835 return wxSafeConvertMB2WX(who
? who
->pw_dir
: 0);
838 // ----------------------------------------------------------------------------
839 // network and user id routines
840 // ----------------------------------------------------------------------------
842 // private utility function which returns output of the given command, removing
843 // the trailing newline
844 static wxString
wxGetCommandOutput(const wxString
&cmd
)
846 // Suppress stderr from the shell to avoid outputting errors if the command
848 FILE *f
= popen((cmd
+ " 2>/dev/null").ToAscii(), "r");
851 // Notice that this doesn't happen simply if the command doesn't exist,
852 // but only in case of some really catastrophic failure inside popen()
853 // so we should really notify the user about this as this is not normal.
854 wxLogSysError(wxT("Executing \"%s\" failed"), cmd
);
862 if ( !fgets(buf
, sizeof(buf
), f
) )
865 s
+= wxString::FromAscii(buf
);
870 if ( !s
.empty() && s
.Last() == wxT('\n') )
876 // retrieve either the hostname or FQDN depending on platform (caller must
877 // check whether it's one or the other, this is why this function is for
879 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
881 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
885 // we're using uname() which is POSIX instead of less standard sysinfo()
886 #if defined(HAVE_UNAME)
888 bool ok
= uname(&uts
) != -1;
891 wxStrlcpy(buf
, wxSafeConvertMB2WX(uts
.nodename
), sz
);
893 #elif defined(HAVE_GETHOSTNAME)
895 bool ok
= gethostname(cbuf
, sz
) != -1;
898 wxStrlcpy(buf
, wxSafeConvertMB2WX(cbuf
), sz
);
900 #else // no uname, no gethostname
901 wxFAIL_MSG(wxT("don't know host name for this machine"));
904 #endif // uname/gethostname
908 wxLogSysError(_("Cannot get the hostname"));
914 bool wxGetHostName(wxChar
*buf
, int sz
)
916 bool ok
= wxGetHostNameInternal(buf
, sz
);
920 // BSD systems return the FQDN, we only want the hostname, so extract
921 // it (we consider that dots are domain separators)
922 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
933 bool wxGetFullHostName(wxChar
*buf
, int sz
)
935 bool ok
= wxGetHostNameInternal(buf
, sz
);
939 if ( !wxStrchr(buf
, wxT('.')) )
941 struct hostent
*host
= gethostbyname(wxSafeConvertWX2MB(buf
));
944 wxLogSysError(_("Cannot get the official hostname"));
950 // the canonical name
951 wxStrlcpy(buf
, wxSafeConvertMB2WX(host
->h_name
), sz
);
954 //else: it's already a FQDN (BSD behaves this way)
960 bool wxGetUserId(wxChar
*buf
, int sz
)
965 if ((who
= getpwuid(getuid ())) != NULL
)
967 wxStrlcpy (buf
, wxSafeConvertMB2WX(who
->pw_name
), sz
);
974 bool wxGetUserName(wxChar
*buf
, int sz
)
980 if ((who
= getpwuid (getuid ())) != NULL
)
982 char *comma
= strchr(who
->pw_gecos
, ',');
984 *comma
= '\0'; // cut off non-name comment fields
985 wxStrlcpy(buf
, wxSafeConvertMB2WX(who
->pw_gecos
), sz
);
990 #else // !HAVE_PW_GECOS
991 return wxGetUserId(buf
, sz
);
992 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
995 bool wxIsPlatform64Bit()
997 const wxString machine
= wxGetCommandOutput(wxT("uname -m"));
999 // the test for "64" is obviously not 100% reliable but seems to work fine
1001 return machine
.Contains(wxT("64")) ||
1002 machine
.Contains(wxT("alpha"));
1006 wxLinuxDistributionInfo
wxGetLinuxDistributionInfo()
1008 const wxString id
= wxGetCommandOutput(wxT("lsb_release --id"));
1009 const wxString desc
= wxGetCommandOutput(wxT("lsb_release --description"));
1010 const wxString rel
= wxGetCommandOutput(wxT("lsb_release --release"));
1011 const wxString codename
= wxGetCommandOutput(wxT("lsb_release --codename"));
1013 wxLinuxDistributionInfo ret
;
1015 id
.StartsWith("Distributor ID:\t", &ret
.Id
);
1016 desc
.StartsWith("Description:\t", &ret
.Description
);
1017 rel
.StartsWith("Release:\t", &ret
.Release
);
1018 codename
.StartsWith("Codename:\t", &ret
.CodeName
);
1024 // these functions are in src/osx/utilsexc_base.cpp for wxMac
1027 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
1031 wxString release
= wxGetCommandOutput(wxT("uname -r"));
1032 if ( release
.empty() ||
1033 wxSscanf(release
.c_str(), wxT("%d.%d"), &major
, &minor
) != 2 )
1035 // failed to get version string or unrecognized format
1045 // try to understand which OS are we running
1046 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
1047 if ( kernel
.empty() )
1048 kernel
= wxGetCommandOutput(wxT("uname -o"));
1050 if ( kernel
.empty() )
1051 return wxOS_UNKNOWN
;
1053 return wxPlatformInfo::GetOperatingSystemId(kernel
);
1056 wxString
wxGetOsDescription()
1058 return wxGetCommandOutput(wxT("uname -s -r -m"));
1061 #endif // !__DARWIN__
1063 unsigned long wxGetProcessId()
1065 return (unsigned long)getpid();
1068 wxMemorySize
wxGetFreeMemory()
1070 #if defined(__LINUX__)
1071 // get it from /proc/meminfo
1072 FILE *fp
= fopen("/proc/meminfo", "r");
1078 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
1080 // /proc/meminfo changed its format in kernel 2.6
1081 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
1083 unsigned long cached
, buffers
;
1084 sscanf(buf
, "MemFree: %ld", &memFree
);
1086 fgets(buf
, WXSIZEOF(buf
), fp
);
1087 sscanf(buf
, "Buffers: %lu", &buffers
);
1089 fgets(buf
, WXSIZEOF(buf
), fp
);
1090 sscanf(buf
, "Cached: %lu", &cached
);
1092 // add to "MemFree" also the "Buffers" and "Cached" values as
1093 // free(1) does as otherwise the value never makes sense: for
1094 // kernel 2.6 it's always almost 0
1095 memFree
+= buffers
+ cached
;
1097 // values here are always expressed in kB and we want bytes
1100 else // Linux 2.4 (or < 2.6, anyhow)
1102 long memTotal
, memUsed
;
1103 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
1109 return (wxMemorySize
)memFree
;
1111 #elif defined(__SGI__)
1112 struct rminfo realmem
;
1113 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
1114 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
1115 #elif defined(_SC_AVPHYS_PAGES)
1116 return ((wxMemorySize
)sysconf(_SC_AVPHYS_PAGES
))*sysconf(_SC_PAGESIZE
);
1117 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1120 // can't find it out
1124 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
1126 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1127 // the case to "char *" is needed for AIX 4.3
1129 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
1131 wxLogSysError( wxT("Failed to get file system statistics") );
1136 // under Solaris we also have to use f_frsize field instead of f_bsize
1137 // which is in general a multiple of f_frsize
1139 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1140 #else // HAVE_STATFS
1141 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1142 #endif // HAVE_STATVFS/HAVE_STATFS
1146 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1151 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1155 #else // !HAVE_STATFS && !HAVE_STATVFS
1157 #endif // HAVE_STATFS
1160 // ----------------------------------------------------------------------------
1162 // ----------------------------------------------------------------------------
1166 WX_DECLARE_STRING_HASH_MAP(char *, wxEnvVars
);
1168 static wxEnvVars gs_envVars
;
1170 class wxSetEnvModule
: public wxModule
1173 virtual bool OnInit() { return true; }
1174 virtual void OnExit()
1176 for ( wxEnvVars::const_iterator i
= gs_envVars
.begin();
1177 i
!= gs_envVars
.end();
1186 DECLARE_DYNAMIC_CLASS(wxSetEnvModule
)
1189 IMPLEMENT_DYNAMIC_CLASS(wxSetEnvModule
, wxModule
)
1191 #endif // USE_PUTENV
1193 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1195 // wxGetenv is defined as getenv()
1196 char *p
= wxGetenv(var
);
1208 static bool wxDoSetEnv(const wxString
& variable
, const char *value
)
1210 #if defined(HAVE_SETENV)
1213 #ifdef HAVE_UNSETENV
1214 // don't test unsetenv() return value: it's void on some systems (at
1216 unsetenv(variable
.mb_str());
1219 value
= ""; // we can't pass NULL to setenv()
1223 return setenv(variable
.mb_str(), value
, 1 /* overwrite */) == 0;
1224 #elif defined(HAVE_PUTENV)
1225 wxString s
= variable
;
1227 s
<< wxT('=') << value
;
1229 // transform to ANSI
1230 const wxWX2MBbuf p
= s
.mb_str();
1232 char *buf
= (char *)malloc(strlen(p
) + 1);
1235 // store the string to free() it later
1236 wxEnvVars::iterator i
= gs_envVars
.find(variable
);
1237 if ( i
!= gs_envVars
.end() )
1242 else // this variable hadn't been set before
1244 gs_envVars
[variable
] = buf
;
1247 return putenv(buf
) == 0;
1248 #else // no way to set an env var
1253 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
1255 return wxDoSetEnv(variable
, value
.mb_str());
1258 bool wxUnsetEnv(const wxString
& variable
)
1260 return wxDoSetEnv(variable
, NULL
);
1263 // ----------------------------------------------------------------------------
1265 // ----------------------------------------------------------------------------
1267 #if wxUSE_ON_FATAL_EXCEPTION
1271 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1275 // give the user a chance to do something special about this
1276 wxTheApp
->OnFatalException();
1282 bool wxHandleFatalExceptions(bool doit
)
1285 static bool s_savedHandlers
= false;
1286 static struct sigaction s_handlerFPE
,
1292 if ( doit
&& !s_savedHandlers
)
1294 // install the signal handler
1295 struct sigaction act
;
1297 // some systems extend it with non std fields, so zero everything
1298 memset(&act
, 0, sizeof(act
));
1300 act
.sa_handler
= wxFatalSignalHandler
;
1301 sigemptyset(&act
.sa_mask
);
1304 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1305 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1306 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1307 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1310 wxLogDebug(wxT("Failed to install our signal handler."));
1313 s_savedHandlers
= true;
1315 else if ( s_savedHandlers
)
1317 // uninstall the signal handler
1318 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1319 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1320 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1321 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1324 wxLogDebug(wxT("Failed to uninstall our signal handler."));
1327 s_savedHandlers
= false;
1329 //else: nothing to do
1334 #endif // wxUSE_ON_FATAL_EXCEPTION
1336 // ----------------------------------------------------------------------------
1337 // wxExecute support
1338 // ----------------------------------------------------------------------------
1340 int wxAppTraits::AddProcessCallback(wxEndProcessData
*data
, int fd
)
1342 // define a custom handler processing only the closure of the descriptor
1343 struct wxEndProcessFDIOHandler
: public wxFDIOHandler
1345 wxEndProcessFDIOHandler(wxEndProcessData
*data
, int fd
)
1346 : m_data(data
), m_fd(fd
)
1350 virtual void OnReadWaiting()
1352 wxFDIODispatcher::Get()->UnregisterFD(m_fd
);
1355 wxHandleProcessTermination(m_data
);
1360 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1361 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1363 wxEndProcessData
* const m_data
;
1367 wxFDIODispatcher::Get()->RegisterFD
1370 new wxEndProcessFDIOHandler(data
, fd
),
1373 return fd
; // unused, but return something unique for the tag
1376 bool wxAppTraits::CheckForRedirectedIO(wxExecuteData
& execData
)
1378 #if HAS_PIPE_STREAMS
1381 if ( execData
.bufOut
&& execData
.bufOut
->Update() )
1384 if ( execData
.bufErr
&& execData
.bufErr
->Update() )
1388 #else // !HAS_PIPE_STREAMS
1389 wxUnusedVar(execData
);
1392 #endif // HAS_PIPE_STREAMS/!HAS_PIPE_STREAMS
1395 // helper classes/functions used by WaitForChild()
1399 // convenient base class for IO handlers which are registered for read
1400 // notifications only and which also stores the FD we're reading from
1402 // the derived classes still have to implement OnReadWaiting()
1403 class wxReadFDIOHandler
: public wxFDIOHandler
1406 wxReadFDIOHandler(wxFDIODispatcher
& disp
, int fd
) : m_fd(fd
)
1409 disp
.RegisterFD(fd
, this, wxFDIO_INPUT
);
1412 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1413 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1418 wxDECLARE_NO_COPY_CLASS(wxReadFDIOHandler
);
1421 // class for monitoring our end of the process detection pipe, simply sets a
1422 // flag when input on the pipe (which must be due to EOF) is detected
1423 class wxEndHandler
: public wxReadFDIOHandler
1426 wxEndHandler(wxFDIODispatcher
& disp
, int fd
)
1427 : wxReadFDIOHandler(disp
, fd
)
1429 m_terminated
= false;
1432 bool Terminated() const { return m_terminated
; }
1434 virtual void OnReadWaiting() { m_terminated
= true; }
1439 wxDECLARE_NO_COPY_CLASS(wxEndHandler
);
1442 #if HAS_PIPE_STREAMS
1444 // class for monitoring our ends of child stdout/err, should be constructed
1445 // with the FD and stream from wxExecuteData and will do nothing if they're
1448 // unlike wxEndHandler this class registers itself with the provided dispatcher
1449 class wxRedirectedIOHandler
: public wxReadFDIOHandler
1452 wxRedirectedIOHandler(wxFDIODispatcher
& disp
,
1454 wxStreamTempInputBuffer
*buf
)
1455 : wxReadFDIOHandler(disp
, fd
),
1460 virtual void OnReadWaiting()
1466 wxStreamTempInputBuffer
* const m_buf
;
1468 wxDECLARE_NO_COPY_CLASS(wxRedirectedIOHandler
);
1471 #endif // HAS_PIPE_STREAMS
1473 // helper function which calls waitpid() and analyzes the result
1474 int DoWaitForChild(int pid
, int flags
= 0)
1476 wxASSERT_MSG( pid
> 0, "invalid PID" );
1480 // loop while we're getting EINTR
1483 rc
= waitpid(pid
, &status
, flags
);
1485 if ( rc
!= -1 || errno
!= EINTR
)
1491 // This can only happen if the child application closes our dummy pipe
1492 // that is used to monitor its lifetime; in that case, our best bet is
1493 // to pretend the process did terminate, because otherwise wxExecute()
1494 // would hang indefinitely (OnReadWaiting() won't be called again, the
1495 // descriptor is closed now).
1496 wxLogDebug("Child process (PID %d) still alive but pipe closed so "
1497 "generating a close notification", pid
);
1499 else if ( rc
== -1 )
1501 wxLogLastError(wxString::Format("waitpid(%d)", pid
));
1503 else // child did terminate
1505 wxASSERT_MSG( rc
== pid
, "unexpected waitpid() return value" );
1507 // notice that the caller expects the exit code to be signed, e.g. -1
1508 // instead of 255 so don't assign WEXITSTATUS() to an int
1509 signed char exitcode
;
1510 if ( WIFEXITED(status
) )
1511 exitcode
= WEXITSTATUS(status
);
1512 else if ( WIFSIGNALED(status
) )
1513 exitcode
= -WTERMSIG(status
);
1516 wxLogError("Child process (PID %d) exited for unknown reason, "
1517 "status = %d", pid
, status
);
1527 } // anonymous namespace
1529 int wxAppTraits::WaitForChild(wxExecuteData
& execData
)
1531 if ( !(execData
.flags
& wxEXEC_SYNC
) )
1533 // asynchronous execution: just launch the process and return,
1534 // endProcData will be destroyed when it terminates (currently we leak
1535 // it if the process doesn't terminate before we do and this should be
1536 // fixed but it's not a real leak so it's not really very high
1538 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1539 endProcData
->process
= execData
.process
;
1540 endProcData
->pid
= execData
.pid
;
1541 endProcData
->tag
= AddProcessCallback
1544 execData
.GetEndProcReadFD()
1546 endProcData
->async
= true;
1548 return execData
.pid
;
1550 //else: synchronous execution case
1552 #if HAS_PIPE_STREAMS && wxUSE_SOCKETS
1553 wxProcess
* const process
= execData
.process
;
1554 if ( process
&& process
->IsRedirected() )
1556 // we can't simply block waiting for the child to terminate as we would
1557 // dead lock if it writes more than the pipe buffer size (typically
1558 // 4KB) bytes of output -- it would then block waiting for us to read
1559 // the data while we'd block waiting for it to terminate
1561 // so multiplex here waiting for any input from the child or closure of
1562 // the pipe used to indicate its termination
1563 wxSelectDispatcher disp
;
1565 wxEndHandler
endHandler(disp
, execData
.GetEndProcReadFD());
1567 wxRedirectedIOHandler
outHandler(disp
, execData
.fdOut
, execData
.bufOut
),
1568 errHandler(disp
, execData
.fdErr
, execData
.bufErr
);
1570 while ( !endHandler
.Terminated() )
1575 //else: no IO redirection, just block waiting for the child to exit
1576 #endif // HAS_PIPE_STREAMS
1578 return DoWaitForChild(execData
.pid
);
1581 void wxHandleProcessTermination(wxEndProcessData
*data
)
1583 data
->exitcode
= DoWaitForChild(data
->pid
, WNOHANG
);
1585 // notify user about termination if required
1586 if ( data
->process
)
1588 data
->process
->OnTerminate(data
->pid
, data
->exitcode
);
1593 // in case of asynchronous execution we don't need this data any more
1594 // after the child terminates
1597 else // sync execution
1599 // let wxExecute() know that the process has terminated