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 // define this to let wxexec.cpp know that we know what we're doing
67 #define _WX_USED_BY_WXEXECUTE_
68 #include "../common/execcmn.cpp"
70 #endif // HAS_PIPE_STREAMS
72 // not only the statfs syscall is called differently depending on platform, but
73 // one of its incarnations, statvfs(), takes different arguments under
74 // different platforms and even different versions of the same system (Solaris
75 // 7 and 8): if you want to test for this, don't forget that the problems only
76 // appear if the large files support is enabled
79 #include <sys/param.h>
80 #include <sys/mount.h>
83 #endif // __BSD__/!__BSD__
85 #define wxStatfs statfs
87 #ifndef HAVE_STATFS_DECL
88 // some systems lack statfs() prototype in the system headers (AIX 4)
89 extern "C" int statfs(const char *path
, struct statfs
*buf
);
94 #include <sys/statvfs.h>
96 #define wxStatfs statvfs
97 #endif // HAVE_STATVFS
99 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
100 // WX_STATFS_T is detected by configure
101 #define wxStatfs_t WX_STATFS_T
104 // SGI signal.h defines signal handler arguments differently depending on
105 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
106 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
107 #define _LANGUAGE_C_PLUS_PLUS 1
113 #include <sys/stat.h>
114 #include <sys/types.h>
115 #include <sys/wait.h>
120 #include <fcntl.h> // for O_WRONLY and friends
121 #include <time.h> // nanosleep() and/or usleep()
122 #include <ctype.h> // isspace()
123 #include <sys/time.h> // needed for FD_SETSIZE
126 #include <sys/utsname.h> // for uname()
129 // Used by wxGetFreeMemory().
131 #include <sys/sysmp.h>
132 #include <sys/sysinfo.h> // for SAGET and MINFO structures
135 #ifdef HAVE_SETPRIORITY
136 #include <sys/resource.h> // for setpriority()
139 // ----------------------------------------------------------------------------
140 // conditional compilation
141 // ----------------------------------------------------------------------------
143 // many versions of Unices have this function, but it is not defined in system
144 // headers - please add your system here if it is the case for your OS.
145 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
146 #if !defined(HAVE_USLEEP) && \
147 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
148 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
149 defined(__osf__) || defined(__EMX__))
153 /* I copied this from the XFree86 diffs. AV. */
154 #define INCL_DOSPROCESS
156 inline void usleep(unsigned long delay
)
158 DosSleep(delay
? (delay
/1000l) : 1l);
161 int usleep(unsigned int usec
);
162 #endif // __EMX__/Unix
165 #define HAVE_USLEEP 1
166 #endif // Unices without usleep()
168 // ============================================================================
170 // ============================================================================
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
176 void wxSleep(int nSecs
)
181 void wxMicroSleep(unsigned long microseconds
)
183 #if defined(HAVE_NANOSLEEP)
185 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
186 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
188 // we're not interested in remaining time nor in return value
189 (void)nanosleep(&tmReq
, NULL
);
190 #elif defined(HAVE_USLEEP)
191 // uncomment this if you feel brave or if you are sure that your version
192 // of Solaris has a safe usleep() function but please notice that usleep()
193 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
194 // documented as MT-Safe
195 #if defined(__SUN__) && wxUSE_THREADS
196 #error "usleep() cannot be used in MT programs under Solaris."
199 usleep(microseconds
);
200 #elif defined(HAVE_SLEEP)
201 // under BeOS sleep() takes seconds (what about other platforms, if any?)
202 sleep(microseconds
* 1000000);
203 #else // !sleep function
204 #error "usleep() or nanosleep() function required for wxMicroSleep"
205 #endif // sleep function
208 void wxMilliSleep(unsigned long milliseconds
)
210 wxMicroSleep(milliseconds
*1000);
213 // ----------------------------------------------------------------------------
214 // process management
215 // ----------------------------------------------------------------------------
217 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
219 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
222 switch ( err
? errno
: 0 )
229 *rc
= wxKILL_BAD_SIGNAL
;
233 *rc
= wxKILL_ACCESS_DENIED
;
237 *rc
= wxKILL_NO_PROCESS
;
241 // this goes against Unix98 docs so log it
242 wxLogDebug(wxT("unexpected kill(2) return value %d"), err
);
252 // Shutdown or reboot the PC
253 bool wxShutdown(int flags
)
255 flags
&= ~wxSHUTDOWN_FORCE
;
260 case wxSHUTDOWN_POWEROFF
:
264 case wxSHUTDOWN_REBOOT
:
268 case wxSHUTDOWN_LOGOFF
:
269 // TODO: use dcop to log off?
273 wxFAIL_MSG( wxT("unknown wxShutdown() flag") );
277 return system(wxString::Format("init %c", level
).mb_str()) == 0;
280 // ----------------------------------------------------------------------------
281 // wxStream classes to support IO redirection in wxExecute
282 // ----------------------------------------------------------------------------
286 bool wxPipeInputStream::CanRead() const
288 if ( m_lasterror
== wxSTREAM_EOF
)
291 // check if there is any input available
296 const int fd
= m_file
->fd();
301 wxFD_SET(fd
, &readfds
);
303 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
306 wxLogSysError(_("Impossible to get child process input"));
313 wxFAIL_MSG(wxT("unexpected select() return value"));
314 // still fall through
317 // input available -- or maybe not, as select() returns 1 when a
318 // read() will complete without delay, but it could still not read
324 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t size
)
326 // We need to suppress error logging here, because on writing to a pipe
327 // which is full, wxFile::Write reports a system error. However, this is
328 // not an extraordinary situation, and it should not be reported to the
329 // user (but if really needed, the program can recognize it by checking
330 // whether LastRead() == 0.) Other errors will be reported below.
334 ret
= m_file
->Write(buffer
, size
);
337 switch ( m_file
->GetLastError() )
343 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
346 // do not treat it as an error
347 m_file
->ClearLastError();
356 wxLogSysError(_("Can't write to child process's stdin"));
357 m_lasterror
= wxSTREAM_WRITE_ERROR
;
363 #endif // HAS_PIPE_STREAMS
365 // ----------------------------------------------------------------------------
367 // ----------------------------------------------------------------------------
369 static wxString
wxMakeShellCommand(const wxString
& command
)
374 // just an interactive shell
379 // execute command in a shell
380 cmd
<< wxT("/bin/sh -c '") << command
<< wxT('\'');
386 bool wxShell(const wxString
& command
)
388 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
391 bool wxShell(const wxString
& command
, wxArrayString
& output
)
393 wxCHECK_MSG( !command
.empty(), false, wxT("can't exec shell non interactively") );
395 return wxExecute(wxMakeShellCommand(command
), output
);
401 // helper class for storing arguments as char** array suitable for passing to
402 // execvp(), whatever form they were passed to us
406 ArgsArray(const wxArrayString
& args
)
410 for ( int i
= 0; i
< m_argc
; i
++ )
412 m_argv
[i
] = wxStrdup(args
[i
]);
417 ArgsArray(wchar_t **wargv
)
420 while ( wargv
[argc
] )
425 for ( int i
= 0; i
< m_argc
; i
++ )
427 m_argv
[i
] = wxSafeConvertWX2MB(wargv
[i
]).release();
430 #endif // wxUSE_UNICODE
434 for ( int i
= 0; i
< m_argc
; i
++ )
442 operator char**() const { return m_argv
; }
448 m_argv
= new char *[m_argc
+ 1];
449 m_argv
[m_argc
] = NULL
;
455 wxDECLARE_NO_COPY_CLASS(ArgsArray
);
458 } // anonymous namespace
460 // ----------------------------------------------------------------------------
461 // wxExecute implementations
462 // ----------------------------------------------------------------------------
464 #if defined(__DARWIN__)
465 bool wxMacLaunch(char **argv
);
468 long wxExecute(const wxString
& command
, int flags
, wxProcess
*process
,
469 const wxExecuteEnv
*env
)
471 ArgsArray
argv(wxCmdLineParser::ConvertStringToArgs(command
,
472 wxCMD_LINE_SPLIT_UNIX
));
474 return wxExecute(argv
, flags
, process
, env
);
479 long wxExecute(wchar_t **wargv
, int flags
, wxProcess
*process
,
480 const wxExecuteEnv
*env
)
482 ArgsArray
argv(wargv
);
484 return wxExecute(argv
, flags
, process
, env
);
487 #endif // wxUSE_UNICODE
489 // wxExecute: the real worker function
490 long wxExecute(char **argv
, int flags
, wxProcess
*process
,
491 const wxExecuteEnv
*env
)
493 // for the sync execution, we return -1 to indicate failure, but for async
494 // case we return 0 which is never a valid PID
496 // we define this as a macro, not a variable, to avoid compiler warnings
497 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
498 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
500 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
503 // fork() doesn't mix well with POSIX threads: on many systems the program
504 // deadlocks or crashes for some reason. Probably our code is buggy and
505 // doesn't do something which must be done to allow this to work, but I
506 // don't know what yet, so for now just warn the user (this is the least we
508 wxASSERT_MSG( wxThread::IsMain(),
509 wxT("wxExecute() can be called only from the main thread") );
510 #endif // wxUSE_THREADS
512 #if defined(__WXCOCOA__) || ( defined(__WXOSX_MAC__) && wxOSX_USE_COCOA_OR_CARBON )
513 // wxMacLaunch() only executes app bundles and only does it asynchronously.
514 // It returns false if the target is not an app bundle, thus falling
515 // through to the regular code for non app bundles.
516 if ( !(flags
& wxEXEC_SYNC
) && wxMacLaunch(argv
) )
518 // we don't have any PID to return so just make up something non null
524 // this struct contains all information which we use for housekeeping
525 wxExecuteData execData
;
526 execData
.flags
= flags
;
527 execData
.process
= process
;
530 if ( !execData
.pipeEndProcDetect
.Create() )
532 wxLogError( _("Failed to execute '%s'\n"), *argv
);
534 return ERROR_RETURN_CODE
;
537 // pipes for inter process communication
538 wxPipe pipeIn
, // stdin
542 if ( process
&& process
->IsRedirected() )
544 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
546 wxLogError( _("Failed to execute '%s'\n"), *argv
);
548 return ERROR_RETURN_CODE
;
552 // priority: we need to map wxWidgets priority which is in the range 0..100
553 // to Unix nice value which is in the range -20..19. As there is an odd
554 // number of elements in our range and an even number in the Unix one, we
555 // have to do it in this rather ugly way to guarantee that:
556 // 1. wxPRIORITY_{MIN,DEFAULT,MAX} map to -20, 0 and 19 respectively.
557 // 2. The mapping is monotonously increasing.
558 // 3. The mapping is onto the target range.
559 int prio
= process
? process
->GetPriority() : 0;
561 prio
= (2*prio
)/5 - 20;
562 else if ( prio
< 55 )
565 prio
= (2*prio
)/5 - 21;
569 // NB: do *not* use vfork() here, it completely breaks this code for some
570 // reason under Solaris (and maybe others, although not under Linux)
571 // But on OpenVMS we do not have fork so we have to use vfork and
572 // cross our fingers that it works.
578 if ( pid
== -1 ) // error?
580 wxLogSysError( _("Fork failed") );
582 return ERROR_RETURN_CODE
;
584 else if ( pid
== 0 ) // we're in child
586 // NB: we used to close all the unused descriptors of the child here
587 // but this broke some programs which relied on e.g. FD 1 being
588 // always opened so don't do it any more, after all there doesn't
589 // seem to be any real problem with keeping them opened
591 #if !defined(__VMS) && !defined(__EMX__)
592 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
594 // Set process group to child process' pid. Then killing -pid
595 // of the parent will kill the process and all of its children.
600 #if defined(HAVE_SETPRIORITY)
601 if ( prio
&& setpriority(PRIO_PROCESS
, 0, prio
) != 0 )
603 wxLogSysError(_("Failed to set process priority"));
605 #endif // HAVE_SETPRIORITY
607 // redirect stdin, stdout and stderr
610 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
611 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
612 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
614 wxLogSysError(_("Failed to redirect child process input/output"));
622 // Close all (presumably accidentally) inherited file descriptors to
623 // avoid descriptor leaks. This means that we don't allow inheriting
624 // them purposefully but this seems like a lesser evil in wx code.
625 // Ideally we'd provide some flag to indicate that none (or some?) of
626 // the descriptors do not need to be closed but for now this is better
627 // than never closing them at all as wx code never used FD_CLOEXEC.
629 // Note that while the reading side of the end process detection pipe
630 // can be safely closed, we should keep the write one opened, it will
631 // be only closed when the process terminates resulting in a read
632 // notification to the parent
633 const int fdEndProc
= execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
634 execData
.pipeEndProcDetect
.Close();
636 // TODO: Iterating up to FD_SETSIZE is both inefficient (because it may
637 // be quite big) and incorrect (because in principle we could
638 // have more opened descriptions than this number). Unfortunately
639 // there is no good portable solution for closing all descriptors
640 // above a certain threshold but non-portable solutions exist for
641 // most platforms, see [http://stackoverflow.com/questions/899038/
642 // getting-the-highest-allocated-file-descriptor]
643 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; ++fd
)
645 if ( fd
!= STDIN_FILENO
&&
646 fd
!= STDOUT_FILENO
&&
647 fd
!= STDERR_FILENO
&&
655 // Process additional options if we have any
658 // Change working directory if it is specified
659 if ( !env
->cwd
.empty() )
660 wxSetWorkingDirectory(env
->cwd
);
662 // Change environment if needed.
664 // NB: We can't use execve() currently because we allow using
665 // non full paths to wxExecute(), i.e. we want to search for
666 // the program in PATH. However it just might be simpler/better
667 // to do the search manually and use execve() envp parameter to
668 // set up the environment of the child process explicitly
669 // instead of doing what we do below.
670 if ( !env
->env
.empty() )
672 wxEnvVariableHashMap oldenv
;
673 wxGetEnvMap(&oldenv
);
675 // Remove unwanted variables
676 wxEnvVariableHashMap::const_iterator it
;
677 for ( it
= oldenv
.begin(); it
!= oldenv
.end(); ++it
)
679 if ( env
->env
.find(it
->first
) == env
->env
.end() )
680 wxUnsetEnv(it
->first
);
683 // And add the new ones (possibly replacing the old values)
684 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
685 wxSetEnv(it
->first
, it
->second
);
691 fprintf(stderr
, "execvp(");
692 for ( char **a
= argv
; *a
; a
++ )
693 fprintf(stderr
, "%s%s", a
== argv
? "" : ", ", *a
);
694 fprintf(stderr
, ") failed with error %d!\n", errno
);
696 // there is no return after successful exec()
699 // some compilers complain about missing return - of course, they
700 // should know that exit() doesn't return but what else can we do if
703 // and, sure enough, other compilers complain about unreachable code
704 // after exit() call, so we can just always have return here...
705 #if defined(__VMS) || defined(__INTEL_COMPILER)
709 else // we're in parent
711 // save it for WaitForChild() use
713 if (execData
.process
)
714 execData
.process
->SetPid(pid
); // and also in the wxProcess
716 // prepare for IO redirection
719 // the input buffer bufOut is connected to stdout, this is why it is
720 // called bufOut and not bufIn
721 wxStreamTempInputBuffer bufOut
,
724 if ( process
&& process
->IsRedirected() )
726 // Avoid deadlocks which could result from trying to write to the
727 // child input pipe end while the child itself is writing to its
728 // output end and waiting for us to read from it.
729 if ( !pipeIn
.MakeNonBlocking(wxPipe::Write
) )
731 // This message is not terrible useful for the user but what
732 // else can we do? Also, should we fail here or take the risk
733 // to continue and deadlock? Currently we choose the latter but
734 // it might not be the best idea.
735 wxLogSysError(_("Failed to set up non-blocking pipe, "
736 "the program might hang."));
738 wxLog::FlushActive();
742 wxOutputStream
*inStream
=
743 new wxPipeOutputStream(pipeIn
.Detach(wxPipe::Write
));
745 const int fdOut
= pipeOut
.Detach(wxPipe::Read
);
746 wxPipeInputStream
*outStream
= new wxPipeInputStream(fdOut
);
748 const int fdErr
= pipeErr
.Detach(wxPipe::Read
);
749 wxPipeInputStream
*errStream
= new wxPipeInputStream(fdErr
);
751 process
->SetPipeStreams(outStream
, inStream
, errStream
);
753 bufOut
.Init(outStream
);
754 bufErr
.Init(errStream
);
756 execData
.bufOut
= &bufOut
;
757 execData
.bufErr
= &bufErr
;
759 execData
.fdOut
= fdOut
;
760 execData
.fdErr
= fdErr
;
762 #endif // HAS_PIPE_STREAMS
771 // we want this function to work even if there is no wxApp so ensure
772 // that we have a valid traits pointer
773 wxConsoleAppTraits traitsConsole
;
774 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
776 traits
= &traitsConsole
;
778 return traits
->WaitForChild(execData
);
781 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
782 return ERROR_RETURN_CODE
;
786 #undef ERROR_RETURN_CODE
788 // ----------------------------------------------------------------------------
789 // file and directory functions
790 // ----------------------------------------------------------------------------
792 const wxChar
* wxGetHomeDir( wxString
*home
)
794 *home
= wxGetUserHome();
800 if ( tmp
.Last() != wxT(']'))
801 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
803 return home
->c_str();
806 wxString
wxGetUserHome( const wxString
&user
)
808 struct passwd
*who
= (struct passwd
*) NULL
;
814 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
819 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
||
820 (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
822 who
= getpwnam(wxSafeConvertWX2MB(ptr
));
825 // make sure the user exists!
828 who
= getpwuid(getuid());
833 who
= getpwnam (user
.mb_str());
836 return wxSafeConvertMB2WX(who
? who
->pw_dir
: 0);
839 // ----------------------------------------------------------------------------
840 // network and user id routines
841 // ----------------------------------------------------------------------------
843 // private utility function which returns output of the given command, removing
844 // the trailing newline
845 static wxString
wxGetCommandOutput(const wxString
&cmd
)
847 // Suppress stderr from the shell to avoid outputting errors if the command
849 FILE *f
= popen((cmd
+ " 2>/dev/null").ToAscii(), "r");
852 // Notice that this doesn't happen simply if the command doesn't exist,
853 // but only in case of some really catastrophic failure inside popen()
854 // so we should really notify the user about this as this is not normal.
855 wxLogSysError(wxT("Executing \"%s\" failed"), cmd
);
863 if ( !fgets(buf
, sizeof(buf
), f
) )
866 s
+= wxString::FromAscii(buf
);
871 if ( !s
.empty() && s
.Last() == wxT('\n') )
877 // retrieve either the hostname or FQDN depending on platform (caller must
878 // check whether it's one or the other, this is why this function is for
880 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
882 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
886 // we're using uname() which is POSIX instead of less standard sysinfo()
887 #if defined(HAVE_UNAME)
889 bool ok
= uname(&uts
) != -1;
892 wxStrlcpy(buf
, wxSafeConvertMB2WX(uts
.nodename
), sz
);
894 #elif defined(HAVE_GETHOSTNAME)
896 bool ok
= gethostname(cbuf
, sz
) != -1;
899 wxStrlcpy(buf
, wxSafeConvertMB2WX(cbuf
), sz
);
901 #else // no uname, no gethostname
902 wxFAIL_MSG(wxT("don't know host name for this machine"));
905 #endif // uname/gethostname
909 wxLogSysError(_("Cannot get the hostname"));
915 bool wxGetHostName(wxChar
*buf
, int sz
)
917 bool ok
= wxGetHostNameInternal(buf
, sz
);
921 // BSD systems return the FQDN, we only want the hostname, so extract
922 // it (we consider that dots are domain separators)
923 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
934 bool wxGetFullHostName(wxChar
*buf
, int sz
)
936 bool ok
= wxGetHostNameInternal(buf
, sz
);
940 if ( !wxStrchr(buf
, wxT('.')) )
942 struct hostent
*host
= gethostbyname(wxSafeConvertWX2MB(buf
));
945 wxLogSysError(_("Cannot get the official hostname"));
951 // the canonical name
952 wxStrlcpy(buf
, wxSafeConvertMB2WX(host
->h_name
), sz
);
955 //else: it's already a FQDN (BSD behaves this way)
961 bool wxGetUserId(wxChar
*buf
, int sz
)
966 if ((who
= getpwuid(getuid ())) != NULL
)
968 wxStrlcpy (buf
, wxSafeConvertMB2WX(who
->pw_name
), sz
);
975 bool wxGetUserName(wxChar
*buf
, int sz
)
981 if ((who
= getpwuid (getuid ())) != NULL
)
983 char *comma
= strchr(who
->pw_gecos
, ',');
985 *comma
= '\0'; // cut off non-name comment fields
986 wxStrlcpy(buf
, wxSafeConvertMB2WX(who
->pw_gecos
), sz
);
991 #else // !HAVE_PW_GECOS
992 return wxGetUserId(buf
, sz
);
993 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
996 bool wxIsPlatform64Bit()
998 const wxString machine
= wxGetCommandOutput(wxT("uname -m"));
1000 // the test for "64" is obviously not 100% reliable but seems to work fine
1002 return machine
.Contains(wxT("64")) ||
1003 machine
.Contains(wxT("alpha"));
1007 wxLinuxDistributionInfo
wxGetLinuxDistributionInfo()
1009 const wxString id
= wxGetCommandOutput(wxT("lsb_release --id"));
1010 const wxString desc
= wxGetCommandOutput(wxT("lsb_release --description"));
1011 const wxString rel
= wxGetCommandOutput(wxT("lsb_release --release"));
1012 const wxString codename
= wxGetCommandOutput(wxT("lsb_release --codename"));
1014 wxLinuxDistributionInfo ret
;
1016 id
.StartsWith("Distributor ID:\t", &ret
.Id
);
1017 desc
.StartsWith("Description:\t", &ret
.Description
);
1018 rel
.StartsWith("Release:\t", &ret
.Release
);
1019 codename
.StartsWith("Codename:\t", &ret
.CodeName
);
1025 // these functions are in src/osx/utilsexc_base.cpp for wxMac
1028 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
1032 wxString release
= wxGetCommandOutput(wxT("uname -r"));
1033 if ( release
.empty() ||
1034 wxSscanf(release
.c_str(), wxT("%d.%d"), &major
, &minor
) != 2 )
1036 // failed to get version string or unrecognized format
1046 // try to understand which OS are we running
1047 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
1048 if ( kernel
.empty() )
1049 kernel
= wxGetCommandOutput(wxT("uname -o"));
1051 if ( kernel
.empty() )
1052 return wxOS_UNKNOWN
;
1054 return wxPlatformInfo::GetOperatingSystemId(kernel
);
1057 wxString
wxGetOsDescription()
1059 return wxGetCommandOutput(wxT("uname -s -r -m"));
1062 #endif // !__DARWIN__
1064 unsigned long wxGetProcessId()
1066 return (unsigned long)getpid();
1069 wxMemorySize
wxGetFreeMemory()
1071 #if defined(__LINUX__)
1072 // get it from /proc/meminfo
1073 FILE *fp
= fopen("/proc/meminfo", "r");
1079 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
1081 // /proc/meminfo changed its format in kernel 2.6
1082 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
1084 unsigned long cached
, buffers
;
1085 sscanf(buf
, "MemFree: %ld", &memFree
);
1087 fgets(buf
, WXSIZEOF(buf
), fp
);
1088 sscanf(buf
, "Buffers: %lu", &buffers
);
1090 fgets(buf
, WXSIZEOF(buf
), fp
);
1091 sscanf(buf
, "Cached: %lu", &cached
);
1093 // add to "MemFree" also the "Buffers" and "Cached" values as
1094 // free(1) does as otherwise the value never makes sense: for
1095 // kernel 2.6 it's always almost 0
1096 memFree
+= buffers
+ cached
;
1098 // values here are always expressed in kB and we want bytes
1101 else // Linux 2.4 (or < 2.6, anyhow)
1103 long memTotal
, memUsed
;
1104 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
1110 return (wxMemorySize
)memFree
;
1112 #elif defined(__SGI__)
1113 struct rminfo realmem
;
1114 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
1115 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
1116 #elif defined(_SC_AVPHYS_PAGES)
1117 return ((wxMemorySize
)sysconf(_SC_AVPHYS_PAGES
))*sysconf(_SC_PAGESIZE
);
1118 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1121 // can't find it out
1125 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
1127 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1128 // the case to "char *" is needed for AIX 4.3
1130 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
1132 wxLogSysError( wxT("Failed to get file system statistics") );
1137 // under Solaris we also have to use f_frsize field instead of f_bsize
1138 // which is in general a multiple of f_frsize
1140 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1141 #else // HAVE_STATFS
1142 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1143 #endif // HAVE_STATVFS/HAVE_STATFS
1147 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1152 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1156 #else // !HAVE_STATFS && !HAVE_STATVFS
1158 #endif // HAVE_STATFS
1161 // ----------------------------------------------------------------------------
1163 // ----------------------------------------------------------------------------
1167 WX_DECLARE_STRING_HASH_MAP(char *, wxEnvVars
);
1169 static wxEnvVars gs_envVars
;
1171 class wxSetEnvModule
: public wxModule
1174 virtual bool OnInit() { return true; }
1175 virtual void OnExit()
1177 for ( wxEnvVars::const_iterator i
= gs_envVars
.begin();
1178 i
!= gs_envVars
.end();
1187 DECLARE_DYNAMIC_CLASS(wxSetEnvModule
)
1190 IMPLEMENT_DYNAMIC_CLASS(wxSetEnvModule
, wxModule
)
1192 #endif // USE_PUTENV
1194 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1196 // wxGetenv is defined as getenv()
1197 char *p
= wxGetenv(var
);
1209 static bool wxDoSetEnv(const wxString
& variable
, const char *value
)
1211 #if defined(HAVE_SETENV)
1214 #ifdef HAVE_UNSETENV
1215 // don't test unsetenv() return value: it's void on some systems (at
1217 unsetenv(variable
.mb_str());
1220 value
= ""; // we can't pass NULL to setenv()
1224 return setenv(variable
.mb_str(), value
, 1 /* overwrite */) == 0;
1225 #elif defined(HAVE_PUTENV)
1226 wxString s
= variable
;
1228 s
<< wxT('=') << value
;
1230 // transform to ANSI
1231 const wxWX2MBbuf p
= s
.mb_str();
1233 char *buf
= (char *)malloc(strlen(p
) + 1);
1236 // store the string to free() it later
1237 wxEnvVars::iterator i
= gs_envVars
.find(variable
);
1238 if ( i
!= gs_envVars
.end() )
1243 else // this variable hadn't been set before
1245 gs_envVars
[variable
] = buf
;
1248 return putenv(buf
) == 0;
1249 #else // no way to set an env var
1254 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
1256 return wxDoSetEnv(variable
, value
.mb_str());
1259 bool wxUnsetEnv(const wxString
& variable
)
1261 return wxDoSetEnv(variable
, NULL
);
1264 // ----------------------------------------------------------------------------
1266 // ----------------------------------------------------------------------------
1268 #if wxUSE_ON_FATAL_EXCEPTION
1272 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1276 // give the user a chance to do something special about this
1277 wxTheApp
->OnFatalException();
1283 bool wxHandleFatalExceptions(bool doit
)
1286 static bool s_savedHandlers
= false;
1287 static struct sigaction s_handlerFPE
,
1293 if ( doit
&& !s_savedHandlers
)
1295 // install the signal handler
1296 struct sigaction act
;
1298 // some systems extend it with non std fields, so zero everything
1299 memset(&act
, 0, sizeof(act
));
1301 act
.sa_handler
= wxFatalSignalHandler
;
1302 sigemptyset(&act
.sa_mask
);
1305 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1306 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1307 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1308 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1311 wxLogDebug(wxT("Failed to install our signal handler."));
1314 s_savedHandlers
= true;
1316 else if ( s_savedHandlers
)
1318 // uninstall the signal handler
1319 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1320 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1321 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1322 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1325 wxLogDebug(wxT("Failed to uninstall our signal handler."));
1328 s_savedHandlers
= false;
1330 //else: nothing to do
1335 #endif // wxUSE_ON_FATAL_EXCEPTION
1337 // ----------------------------------------------------------------------------
1338 // wxExecute support
1339 // ----------------------------------------------------------------------------
1341 int wxAppTraits::AddProcessCallback(wxEndProcessData
*data
, int fd
)
1343 // define a custom handler processing only the closure of the descriptor
1344 struct wxEndProcessFDIOHandler
: public wxFDIOHandler
1346 wxEndProcessFDIOHandler(wxEndProcessData
*data
, int fd
)
1347 : m_data(data
), m_fd(fd
)
1351 virtual void OnReadWaiting()
1353 wxFDIODispatcher::Get()->UnregisterFD(m_fd
);
1356 wxHandleProcessTermination(m_data
);
1361 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1362 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1364 wxEndProcessData
* const m_data
;
1368 wxFDIODispatcher::Get()->RegisterFD
1371 new wxEndProcessFDIOHandler(data
, fd
),
1374 return fd
; // unused, but return something unique for the tag
1377 bool wxAppTraits::CheckForRedirectedIO(wxExecuteData
& execData
)
1379 #if HAS_PIPE_STREAMS
1382 if ( execData
.bufOut
&& execData
.bufOut
->Update() )
1385 if ( execData
.bufErr
&& execData
.bufErr
->Update() )
1389 #else // !HAS_PIPE_STREAMS
1390 wxUnusedVar(execData
);
1393 #endif // HAS_PIPE_STREAMS/!HAS_PIPE_STREAMS
1396 // helper classes/functions used by WaitForChild()
1400 // convenient base class for IO handlers which are registered for read
1401 // notifications only and which also stores the FD we're reading from
1403 // the derived classes still have to implement OnReadWaiting()
1404 class wxReadFDIOHandler
: public wxFDIOHandler
1407 wxReadFDIOHandler(wxFDIODispatcher
& disp
, int fd
) : m_fd(fd
)
1410 disp
.RegisterFD(fd
, this, wxFDIO_INPUT
);
1413 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1414 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1419 wxDECLARE_NO_COPY_CLASS(wxReadFDIOHandler
);
1422 // class for monitoring our end of the process detection pipe, simply sets a
1423 // flag when input on the pipe (which must be due to EOF) is detected
1424 class wxEndHandler
: public wxReadFDIOHandler
1427 wxEndHandler(wxFDIODispatcher
& disp
, int fd
)
1428 : wxReadFDIOHandler(disp
, fd
)
1430 m_terminated
= false;
1433 bool Terminated() const { return m_terminated
; }
1435 virtual void OnReadWaiting() { m_terminated
= true; }
1440 wxDECLARE_NO_COPY_CLASS(wxEndHandler
);
1443 #if HAS_PIPE_STREAMS
1445 // class for monitoring our ends of child stdout/err, should be constructed
1446 // with the FD and stream from wxExecuteData and will do nothing if they're
1449 // unlike wxEndHandler this class registers itself with the provided dispatcher
1450 class wxRedirectedIOHandler
: public wxReadFDIOHandler
1453 wxRedirectedIOHandler(wxFDIODispatcher
& disp
,
1455 wxStreamTempInputBuffer
*buf
)
1456 : wxReadFDIOHandler(disp
, fd
),
1461 virtual void OnReadWaiting()
1467 wxStreamTempInputBuffer
* const m_buf
;
1469 wxDECLARE_NO_COPY_CLASS(wxRedirectedIOHandler
);
1472 #endif // HAS_PIPE_STREAMS
1474 // helper function which calls waitpid() and analyzes the result
1475 int DoWaitForChild(int pid
, int flags
= 0)
1477 wxASSERT_MSG( pid
> 0, "invalid PID" );
1481 // loop while we're getting EINTR
1484 rc
= waitpid(pid
, &status
, flags
);
1486 if ( rc
!= -1 || errno
!= EINTR
)
1492 // This can only happen if the child application closes our dummy pipe
1493 // that is used to monitor its lifetime; in that case, our best bet is
1494 // to pretend the process did terminate, because otherwise wxExecute()
1495 // would hang indefinitely (OnReadWaiting() won't be called again, the
1496 // descriptor is closed now).
1497 wxLogDebug("Child process (PID %d) still alive but pipe closed so "
1498 "generating a close notification", pid
);
1500 else if ( rc
== -1 )
1502 wxLogLastError(wxString::Format("waitpid(%d)", pid
));
1504 else // child did terminate
1506 wxASSERT_MSG( rc
== pid
, "unexpected waitpid() return value" );
1508 // notice that the caller expects the exit code to be signed, e.g. -1
1509 // instead of 255 so don't assign WEXITSTATUS() to an int
1510 signed char exitcode
;
1511 if ( WIFEXITED(status
) )
1512 exitcode
= WEXITSTATUS(status
);
1513 else if ( WIFSIGNALED(status
) )
1514 exitcode
= -WTERMSIG(status
);
1517 wxLogError("Child process (PID %d) exited for unknown reason, "
1518 "status = %d", pid
, status
);
1528 } // anonymous namespace
1530 int wxAppTraits::WaitForChild(wxExecuteData
& execData
)
1532 if ( !(execData
.flags
& wxEXEC_SYNC
) )
1534 // asynchronous execution: just launch the process and return,
1535 // endProcData will be destroyed when it terminates (currently we leak
1536 // it if the process doesn't terminate before we do and this should be
1537 // fixed but it's not a real leak so it's not really very high
1539 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1540 endProcData
->process
= execData
.process
;
1541 endProcData
->pid
= execData
.pid
;
1542 endProcData
->tag
= AddProcessCallback
1545 execData
.GetEndProcReadFD()
1547 endProcData
->async
= true;
1549 return execData
.pid
;
1551 //else: synchronous execution case
1553 #if HAS_PIPE_STREAMS && wxUSE_SOCKETS
1554 wxProcess
* const process
= execData
.process
;
1555 if ( process
&& process
->IsRedirected() )
1557 // we can't simply block waiting for the child to terminate as we would
1558 // dead lock if it writes more than the pipe buffer size (typically
1559 // 4KB) bytes of output -- it would then block waiting for us to read
1560 // the data while we'd block waiting for it to terminate
1562 // so multiplex here waiting for any input from the child or closure of
1563 // the pipe used to indicate its termination
1564 wxSelectDispatcher disp
;
1566 wxEndHandler
endHandler(disp
, execData
.GetEndProcReadFD());
1568 wxRedirectedIOHandler
outHandler(disp
, execData
.fdOut
, execData
.bufOut
),
1569 errHandler(disp
, execData
.fdErr
, execData
.bufErr
);
1571 while ( !endHandler
.Terminated() )
1576 //else: no IO redirection, just block waiting for the child to exit
1577 #endif // HAS_PIPE_STREAMS
1579 return DoWaitForChild(execData
.pid
);
1582 void wxHandleProcessTermination(wxEndProcessData
*data
)
1584 data
->exitcode
= DoWaitForChild(data
->pid
, WNOHANG
);
1586 // notify user about termination if required
1587 if ( data
->process
)
1589 data
->process
->OnTerminate(data
->pid
, data
->exitcode
);
1594 // in case of asynchronous execution we don't need this data any more
1595 // after the child terminates
1598 else // sync execution
1600 // let wxExecute() know that the process has terminated