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 // ----------------------------------------------------------------------------
136 // conditional compilation
137 // ----------------------------------------------------------------------------
139 // many versions of Unices have this function, but it is not defined in system
140 // headers - please add your system here if it is the case for your OS.
141 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
142 #if !defined(HAVE_USLEEP) && \
143 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
144 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
145 defined(__osf__) || defined(__EMX__))
149 /* I copied this from the XFree86 diffs. AV. */
150 #define INCL_DOSPROCESS
152 inline void usleep(unsigned long delay
)
154 DosSleep(delay
? (delay
/1000l) : 1l);
157 int usleep(unsigned int usec
);
158 #endif // __EMX__/Unix
161 #define HAVE_USLEEP 1
162 #endif // Unices without usleep()
164 // ============================================================================
166 // ============================================================================
168 // ----------------------------------------------------------------------------
170 // ----------------------------------------------------------------------------
172 void wxSleep(int nSecs
)
177 void wxMicroSleep(unsigned long microseconds
)
179 #if defined(HAVE_NANOSLEEP)
181 tmReq
.tv_sec
= (time_t)(microseconds
/ 1000000);
182 tmReq
.tv_nsec
= (microseconds
% 1000000) * 1000;
184 // we're not interested in remaining time nor in return value
185 (void)nanosleep(&tmReq
, NULL
);
186 #elif defined(HAVE_USLEEP)
187 // uncomment this if you feel brave or if you are sure that your version
188 // of Solaris has a safe usleep() function but please notice that usleep()
189 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
190 // documented as MT-Safe
191 #if defined(__SUN__) && wxUSE_THREADS
192 #error "usleep() cannot be used in MT programs under Solaris."
195 usleep(microseconds
);
196 #elif defined(HAVE_SLEEP)
197 // under BeOS sleep() takes seconds (what about other platforms, if any?)
198 sleep(microseconds
* 1000000);
199 #else // !sleep function
200 #error "usleep() or nanosleep() function required for wxMicroSleep"
201 #endif // sleep function
204 void wxMilliSleep(unsigned long milliseconds
)
206 wxMicroSleep(milliseconds
*1000);
209 // ----------------------------------------------------------------------------
210 // process management
211 // ----------------------------------------------------------------------------
213 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
, int flags
)
215 int err
= kill((pid_t
) (flags
& wxKILL_CHILDREN
) ? -pid
: pid
, (int)sig
);
218 switch ( err
? errno
: 0 )
225 *rc
= wxKILL_BAD_SIGNAL
;
229 *rc
= wxKILL_ACCESS_DENIED
;
233 *rc
= wxKILL_NO_PROCESS
;
237 // this goes against Unix98 docs so log it
238 wxLogDebug(wxT("unexpected kill(2) return value %d"), err
);
248 // Shutdown or reboot the PC
249 bool wxShutdown(int flags
)
251 flags
&= ~wxSHUTDOWN_FORCE
;
256 case wxSHUTDOWN_POWEROFF
:
260 case wxSHUTDOWN_REBOOT
:
264 case wxSHUTDOWN_LOGOFF
:
265 // TODO: use dcop to log off?
269 wxFAIL_MSG( wxT("unknown wxShutdown() flag") );
273 return system(wxString::Format("init %c", level
).mb_str()) == 0;
276 // ----------------------------------------------------------------------------
277 // wxStream classes to support IO redirection in wxExecute
278 // ----------------------------------------------------------------------------
282 bool wxPipeInputStream::CanRead() const
284 if ( m_lasterror
== wxSTREAM_EOF
)
287 // check if there is any input available
292 const int fd
= m_file
->fd();
297 wxFD_SET(fd
, &readfds
);
299 switch ( select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
302 wxLogSysError(_("Impossible to get child process input"));
309 wxFAIL_MSG(wxT("unexpected select() return value"));
310 // still fall through
313 // input available -- or maybe not, as select() returns 1 when a
314 // read() will complete without delay, but it could still not read
320 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t size
)
322 // We need to suppress error logging here, because on writing to a pipe
323 // which is full, wxFile::Write reports a system error. However, this is
324 // not an extraordinary situation, and it should not be reported to the
325 // user (but if really needed, the program can recognize it by checking
326 // whether LastRead() == 0.) Other errors will be reported below.
330 ret
= m_file
->Write(buffer
, size
);
333 switch ( m_file
->GetLastError() )
339 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
342 // do not treat it as an error
343 m_file
->ClearLastError();
352 wxLogSysError(_("Can't write to child process's stdin"));
353 m_lasterror
= wxSTREAM_WRITE_ERROR
;
359 #endif // HAS_PIPE_STREAMS
361 // ----------------------------------------------------------------------------
363 // ----------------------------------------------------------------------------
365 static wxString
wxMakeShellCommand(const wxString
& command
)
370 // just an interactive shell
375 // execute command in a shell
376 cmd
<< wxT("/bin/sh -c '") << command
<< wxT('\'');
382 bool wxShell(const wxString
& command
)
384 return wxExecute(wxMakeShellCommand(command
), wxEXEC_SYNC
) == 0;
387 bool wxShell(const wxString
& command
, wxArrayString
& output
)
389 wxCHECK_MSG( !command
.empty(), false, wxT("can't exec shell non interactively") );
391 return wxExecute(wxMakeShellCommand(command
), output
);
397 // helper class for storing arguments as char** array suitable for passing to
398 // execvp(), whatever form they were passed to us
402 ArgsArray(const wxArrayString
& args
)
406 for ( int i
= 0; i
< m_argc
; i
++ )
408 m_argv
[i
] = wxStrdup(args
[i
]);
413 ArgsArray(wchar_t **wargv
)
416 while ( wargv
[argc
] )
421 for ( int i
= 0; i
< m_argc
; i
++ )
423 m_argv
[i
] = wxSafeConvertWX2MB(wargv
[i
]).release();
426 #endif // wxUSE_UNICODE
430 for ( int i
= 0; i
< m_argc
; i
++ )
438 operator char**() const { return m_argv
; }
444 m_argv
= new char *[m_argc
+ 1];
445 m_argv
[m_argc
] = NULL
;
451 wxDECLARE_NO_COPY_CLASS(ArgsArray
);
454 } // anonymous namespace
456 // ----------------------------------------------------------------------------
457 // wxExecute implementations
458 // ----------------------------------------------------------------------------
460 #if defined(__DARWIN__)
461 bool wxMacLaunch(char **argv
);
464 long wxExecute(const wxString
& command
, int flags
, wxProcess
*process
,
465 const wxExecuteEnv
*env
)
467 ArgsArray
argv(wxCmdLineParser::ConvertStringToArgs(command
,
468 wxCMD_LINE_SPLIT_UNIX
));
470 return wxExecute(argv
, flags
, process
, env
);
475 long wxExecute(wchar_t **wargv
, int flags
, wxProcess
*process
,
476 const wxExecuteEnv
*env
)
478 ArgsArray
argv(wargv
);
480 return wxExecute(argv
, flags
, process
, env
);
483 #endif // wxUSE_UNICODE
485 // wxExecute: the real worker function
486 long wxExecute(char **argv
, int flags
, wxProcess
*process
,
487 const wxExecuteEnv
*env
)
489 // for the sync execution, we return -1 to indicate failure, but for async
490 // case we return 0 which is never a valid PID
492 // we define this as a macro, not a variable, to avoid compiler warnings
493 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
494 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
496 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
499 // fork() doesn't mix well with POSIX threads: on many systems the program
500 // deadlocks or crashes for some reason. Probably our code is buggy and
501 // doesn't do something which must be done to allow this to work, but I
502 // don't know what yet, so for now just warn the user (this is the least we
504 wxASSERT_MSG( wxThread::IsMain(),
505 wxT("wxExecute() can be called only from the main thread") );
506 #endif // wxUSE_THREADS
508 #if defined(__WXCOCOA__) || ( defined(__WXOSX_MAC__) && wxOSX_USE_COCOA_OR_CARBON )
509 // wxMacLaunch() only executes app bundles and only does it asynchronously.
510 // It returns false if the target is not an app bundle, thus falling
511 // through to the regular code for non app bundles.
512 if ( !(flags
& wxEXEC_SYNC
) && wxMacLaunch(argv
) )
514 // we don't have any PID to return so just make up something non null
520 // this struct contains all information which we use for housekeeping
521 wxExecuteData execData
;
522 execData
.flags
= flags
;
523 execData
.process
= process
;
526 if ( !execData
.pipeEndProcDetect
.Create() )
528 wxLogError( _("Failed to execute '%s'\n"), *argv
);
530 return ERROR_RETURN_CODE
;
533 // pipes for inter process communication
534 wxPipe pipeIn
, // stdin
538 if ( process
&& process
->IsRedirected() )
540 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
542 wxLogError( _("Failed to execute '%s'\n"), *argv
);
544 return ERROR_RETURN_CODE
;
550 // NB: do *not* use vfork() here, it completely breaks this code for some
551 // reason under Solaris (and maybe others, although not under Linux)
552 // But on OpenVMS we do not have fork so we have to use vfork and
553 // cross our fingers that it works.
559 if ( pid
== -1 ) // error?
561 wxLogSysError( _("Fork failed") );
563 return ERROR_RETURN_CODE
;
565 else if ( pid
== 0 ) // we're in child
567 // NB: we used to close all the unused descriptors of the child here
568 // but this broke some programs which relied on e.g. FD 1 being
569 // always opened so don't do it any more, after all there doesn't
570 // seem to be any real problem with keeping them opened
572 #if !defined(__VMS) && !defined(__EMX__)
573 if ( flags
& wxEXEC_MAKE_GROUP_LEADER
)
575 // Set process group to child process' pid. Then killing -pid
576 // of the parent will kill the process and all of its children.
581 // redirect stdin, stdout and stderr
584 if ( dup2(pipeIn
[wxPipe::Read
], STDIN_FILENO
) == -1 ||
585 dup2(pipeOut
[wxPipe::Write
], STDOUT_FILENO
) == -1 ||
586 dup2(pipeErr
[wxPipe::Write
], STDERR_FILENO
) == -1 )
588 wxLogSysError(_("Failed to redirect child process input/output"));
596 // Close all (presumably accidentally) inherited file descriptors to
597 // avoid descriptor leaks. This means that we don't allow inheriting
598 // them purposefully but this seems like a lesser evil in wx code.
599 // Ideally we'd provide some flag to indicate that none (or some?) of
600 // the descriptors do not need to be closed but for now this is better
601 // than never closing them at all as wx code never used FD_CLOEXEC.
603 // Note that while the reading side of the end process detection pipe
604 // can be safely closed, we should keep the write one opened, it will
605 // be only closed when the process terminates resulting in a read
606 // notification to the parent
607 const int fdEndProc
= execData
.pipeEndProcDetect
.Detach(wxPipe::Write
);
608 execData
.pipeEndProcDetect
.Close();
610 // TODO: Iterating up to FD_SETSIZE is both inefficient (because it may
611 // be quite big) and incorrect (because in principle we could
612 // have more opened descriptions than this number). Unfortunately
613 // there is no good portable solution for closing all descriptors
614 // above a certain threshold but non-portable solutions exist for
615 // most platforms, see [http://stackoverflow.com/questions/899038/
616 // getting-the-highest-allocated-file-descriptor]
617 for ( int fd
= 0; fd
< (int)FD_SETSIZE
; ++fd
)
619 if ( fd
!= STDIN_FILENO
&&
620 fd
!= STDOUT_FILENO
&&
621 fd
!= STDERR_FILENO
&&
629 // Process additional options if we have any
632 // Change working directory if it is specified
633 if ( !env
->cwd
.empty() )
634 wxSetWorkingDirectory(env
->cwd
);
636 // Change environment if needed.
638 // NB: We can't use execve() currently because we allow using
639 // non full paths to wxExecute(), i.e. we want to search for
640 // the program in PATH. However it just might be simpler/better
641 // to do the search manually and use execve() envp parameter to
642 // set up the environment of the child process explicitly
643 // instead of doing what we do below.
644 if ( !env
->env
.empty() )
646 wxEnvVariableHashMap oldenv
;
647 wxGetEnvMap(&oldenv
);
649 // Remove unwanted variables
650 wxEnvVariableHashMap::const_iterator it
;
651 for ( it
= oldenv
.begin(); it
!= oldenv
.end(); ++it
)
653 if ( env
->env
.find(it
->first
) == env
->env
.end() )
654 wxUnsetEnv(it
->first
);
657 // And add the new ones (possibly replacing the old values)
658 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
659 wxSetEnv(it
->first
, it
->second
);
665 fprintf(stderr
, "execvp(");
666 for ( char **a
= argv
; *a
; a
++ )
667 fprintf(stderr
, "%s%s", a
== argv
? "" : ", ", *a
);
668 fprintf(stderr
, ") failed with error %d!\n", errno
);
670 // there is no return after successful exec()
673 // some compilers complain about missing return - of course, they
674 // should know that exit() doesn't return but what else can we do if
677 // and, sure enough, other compilers complain about unreachable code
678 // after exit() call, so we can just always have return here...
679 #if defined(__VMS) || defined(__INTEL_COMPILER)
683 else // we're in parent
685 // save it for WaitForChild() use
687 if (execData
.process
)
688 execData
.process
->SetPid(pid
); // and also in the wxProcess
690 // prepare for IO redirection
693 // the input buffer bufOut is connected to stdout, this is why it is
694 // called bufOut and not bufIn
695 wxStreamTempInputBuffer bufOut
,
698 if ( process
&& process
->IsRedirected() )
700 // Avoid deadlocks which could result from trying to write to the
701 // child input pipe end while the child itself is writing to its
702 // output end and waiting for us to read from it.
703 if ( !pipeIn
.MakeNonBlocking(wxPipe::Write
) )
705 // This message is not terrible useful for the user but what
706 // else can we do? Also, should we fail here or take the risk
707 // to continue and deadlock? Currently we choose the latter but
708 // it might not be the best idea.
709 wxLogSysError(_("Failed to set up non-blocking pipe, "
710 "the program might hang."));
712 wxLog::FlushActive();
716 wxOutputStream
*inStream
=
717 new wxPipeOutputStream(pipeIn
.Detach(wxPipe::Write
));
719 const int fdOut
= pipeOut
.Detach(wxPipe::Read
);
720 wxPipeInputStream
*outStream
= new wxPipeInputStream(fdOut
);
722 const int fdErr
= pipeErr
.Detach(wxPipe::Read
);
723 wxPipeInputStream
*errStream
= new wxPipeInputStream(fdErr
);
725 process
->SetPipeStreams(outStream
, inStream
, errStream
);
727 bufOut
.Init(outStream
);
728 bufErr
.Init(errStream
);
730 execData
.bufOut
= &bufOut
;
731 execData
.bufErr
= &bufErr
;
733 execData
.fdOut
= fdOut
;
734 execData
.fdErr
= fdErr
;
736 #endif // HAS_PIPE_STREAMS
745 // we want this function to work even if there is no wxApp so ensure
746 // that we have a valid traits pointer
747 wxConsoleAppTraits traitsConsole
;
748 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
750 traits
= &traitsConsole
;
752 return traits
->WaitForChild(execData
);
755 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
756 return ERROR_RETURN_CODE
;
760 #undef ERROR_RETURN_CODE
762 // ----------------------------------------------------------------------------
763 // file and directory functions
764 // ----------------------------------------------------------------------------
766 const wxChar
* wxGetHomeDir( wxString
*home
)
768 *home
= wxGetUserHome();
774 if ( tmp
.Last() != wxT(']'))
775 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
777 return home
->c_str();
780 wxString
wxGetUserHome( const wxString
&user
)
782 struct passwd
*who
= (struct passwd
*) NULL
;
788 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
793 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
||
794 (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
796 who
= getpwnam(wxSafeConvertWX2MB(ptr
));
799 // make sure the user exists!
802 who
= getpwuid(getuid());
807 who
= getpwnam (user
.mb_str());
810 return wxSafeConvertMB2WX(who
? who
->pw_dir
: 0);
813 // ----------------------------------------------------------------------------
814 // network and user id routines
815 // ----------------------------------------------------------------------------
817 // private utility function which returns output of the given command, removing
818 // the trailing newline
819 static wxString
wxGetCommandOutput(const wxString
&cmd
)
821 FILE *f
= popen(cmd
.ToAscii(), "r");
824 wxLogSysError(wxT("Executing \"%s\" failed"), cmd
.c_str());
825 return wxEmptyString
;
832 if ( !fgets(buf
, sizeof(buf
), f
) )
835 s
+= wxString::FromAscii(buf
);
840 if ( !s
.empty() && s
.Last() == wxT('\n') )
846 // retrieve either the hostname or FQDN depending on platform (caller must
847 // check whether it's one or the other, this is why this function is for
849 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
851 wxCHECK_MSG( buf
, false, wxT("NULL pointer in wxGetHostNameInternal") );
855 // we're using uname() which is POSIX instead of less standard sysinfo()
856 #if defined(HAVE_UNAME)
858 bool ok
= uname(&uts
) != -1;
861 wxStrlcpy(buf
, wxSafeConvertMB2WX(uts
.nodename
), sz
);
863 #elif defined(HAVE_GETHOSTNAME)
865 bool ok
= gethostname(cbuf
, sz
) != -1;
868 wxStrlcpy(buf
, wxSafeConvertMB2WX(cbuf
), sz
);
870 #else // no uname, no gethostname
871 wxFAIL_MSG(wxT("don't know host name for this machine"));
874 #endif // uname/gethostname
878 wxLogSysError(_("Cannot get the hostname"));
884 bool wxGetHostName(wxChar
*buf
, int sz
)
886 bool ok
= wxGetHostNameInternal(buf
, sz
);
890 // BSD systems return the FQDN, we only want the hostname, so extract
891 // it (we consider that dots are domain separators)
892 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
903 bool wxGetFullHostName(wxChar
*buf
, int sz
)
905 bool ok
= wxGetHostNameInternal(buf
, sz
);
909 if ( !wxStrchr(buf
, wxT('.')) )
911 struct hostent
*host
= gethostbyname(wxSafeConvertWX2MB(buf
));
914 wxLogSysError(_("Cannot get the official hostname"));
920 // the canonical name
921 wxStrlcpy(buf
, wxSafeConvertMB2WX(host
->h_name
), sz
);
924 //else: it's already a FQDN (BSD behaves this way)
930 bool wxGetUserId(wxChar
*buf
, int sz
)
935 if ((who
= getpwuid(getuid ())) != NULL
)
937 wxStrlcpy (buf
, wxSafeConvertMB2WX(who
->pw_name
), sz
);
944 bool wxGetUserName(wxChar
*buf
, int sz
)
950 if ((who
= getpwuid (getuid ())) != NULL
)
952 char *comma
= strchr(who
->pw_gecos
, ',');
954 *comma
= '\0'; // cut off non-name comment fields
955 wxStrlcpy(buf
, wxSafeConvertMB2WX(who
->pw_gecos
), sz
);
960 #else // !HAVE_PW_GECOS
961 return wxGetUserId(buf
, sz
);
962 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
965 bool wxIsPlatform64Bit()
967 const wxString machine
= wxGetCommandOutput(wxT("uname -m"));
969 // the test for "64" is obviously not 100% reliable but seems to work fine
971 return machine
.Contains(wxT("64")) ||
972 machine
.Contains(wxT("alpha"));
976 wxLinuxDistributionInfo
wxGetLinuxDistributionInfo()
978 const wxString id
= wxGetCommandOutput(wxT("lsb_release --id"));
979 const wxString desc
= wxGetCommandOutput(wxT("lsb_release --description"));
980 const wxString rel
= wxGetCommandOutput(wxT("lsb_release --release"));
981 const wxString codename
= wxGetCommandOutput(wxT("lsb_release --codename"));
983 wxLinuxDistributionInfo ret
;
985 id
.StartsWith("Distributor ID:\t", &ret
.Id
);
986 desc
.StartsWith("Description:\t", &ret
.Description
);
987 rel
.StartsWith("Release:\t", &ret
.Release
);
988 codename
.StartsWith("Codename:\t", &ret
.CodeName
);
994 // these functions are in src/osx/utilsexc_base.cpp for wxMac
997 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
1001 wxString release
= wxGetCommandOutput(wxT("uname -r"));
1002 if ( release
.empty() ||
1003 wxSscanf(release
.c_str(), wxT("%d.%d"), &major
, &minor
) != 2 )
1005 // failed to get version string or unrecognized format
1015 // try to understand which OS are we running
1016 wxString kernel
= wxGetCommandOutput(wxT("uname -s"));
1017 if ( kernel
.empty() )
1018 kernel
= wxGetCommandOutput(wxT("uname -o"));
1020 if ( kernel
.empty() )
1021 return wxOS_UNKNOWN
;
1023 return wxPlatformInfo::GetOperatingSystemId(kernel
);
1026 wxString
wxGetOsDescription()
1028 return wxGetCommandOutput(wxT("uname -s -r -m"));
1031 #endif // !__WXMAC__
1033 unsigned long wxGetProcessId()
1035 return (unsigned long)getpid();
1038 wxMemorySize
wxGetFreeMemory()
1040 #if defined(__LINUX__)
1041 // get it from /proc/meminfo
1042 FILE *fp
= fopen("/proc/meminfo", "r");
1048 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
1050 // /proc/meminfo changed its format in kernel 2.6
1051 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
1053 unsigned long cached
, buffers
;
1054 sscanf(buf
, "MemFree: %ld", &memFree
);
1056 fgets(buf
, WXSIZEOF(buf
), fp
);
1057 sscanf(buf
, "Buffers: %lu", &buffers
);
1059 fgets(buf
, WXSIZEOF(buf
), fp
);
1060 sscanf(buf
, "Cached: %lu", &cached
);
1062 // add to "MemFree" also the "Buffers" and "Cached" values as
1063 // free(1) does as otherwise the value never makes sense: for
1064 // kernel 2.6 it's always almost 0
1065 memFree
+= buffers
+ cached
;
1067 // values here are always expressed in kB and we want bytes
1070 else // Linux 2.4 (or < 2.6, anyhow)
1072 long memTotal
, memUsed
;
1073 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
1079 return (wxMemorySize
)memFree
;
1081 #elif defined(__SGI__)
1082 struct rminfo realmem
;
1083 if ( sysmp(MP_SAGET
, MPSA_RMINFO
, &realmem
, sizeof realmem
) == 0 )
1084 return ((wxMemorySize
)realmem
.physmem
* sysconf(_SC_PAGESIZE
));
1085 #elif defined(_SC_AVPHYS_PAGES)
1086 return ((wxMemorySize
)sysconf(_SC_AVPHYS_PAGES
))*sysconf(_SC_PAGESIZE
);
1087 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1090 // can't find it out
1094 bool wxGetDiskSpace(const wxString
& path
, wxDiskspaceSize_t
*pTotal
, wxDiskspaceSize_t
*pFree
)
1096 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1097 // the case to "char *" is needed for AIX 4.3
1099 if ( wxStatfs((char *)(const char*)path
.fn_str(), &fs
) != 0 )
1101 wxLogSysError( wxT("Failed to get file system statistics") );
1106 // under Solaris we also have to use f_frsize field instead of f_bsize
1107 // which is in general a multiple of f_frsize
1109 wxDiskspaceSize_t blockSize
= fs
.f_frsize
;
1110 #else // HAVE_STATFS
1111 wxDiskspaceSize_t blockSize
= fs
.f_bsize
;
1112 #endif // HAVE_STATVFS/HAVE_STATFS
1116 *pTotal
= wxDiskspaceSize_t(fs
.f_blocks
) * blockSize
;
1121 *pFree
= wxDiskspaceSize_t(fs
.f_bavail
) * blockSize
;
1125 #else // !HAVE_STATFS && !HAVE_STATVFS
1127 #endif // HAVE_STATFS
1130 // ----------------------------------------------------------------------------
1132 // ----------------------------------------------------------------------------
1136 WX_DECLARE_STRING_HASH_MAP(char *, wxEnvVars
);
1138 static wxEnvVars gs_envVars
;
1140 class wxSetEnvModule
: public wxModule
1143 virtual bool OnInit() { return true; }
1144 virtual void OnExit()
1146 for ( wxEnvVars::const_iterator i
= gs_envVars
.begin();
1147 i
!= gs_envVars
.end();
1156 DECLARE_DYNAMIC_CLASS(wxSetEnvModule
)
1159 IMPLEMENT_DYNAMIC_CLASS(wxSetEnvModule
, wxModule
)
1161 #endif // USE_PUTENV
1163 bool wxGetEnv(const wxString
& var
, wxString
*value
)
1165 // wxGetenv is defined as getenv()
1166 char *p
= wxGetenv(var
);
1178 static bool wxDoSetEnv(const wxString
& variable
, const char *value
)
1180 #if defined(HAVE_SETENV)
1183 #ifdef HAVE_UNSETENV
1184 // don't test unsetenv() return value: it's void on some systems (at
1186 unsetenv(variable
.mb_str());
1189 value
= ""; // we can't pass NULL to setenv()
1193 return setenv(variable
.mb_str(), value
, 1 /* overwrite */) == 0;
1194 #elif defined(HAVE_PUTENV)
1195 wxString s
= variable
;
1197 s
<< wxT('=') << value
;
1199 // transform to ANSI
1200 const wxWX2MBbuf p
= s
.mb_str();
1202 char *buf
= (char *)malloc(strlen(p
) + 1);
1205 // store the string to free() it later
1206 wxEnvVars::iterator i
= gs_envVars
.find(variable
);
1207 if ( i
!= gs_envVars
.end() )
1212 else // this variable hadn't been set before
1214 gs_envVars
[variable
] = buf
;
1217 return putenv(buf
) == 0;
1218 #else // no way to set an env var
1223 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
1225 return wxDoSetEnv(variable
, value
.mb_str());
1228 bool wxUnsetEnv(const wxString
& variable
)
1230 return wxDoSetEnv(variable
, NULL
);
1233 // ----------------------------------------------------------------------------
1235 // ----------------------------------------------------------------------------
1237 #if wxUSE_ON_FATAL_EXCEPTION
1241 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
1245 // give the user a chance to do something special about this
1246 wxTheApp
->OnFatalException();
1252 bool wxHandleFatalExceptions(bool doit
)
1255 static bool s_savedHandlers
= false;
1256 static struct sigaction s_handlerFPE
,
1262 if ( doit
&& !s_savedHandlers
)
1264 // install the signal handler
1265 struct sigaction act
;
1267 // some systems extend it with non std fields, so zero everything
1268 memset(&act
, 0, sizeof(act
));
1270 act
.sa_handler
= wxFatalSignalHandler
;
1271 sigemptyset(&act
.sa_mask
);
1274 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
1275 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
1276 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
1277 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
1280 wxLogDebug(wxT("Failed to install our signal handler."));
1283 s_savedHandlers
= true;
1285 else if ( s_savedHandlers
)
1287 // uninstall the signal handler
1288 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1289 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1290 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1291 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1294 wxLogDebug(wxT("Failed to uninstall our signal handler."));
1297 s_savedHandlers
= false;
1299 //else: nothing to do
1304 #endif // wxUSE_ON_FATAL_EXCEPTION
1306 // ----------------------------------------------------------------------------
1307 // wxExecute support
1308 // ----------------------------------------------------------------------------
1310 int wxAppTraits::AddProcessCallback(wxEndProcessData
*data
, int fd
)
1312 // define a custom handler processing only the closure of the descriptor
1313 struct wxEndProcessFDIOHandler
: public wxFDIOHandler
1315 wxEndProcessFDIOHandler(wxEndProcessData
*data
, int fd
)
1316 : m_data(data
), m_fd(fd
)
1320 virtual void OnReadWaiting()
1322 wxFDIODispatcher::Get()->UnregisterFD(m_fd
);
1325 wxHandleProcessTermination(m_data
);
1330 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1331 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1333 wxEndProcessData
* const m_data
;
1337 wxFDIODispatcher::Get()->RegisterFD
1340 new wxEndProcessFDIOHandler(data
, fd
),
1343 return fd
; // unused, but return something unique for the tag
1346 bool wxAppTraits::CheckForRedirectedIO(wxExecuteData
& execData
)
1348 #if HAS_PIPE_STREAMS
1351 if ( execData
.bufOut
&& execData
.bufOut
->Update() )
1354 if ( execData
.bufErr
&& execData
.bufErr
->Update() )
1358 #else // !HAS_PIPE_STREAMS
1359 wxUnusedVar(execData
);
1362 #endif // HAS_PIPE_STREAMS/!HAS_PIPE_STREAMS
1365 // helper classes/functions used by WaitForChild()
1369 // convenient base class for IO handlers which are registered for read
1370 // notifications only and which also stores the FD we're reading from
1372 // the derived classes still have to implement OnReadWaiting()
1373 class wxReadFDIOHandler
: public wxFDIOHandler
1376 wxReadFDIOHandler(wxFDIODispatcher
& disp
, int fd
) : m_fd(fd
)
1379 disp
.RegisterFD(fd
, this, wxFDIO_INPUT
);
1382 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1383 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1388 wxDECLARE_NO_COPY_CLASS(wxReadFDIOHandler
);
1391 // class for monitoring our end of the process detection pipe, simply sets a
1392 // flag when input on the pipe (which must be due to EOF) is detected
1393 class wxEndHandler
: public wxReadFDIOHandler
1396 wxEndHandler(wxFDIODispatcher
& disp
, int fd
)
1397 : wxReadFDIOHandler(disp
, fd
)
1399 m_terminated
= false;
1402 bool Terminated() const { return m_terminated
; }
1404 virtual void OnReadWaiting() { m_terminated
= true; }
1409 wxDECLARE_NO_COPY_CLASS(wxEndHandler
);
1412 #if HAS_PIPE_STREAMS
1414 // class for monitoring our ends of child stdout/err, should be constructed
1415 // with the FD and stream from wxExecuteData and will do nothing if they're
1418 // unlike wxEndHandler this class registers itself with the provided dispatcher
1419 class wxRedirectedIOHandler
: public wxReadFDIOHandler
1422 wxRedirectedIOHandler(wxFDIODispatcher
& disp
,
1424 wxStreamTempInputBuffer
*buf
)
1425 : wxReadFDIOHandler(disp
, fd
),
1430 virtual void OnReadWaiting()
1436 wxStreamTempInputBuffer
* const m_buf
;
1438 wxDECLARE_NO_COPY_CLASS(wxRedirectedIOHandler
);
1441 #endif // HAS_PIPE_STREAMS
1443 // helper function which calls waitpid() and analyzes the result
1444 int DoWaitForChild(int pid
, int flags
= 0)
1446 wxASSERT_MSG( pid
> 0, "invalid PID" );
1450 // loop while we're getting EINTR
1453 rc
= waitpid(pid
, &status
, flags
);
1455 if ( rc
!= -1 || errno
!= EINTR
)
1461 // This can only happen if the child application closes our dummy pipe
1462 // that is used to monitor its lifetime; in that case, our best bet is
1463 // to pretend the process did terminate, because otherwise wxExecute()
1464 // would hang indefinitely (OnReadWaiting() won't be called again, the
1465 // descriptor is closed now).
1466 wxLogDebug("Child process (PID %d) still alive but pipe closed so "
1467 "generating a close notification", pid
);
1469 else if ( rc
== -1 )
1471 wxLogLastError(wxString::Format("waitpid(%d)", pid
));
1473 else // child did terminate
1475 wxASSERT_MSG( rc
== pid
, "unexpected waitpid() return value" );
1477 // notice that the caller expects the exit code to be signed, e.g. -1
1478 // instead of 255 so don't assign WEXITSTATUS() to an int
1479 signed char exitcode
;
1480 if ( WIFEXITED(status
) )
1481 exitcode
= WEXITSTATUS(status
);
1482 else if ( WIFSIGNALED(status
) )
1483 exitcode
= -WTERMSIG(status
);
1486 wxLogError("Child process (PID %d) exited for unknown reason, "
1487 "status = %d", pid
, status
);
1497 } // anonymous namespace
1499 int wxAppTraits::WaitForChild(wxExecuteData
& execData
)
1501 if ( !(execData
.flags
& wxEXEC_SYNC
) )
1503 // asynchronous execution: just launch the process and return,
1504 // endProcData will be destroyed when it terminates (currently we leak
1505 // it if the process doesn't terminate before we do and this should be
1506 // fixed but it's not a real leak so it's not really very high
1508 wxEndProcessData
*endProcData
= new wxEndProcessData
;
1509 endProcData
->process
= execData
.process
;
1510 endProcData
->pid
= execData
.pid
;
1511 endProcData
->tag
= AddProcessCallback
1514 execData
.GetEndProcReadFD()
1516 endProcData
->async
= true;
1518 return execData
.pid
;
1520 //else: synchronous execution case
1522 #if HAS_PIPE_STREAMS && wxUSE_SOCKETS
1523 wxProcess
* const process
= execData
.process
;
1524 if ( process
&& process
->IsRedirected() )
1526 // we can't simply block waiting for the child to terminate as we would
1527 // dead lock if it writes more than the pipe buffer size (typically
1528 // 4KB) bytes of output -- it would then block waiting for us to read
1529 // the data while we'd block waiting for it to terminate
1531 // so multiplex here waiting for any input from the child or closure of
1532 // the pipe used to indicate its termination
1533 wxSelectDispatcher disp
;
1535 wxEndHandler
endHandler(disp
, execData
.GetEndProcReadFD());
1537 wxRedirectedIOHandler
outHandler(disp
, execData
.fdOut
, execData
.bufOut
),
1538 errHandler(disp
, execData
.fdErr
, execData
.bufErr
);
1540 while ( !endHandler
.Terminated() )
1545 //else: no IO redirection, just block waiting for the child to exit
1546 #endif // HAS_PIPE_STREAMS
1548 return DoWaitForChild(execData
.pid
);
1551 void wxHandleProcessTermination(wxEndProcessData
*data
)
1553 data
->exitcode
= DoWaitForChild(data
->pid
, WNOHANG
);
1555 // notify user about termination if required
1556 if ( data
->process
)
1558 data
->process
->OnTerminate(data
->pid
, data
->exitcode
);
1563 // in case of asynchronous execution we don't need this data any more
1564 // after the child terminates
1567 else // sync execution
1569 // let wxExecute() know that the process has terminated