1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: generic Unix implementation of many wx functions
4 // Author: Vadim Zeitlin
6 // Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 // ============================================================================
12 // ============================================================================
14 // ----------------------------------------------------------------------------
16 // ----------------------------------------------------------------------------
19 #include "wx/string.h"
26 #include "wx/process.h"
27 #include "wx/thread.h"
29 #include "wx/stream.h"
32 #include "wx/unix/execute.h"
35 // SGI signal.h defines signal handler arguments differently depending on
36 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
37 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
38 #define _LANGUAGE_C_PLUS_PLUS 1
45 #include <sys/types.h>
52 #include <fcntl.h> // for O_WRONLY and friends
53 #include <time.h> // nanosleep() and/or usleep()
54 #include <ctype.h> // isspace()
55 #include <sys/time.h> // needed for FD_SETSIZE
58 #include <sys/utsname.h> // for uname()
61 // ----------------------------------------------------------------------------
62 // conditional compilation
63 // ----------------------------------------------------------------------------
65 // many versions of Unices have this function, but it is not defined in system
66 // headers - please add your system here if it is the case for your OS.
67 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
68 #if !defined(HAVE_USLEEP) && \
69 (defined(__SUN__) && !defined(__SunOs_5_6) && \
70 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
71 defined(__osf__) || defined(__EMX__)
75 int usleep(unsigned int usec
);
78 /* I copied this from the XFree86 diffs. AV. */
79 #define INCL_DOSPROCESS
81 inline void usleep(unsigned long delay
)
83 DosSleep(delay
? (delay
/1000l) : 1l);
86 void usleep(unsigned long usec
);
88 #endif // Sun/EMX/Something else
92 #endif // Unices without usleep()
94 // ============================================================================
96 // ============================================================================
98 // ----------------------------------------------------------------------------
100 // ----------------------------------------------------------------------------
102 void wxSleep(int nSecs
)
107 void wxUsleep(unsigned long milliseconds
)
109 #if defined(HAVE_NANOSLEEP)
111 tmReq
.tv_sec
= (time_t)(milliseconds
/ 1000);
112 tmReq
.tv_nsec
= (milliseconds
% 1000) * 1000 * 1000;
114 // we're not interested in remaining time nor in return value
115 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
116 #elif defined(HAVE_USLEEP)
117 // uncomment this if you feel brave or if you are sure that your version
118 // of Solaris has a safe usleep() function but please notice that usleep()
119 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
120 // documented as MT-Safe
121 #if defined(__SUN__) && wxUSE_THREADS
122 #error "usleep() cannot be used in MT programs under Solaris."
125 usleep(milliseconds
* 1000); // usleep(3) wants microseconds
126 #elif defined(HAVE_SLEEP)
127 // under BeOS sleep() takes seconds (what about other platforms, if any?)
128 sleep(milliseconds
* 1000);
129 #else // !sleep function
130 #error "usleep() or nanosleep() function required for wxUsleep"
131 #endif // sleep function
134 // ----------------------------------------------------------------------------
135 // process management
136 // ----------------------------------------------------------------------------
138 int wxKill(long pid
, wxSignal sig
, wxKillError
*rc
)
140 int err
= kill((pid_t
)pid
, (int)sig
);
150 *rc
= wxKILL_BAD_SIGNAL
;
154 *rc
= wxKILL_ACCESS_DENIED
;
158 *rc
= wxKILL_NO_PROCESS
;
162 // this goes against Unix98 docs so log it
163 wxLogDebug(_T("unexpected kill(2) return value %d"), err
);
173 #define WXEXECUTE_NARGS 127
175 long wxExecute( const wxString
& command
, bool sync
, wxProcess
*process
)
177 wxCHECK_MSG( !command
.IsEmpty(), 0, wxT("can't exec empty command") );
180 wxChar
*argv
[WXEXECUTE_NARGS
];
182 const wxChar
*cptr
= command
.c_str();
183 wxChar quotechar
= wxT('\0'); // is arg quoted?
184 bool escaped
= FALSE
;
186 // split the command line in arguments
190 quotechar
= wxT('\0');
192 // eat leading whitespace:
193 while ( wxIsspace(*cptr
) )
196 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
201 if ( *cptr
== wxT('\\') && ! escaped
)
208 // all other characters:
212 // have we reached the end of the argument?
213 if ( (*cptr
== quotechar
&& ! escaped
)
214 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
215 || *cptr
== wxT('\0') )
217 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
218 wxT("too many arguments in wxExecute") );
220 argv
[argc
] = new wxChar
[argument
.length() + 1];
221 wxStrcpy(argv
[argc
], argument
.c_str());
224 // if not at end of buffer, swallow last character:
228 break; // done with this one, start over
234 // do execute the command
235 long lRc
= wxExecute(argv
, sync
, process
);
240 delete [] argv
[argc
++];
245 // ----------------------------------------------------------------------------
247 // ----------------------------------------------------------------------------
249 static wxString
wxMakeShellCommand(const wxString
& command
)
254 // just an interactive shell
259 // execute command in a shell
260 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
266 bool wxShell(const wxString
& command
)
268 return wxExecute(wxMakeShellCommand(command
), TRUE
/* sync */) == 0;
271 bool wxShell(const wxString
& command
, wxArrayString
& output
)
273 wxCHECK_MSG( !!command
, FALSE
, _T("can't exec shell non interactively") );
275 return wxExecute(wxMakeShellCommand(command
), output
);
280 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
282 int pid
= (proc_data
->pid
> 0) ? proc_data
->pid
: -(proc_data
->pid
);
284 // waitpid is POSIX so should be available everywhere, however on older
285 // systems wait() might be used instead in a loop (until the right pid
290 // wait for child termination and if waitpid() was interrupted, try again
293 rc
= waitpid(pid
, &status
, 0);
295 while ( rc
== -1 && errno
== EINTR
);
298 if( rc
== -1 || ! (WIFEXITED(status
) || WIFSIGNALED(status
)) )
300 wxLogSysError(_("Waiting for subprocess termination failed"));
301 /* AFAIK, this can only happen if something went wrong within
302 wxGTK, i.e. due to a race condition or some serious bug.
303 After having fixed the order of statements in
304 GTK_EndProcessDetector(). (KB)
309 // notify user about termination if required
310 if (proc_data
->process
)
312 proc_data
->process
->OnTerminate(proc_data
->pid
,
313 WEXITSTATUS(status
));
316 if ( proc_data
->pid
> 0 )
322 // wxExecute() will know about it
323 proc_data
->exitcode
= status
;
332 // ----------------------------------------------------------------------------
333 // wxStream classes to support IO redirection in wxExecute
334 // ----------------------------------------------------------------------------
336 class wxProcessFileInputStream
: public wxInputStream
339 wxProcessFileInputStream(int fd
) { m_fd
= fd
; }
340 ~wxProcessFileInputStream() { close(m_fd
); }
342 virtual bool Eof() const;
345 size_t OnSysRead(void *buffer
, size_t bufsize
);
351 class wxProcessFileOutputStream
: public wxOutputStream
354 wxProcessFileOutputStream(int fd
) { m_fd
= fd
; }
355 ~wxProcessFileOutputStream() { close(m_fd
); }
358 size_t OnSysWrite(const void *buffer
, size_t bufsize
);
364 bool wxProcessFileInputStream::Eof() const
366 if ( m_lasterror
== wxSTREAM_EOF
)
369 // check if there is any input available
376 FD_SET(m_fd
, &readfds
);
377 switch ( select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
380 wxLogSysError(_("Impossible to get child process input"));
387 wxFAIL_MSG(_T("unexpected select() return value"));
388 // still fall through
391 // input available: check if there is any
392 return wxInputStream::Eof();
396 size_t wxProcessFileInputStream::OnSysRead(void *buffer
, size_t bufsize
)
398 int ret
= read(m_fd
, buffer
, bufsize
);
401 m_lasterror
= wxSTREAM_EOF
;
403 else if ( ret
== -1 )
405 m_lasterror
= wxSTREAM_READ_ERROR
;
410 m_lasterror
= wxSTREAM_NOERROR
;
416 size_t wxProcessFileOutputStream::OnSysWrite(const void *buffer
, size_t bufsize
)
418 int ret
= write(m_fd
, buffer
, bufsize
);
421 m_lasterror
= wxSTREAM_WRITE_ERROR
;
426 m_lasterror
= wxSTREAM_NOERROR
;
432 long wxExecute(wxChar
**argv
,
436 // for the sync execution, we return -1 to indicate failure, but for async
437 // case we return 0 which is never a valid PID
439 // we define this as a macro, not a variable, to avoid compiler warnings
440 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
441 #define ERROR_RETURN_CODE ((sync) ? -1 : 0)
443 wxCHECK_MSG( *argv
, ERROR_RETURN_CODE
, wxT("can't exec empty command") );
447 char *mb_argv
[WXEXECUTE_NARGS
];
449 while (argv
[mb_argc
])
451 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
452 mb_argv
[mb_argc
] = strdup(mb_arg
);
455 mb_argv
[mb_argc
] = (char *) NULL
;
457 // this macro will free memory we used above
458 #define ARGS_CLEANUP \
459 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
460 free(mb_argv[mb_argc])
462 // no need for cleanup
465 wxChar
**mb_argv
= argv
;
466 #endif // Unicode/ANSI
470 int end_proc_detect
[2];
471 if ( pipe(end_proc_detect
) == -1 )
473 wxLogSysError( _("Pipe creation failed") );
474 wxLogError( _("Failed to execute '%s'\n"), *argv
);
478 return ERROR_RETURN_CODE
;
482 // pipes for inter process communication
483 int pipeIn
[2], // stdin
484 pipeOut
[2], // stdout
485 pipeErr
[2]; // stderr
487 pipeIn
[0] = pipeIn
[1] =
488 pipeOut
[0] = pipeOut
[1] =
489 pipeErr
[0] = pipeErr
[1] = -1;
491 if ( process
&& process
->IsRedirected() )
493 if ( pipe(pipeIn
) == -1 || pipe(pipeOut
) == -1 || pipe(pipeErr
) == -1 )
496 // free previously allocated resources
497 close(end_proc_detect
[0]);
498 close(end_proc_detect
[1]);
501 wxLogSysError( _("Pipe creation failed") );
502 wxLogError( _("Failed to execute '%s'\n"), *argv
);
506 return ERROR_RETURN_CODE
;
517 if ( pid
== -1 ) // error?
520 close(end_proc_detect
[0]);
521 close(end_proc_detect
[1]);
530 wxLogSysError( _("Fork failed") );
534 return ERROR_RETURN_CODE
;
536 else if ( pid
== 0 ) // we're in child
539 close(end_proc_detect
[0]); // close reading side
542 // These lines close the open file descriptors to to avoid any
543 // input/output which might block the process or irritate the user. If
544 // one wants proper IO for the subprocess, the right thing to do is to
545 // start an xterm executing it.
548 for ( int fd
= 0; fd
< FD_SETSIZE
; fd
++ )
550 if ( fd
== pipeIn
[0] || fd
== pipeOut
[1] || fd
== pipeErr
[1]
552 || fd
== end_proc_detect
[1]
556 // don't close this one, we still need it
560 // leave stderr opened too, it won't do any hurm
561 if ( fd
!= STDERR_FILENO
)
566 // redirect stdio, stdout and stderr
567 if ( pipeIn
[0] != -1 )
569 if ( dup2(pipeIn
[0], STDIN_FILENO
) == -1 ||
570 dup2(pipeOut
[1], STDOUT_FILENO
) == -1 ||
571 dup2(pipeErr
[1], STDERR_FILENO
) == -1 )
573 wxLogSysError(_("Failed to redirect child process input/output"));
581 execvp (*mb_argv
, mb_argv
);
583 // there is no return after successful exec()
586 else // we're in parent
590 // pipe initialization: construction of the wxStreams
591 if ( process
&& process
->IsRedirected() )
593 // These two streams are relative to this process.
594 wxOutputStream
*outStream
= new wxProcessFileOutputStream(pipeIn
[1]);
595 wxInputStream
*inStream
= new wxProcessFileInputStream(pipeOut
[0]);
596 wxInputStream
*errStream
= new wxProcessFileInputStream(pipeErr
[0]);
598 close(pipeIn
[0]); // close reading side
599 close(pipeOut
[1]); // close writing side
600 close(pipeErr
[1]); // close writing side
602 process
->SetPipeStreams(inStream
, outStream
, errStream
);
606 wxEndProcessData
*data
= new wxEndProcessData
;
610 // we may have process for capturing the program output, but it's
611 // not used in wxEndProcessData in the case of sync execution
612 data
->process
= NULL
;
614 // sync execution: indicate it by negating the pid
616 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
618 close(end_proc_detect
[1]); // close writing side
623 // it will be set to 0 from GTK_EndProcessDetector
624 while (data
->pid
!= 0)
627 int exitcode
= data
->exitcode
;
633 else // async execution
635 // async execution, nothing special to do - caller will be
636 // notified about the process termination if process != NULL, data
637 // will be deleted in GTK_EndProcessDetector
638 data
->process
= process
;
640 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
642 close(end_proc_detect
[1]); // close writing side
647 wxASSERT_MSG( sync
, wxT("async execution not supported yet") );
650 if ( waitpid(pid
, &exitcode
, 0) == -1 || !WIFEXITED(exitcode
) )
652 wxLogSysError(_("Waiting for subprocess termination failed"));
659 // VMS does not recognise exit as a return and complains about
661 // I think VMS is wrong in this
667 #undef ERROR_RETURN_CODE
670 // ----------------------------------------------------------------------------
671 // file and directory functions
672 // ----------------------------------------------------------------------------
674 const wxChar
* wxGetHomeDir( wxString
*home
)
676 *home
= wxGetUserHome( wxString() );
678 if ( home
->IsEmpty() )
682 if ( tmp
.Last() != wxT(']'))
683 if ( tmp
.Last() != wxT('/')) *home
<< wxT('/');
685 return home
->c_str();
689 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
690 #else // just for binary compatibility -- there is no 'const' here
691 char *wxGetUserHome( const wxString
&user
)
694 struct passwd
*who
= (struct passwd
*) NULL
;
700 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
704 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
706 who
= getpwnam(wxConvertWX2MB(ptr
));
709 // We now make sure the the user exists!
712 who
= getpwuid(getuid());
717 who
= getpwnam (user
.mb_str());
720 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
723 // ----------------------------------------------------------------------------
724 // network and user id routines
725 // ----------------------------------------------------------------------------
727 // retrieve either the hostname or FQDN depending on platform (caller must
728 // check whether it's one or the other, this is why this function is for
730 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
732 wxCHECK_MSG( buf
, FALSE
, wxT("NULL pointer in wxGetHostNameInternal") );
736 // we're using uname() which is POSIX instead of less standard sysinfo()
737 #if defined(HAVE_UNAME)
739 bool ok
= uname(&uts
) != -1;
742 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
745 #elif defined(HAVE_GETHOSTNAME)
746 bool ok
= gethostname(buf
, sz
) != -1;
747 #else // no uname, no gethostname
748 wxFAIL_MSG(wxT("don't know host name for this machine"));
751 #endif // uname/gethostname
755 wxLogSysError(_("Cannot get the hostname"));
761 bool wxGetHostName(wxChar
*buf
, int sz
)
763 bool ok
= wxGetHostNameInternal(buf
, sz
);
767 // BSD systems return the FQDN, we only want the hostname, so extract
768 // it (we consider that dots are domain separators)
769 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
780 bool wxGetFullHostName(wxChar
*buf
, int sz
)
782 bool ok
= wxGetHostNameInternal(buf
, sz
);
786 if ( !wxStrchr(buf
, wxT('.')) )
788 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
791 wxLogSysError(_("Cannot get the official hostname"));
797 // the canonical name
798 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
801 //else: it's already a FQDN (BSD behaves this way)
807 bool wxGetUserId(wxChar
*buf
, int sz
)
812 if ((who
= getpwuid(getuid ())) != NULL
)
814 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
821 bool wxGetUserName(wxChar
*buf
, int sz
)
826 if ((who
= getpwuid (getuid ())) != NULL
)
828 // pw_gecos field in struct passwd is not standard
830 char *comma
= strchr(who
->pw_gecos
, ',');
832 *comma
= '\0'; // cut off non-name comment fields
833 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
834 #else // !HAVE_PW_GECOS
835 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
836 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
843 wxString
wxGetOsDescription()
845 #ifndef WXWIN_OS_DESCRIPTION
846 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
848 return WXWIN_OS_DESCRIPTION
;
852 // this function returns the GUI toolkit version in GUI programs, but OS
853 // version in non-GUI ones
856 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
861 if ( sscanf(WXWIN_OS_DESCRIPTION
, "%s %d.%d", name
, &major
, &minor
) != 3 )
863 // unreckognized uname string format
877 long wxGetFreeMemory()
879 #if defined(__LINUX__)
880 // get it from /proc/meminfo
881 FILE *fp
= fopen("/proc/meminfo", "r");
887 if ( fgets(buf
, WXSIZEOF(buf
), fp
) && fgets(buf
, WXSIZEOF(buf
), fp
) )
889 long memTotal
, memUsed
;
890 sscanf(buf
, "Mem: %ld %ld %ld", &memTotal
, &memUsed
, &memFree
);
897 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
898 return sysconf(_SC_AVPHYS_PAGES
)*sysconf(_SC_PAGESIZE
);
899 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
906 // ----------------------------------------------------------------------------
908 // ----------------------------------------------------------------------------
910 bool wxGetEnv(const wxString
& var
, wxString
*value
)
912 // wxGetenv is defined as getenv()
913 wxChar
*p
= wxGetenv(var
);
925 bool wxSetEnv(const wxString
& variable
, const wxChar
*value
)
927 #if defined(HAVE_SETENV)
928 return setenv(variable
.mb_str(), value
? wxString(value
).mb_str().data()
929 : NULL
, 1 /* overwrite */) == 0;
930 #elif defined(HAVE_PUTENV)
931 wxString s
= variable
;
933 s
<< _T('=') << value
;
936 const char *p
= s
.mb_str();
938 // the string will be free()d by libc
939 char *buf
= (char *)malloc(strlen(p
) + 1);
942 return putenv(buf
) == 0;
943 #else // no way to set an env var
948 // ----------------------------------------------------------------------------
950 // ----------------------------------------------------------------------------
952 #if wxUSE_ON_FATAL_EXCEPTION
956 static void wxFatalSignalHandler(wxTYPE_SA_HANDLER
)
960 // give the user a chance to do something special about this
961 wxTheApp
->OnFatalException();
967 bool wxHandleFatalExceptions(bool doit
)
970 static bool s_savedHandlers
= FALSE
;
971 static struct sigaction s_handlerFPE
,
977 if ( doit
&& !s_savedHandlers
)
979 // install the signal handler
980 struct sigaction act
;
982 // some systems extend it with non std fields, so zero everything
983 memset(&act
, 0, sizeof(act
));
985 act
.sa_handler
= wxFatalSignalHandler
;
986 sigemptyset(&act
.sa_mask
);
989 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
990 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
991 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
992 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
995 wxLogDebug(_T("Failed to install our signal handler."));
998 s_savedHandlers
= TRUE
;
1000 else if ( s_savedHandlers
)
1002 // uninstall the signal handler
1003 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
1004 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
1005 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
1006 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
1009 wxLogDebug(_T("Failed to uninstall our signal handler."));
1012 s_savedHandlers
= FALSE
;
1014 //else: nothing to do
1019 #endif // wxUSE_ON_FATAL_EXCEPTION
1021 // ----------------------------------------------------------------------------
1022 // error and debug output routines (deprecated, use wxLog)
1023 // ----------------------------------------------------------------------------
1025 void wxDebugMsg( const char *format
, ... )
1028 va_start( ap
, format
);
1029 vfprintf( stderr
, format
, ap
);
1034 void wxError( const wxString
&msg
, const wxString
&title
)
1036 wxFprintf( stderr
, _("Error ") );
1037 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
1038 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
1039 wxFprintf( stderr
, wxT(".\n") );
1042 void wxFatalError( const wxString
&msg
, const wxString
&title
)
1044 wxFprintf( stderr
, _("Error ") );
1045 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
1046 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
1047 wxFprintf( stderr
, wxT(".\n") );
1048 exit(3); // the same exit code as for abort()