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"
39 #include <sys/types.h>
46 #include <fcntl.h> // for O_WRONLY and friends
47 #include <time.h> // nanosleep() and/or usleep()
48 #include <ctype.h> // isspace()
49 #include <sys/time.h> // needed for FD_SETSIZE
52 #include <sys/utsname.h> // for uname()
55 // ----------------------------------------------------------------------------
56 // conditional compilation
57 // ----------------------------------------------------------------------------
59 // many versions of Unices have this function, but it is not defined in system
60 // headers - please add your system here if it is the case for your OS.
61 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
62 #if !defined(HAVE_USLEEP) && \
63 (defined(__SUN__) && !defined(__SunOs_5_6) && \
64 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
65 defined(__osf__) || defined(__EMX__)
69 int usleep(unsigned int usec
);
72 /* I copied this from the XFree86 diffs. AV. */
73 #define INCL_DOSPROCESS
75 inline void usleep(unsigned long delay
)
77 DosSleep(delay
? (delay
/1000l) : 1l);
80 void usleep(unsigned long usec
);
82 #endif // Sun/EMX/Something else
86 #endif // Unices without usleep()
88 // ============================================================================
90 // ============================================================================
92 // ----------------------------------------------------------------------------
94 // ----------------------------------------------------------------------------
96 void wxSleep(int nSecs
)
101 void wxUsleep(unsigned long milliseconds
)
103 #if defined(HAVE_NANOSLEEP)
105 tmReq
.tv_sec
= (time_t)(milliseconds
/ 1000);
106 tmReq
.tv_nsec
= (milliseconds
% 1000) * 1000 * 1000;
108 // we're not interested in remaining time nor in return value
109 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
110 #elif defined(HAVE_USLEEP)
111 // uncomment this if you feel brave or if you are sure that your version
112 // of Solaris has a safe usleep() function but please notice that usleep()
113 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
114 // documented as MT-Safe
115 #if defined(__SUN__) && wxUSE_THREADS
116 #error "usleep() cannot be used in MT programs under Solaris."
119 usleep(milliseconds
* 1000); // usleep(3) wants microseconds
120 #elif defined(HAVE_SLEEP)
121 // under BeOS sleep() takes seconds (what about other platforms, if any?)
122 sleep(milliseconds
* 1000);
123 #else // !sleep function
124 #error "usleep() or nanosleep() function required for wxUsleep"
125 #endif // sleep function
128 // ----------------------------------------------------------------------------
129 // process management
130 // ----------------------------------------------------------------------------
132 int wxKill(long pid
, wxSignal sig
)
134 return kill((pid_t
)pid
, (int)sig
);
137 #define WXEXECUTE_NARGS 127
139 long wxExecute( const wxString
& command
, bool sync
, wxProcess
*process
)
141 wxCHECK_MSG( !command
.IsEmpty(), 0, wxT("can't exec empty command") );
144 wxChar
*argv
[WXEXECUTE_NARGS
];
146 const wxChar
*cptr
= command
.c_str();
147 wxChar quotechar
= wxT('\0'); // is arg quoted?
148 bool escaped
= FALSE
;
150 // split the command line in arguments
154 quotechar
= wxT('\0');
156 // eat leading whitespace:
157 while ( wxIsspace(*cptr
) )
160 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
165 if ( *cptr
== wxT('\\') && ! escaped
)
172 // all other characters:
176 // have we reached the end of the argument?
177 if ( (*cptr
== quotechar
&& ! escaped
)
178 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
179 || *cptr
== wxT('\0') )
181 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
182 wxT("too many arguments in wxExecute") );
184 argv
[argc
] = new wxChar
[argument
.length() + 1];
185 wxStrcpy(argv
[argc
], argument
.c_str());
188 // if not at end of buffer, swallow last character:
192 break; // done with this one, start over
198 // do execute the command
199 long lRc
= wxExecute(argv
, sync
, process
);
204 delete [] argv
[argc
++];
209 // ----------------------------------------------------------------------------
211 // ----------------------------------------------------------------------------
213 static wxString
wxMakeShellCommand(const wxString
& command
)
218 // just an interactive shell
223 // execute command in a shell
224 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
230 bool wxShell(const wxString
& command
)
232 return wxExecute(wxMakeShellCommand(command
), TRUE
/* sync */) == 0;
235 bool wxShell(const wxString
& command
, wxArrayString
& output
)
237 wxCHECK_MSG( !!command
, FALSE
, _T("can't exec shell non interactively") );
239 return wxExecute(wxMakeShellCommand(command
), output
);
244 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
246 int pid
= (proc_data
->pid
> 0) ? proc_data
->pid
: -(proc_data
->pid
);
248 // waitpid is POSIX so should be available everywhere, however on older
249 // systems wait() might be used instead in a loop (until the right pid
254 // wait for child termination and if waitpid() was interrupted, try again
257 rc
= waitpid(pid
, &status
, 0);
259 while ( rc
== -1 && errno
== EINTR
);
262 if( rc
== -1 || ! (WIFEXITED(status
) || WIFSIGNALED(status
)) )
264 wxLogSysError(_("Waiting for subprocess termination failed"));
265 /* AFAIK, this can only happen if something went wrong within
266 wxGTK, i.e. due to a race condition or some serious bug.
267 After having fixed the order of statements in
268 GTK_EndProcessDetector(). (KB)
273 // notify user about termination if required
274 if (proc_data
->process
)
276 proc_data
->process
->OnTerminate(proc_data
->pid
,
277 WEXITSTATUS(status
));
280 if ( proc_data
->pid
> 0 )
286 // wxExecute() will know about it
287 proc_data
->exitcode
= status
;
296 // ----------------------------------------------------------------------------
297 // wxStream classes to support IO redirection in wxExecute
298 // ----------------------------------------------------------------------------
300 class wxProcessFileInputStream
: public wxInputStream
303 wxProcessFileInputStream(int fd
) { m_fd
= fd
; }
304 ~wxProcessFileInputStream() { close(m_fd
); }
306 virtual bool Eof() const;
309 size_t OnSysRead(void *buffer
, size_t bufsize
);
315 class wxProcessFileOutputStream
: public wxOutputStream
318 wxProcessFileOutputStream(int fd
) { m_fd
= fd
; }
319 ~wxProcessFileOutputStream() { close(m_fd
); }
322 size_t OnSysWrite(const void *buffer
, size_t bufsize
);
328 bool wxProcessFileInputStream::Eof() const
330 if ( m_lasterror
== wxSTREAM_EOF
)
333 // check if there is any input available
340 FD_SET(m_fd
, &readfds
);
341 switch ( select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
344 wxLogSysError(_("Impossible to get child process input"));
351 wxFAIL_MSG(_T("unexpected select() return value"));
352 // still fall through
355 // input available: check if there is any
356 return wxInputStream::Eof();
360 size_t wxProcessFileInputStream::OnSysRead(void *buffer
, size_t bufsize
)
362 int ret
= read(m_fd
, buffer
, bufsize
);
365 m_lasterror
= wxSTREAM_EOF
;
367 else if ( ret
== -1 )
369 m_lasterror
= wxSTREAM_READ_ERROR
;
374 m_lasterror
= wxSTREAM_NOERROR
;
380 size_t wxProcessFileOutputStream::OnSysWrite(const void *buffer
, size_t bufsize
)
382 int ret
= write(m_fd
, buffer
, bufsize
);
385 m_lasterror
= wxSTREAM_WRITE_ERROR
;
390 m_lasterror
= wxSTREAM_NOERROR
;
396 long wxExecute(wxChar
**argv
,
400 wxCHECK_MSG( *argv
, 0, wxT("can't exec empty command") );
404 char *mb_argv
[WXEXECUTE_NARGS
];
406 while (argv
[mb_argc
])
408 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
409 mb_argv
[mb_argc
] = strdup(mb_arg
);
412 mb_argv
[mb_argc
] = (char *) NULL
;
414 // this macro will free memory we used above
415 #define ARGS_CLEANUP \
416 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
417 free(mb_argv[mb_argc])
419 // no need for cleanup
422 wxChar
**mb_argv
= argv
;
423 #endif // Unicode/ANSI
427 int end_proc_detect
[2];
428 if ( pipe(end_proc_detect
) == -1 )
430 wxLogSysError( _("Pipe creation failed") );
431 wxLogError( _("Failed to execute '%s'\n"), *argv
);
441 pipeIn
[0] = pipeIn
[1] =
442 pipeOut
[0] = pipeOut
[1] = -1;
444 if ( process
&& process
->IsRedirected() )
446 if ( pipe(pipeIn
) == -1 || pipe(pipeOut
) == -1 )
449 // free previously allocated resources
450 close(end_proc_detect
[0]);
451 close(end_proc_detect
[1]);
454 wxLogSysError( _("Pipe creation failed") );
455 wxLogError( _("Failed to execute '%s'\n"), *argv
);
470 if ( pid
== -1 ) // error?
473 close(end_proc_detect
[0]);
474 close(end_proc_detect
[1]);
481 wxLogSysError( _("Fork failed") );
487 else if ( pid
== 0 ) // we're in child
490 close(end_proc_detect
[0]); // close reading side
493 // These lines close the open file descriptors to to avoid any
494 // input/output which might block the process or irritate the user. If
495 // one wants proper IO for the subprocess, the right thing to do is to
496 // start an xterm executing it.
499 for ( int fd
= 0; fd
< FD_SETSIZE
; fd
++ )
501 if ( fd
== pipeIn
[0] || fd
== pipeOut
[1]
503 || fd
== end_proc_detect
[1]
507 // don't close this one, we still need it
511 // leave stderr opened too, it won't do any hurm
512 if ( fd
!= STDERR_FILENO
)
517 // redirect stdio and stdout
518 // (TODO: what about stderr?)
519 if ( pipeIn
[0] != -1 )
521 if ( dup2(pipeIn
[0], STDIN_FILENO
) == -1 ||
522 dup2(pipeOut
[1], STDOUT_FILENO
) == -1 )
524 wxLogSysError(_("Failed to redirect child process "
532 execvp (*mb_argv
, mb_argv
);
534 // there is no return after successful exec()
537 else // we're in parent
541 // pipe initialization: construction of the wxStreams
542 if ( process
&& process
->IsRedirected() )
544 // These two streams are relative to this process.
545 wxOutputStream
*outStream
= new wxProcessFileOutputStream(pipeIn
[1]);
546 wxInputStream
*inStream
= new wxProcessFileInputStream(pipeOut
[0]);
547 close(pipeIn
[0]); // close reading side
548 close(pipeOut
[1]); // close writing side
550 process
->SetPipeStreams(inStream
, outStream
);
554 wxEndProcessData
*data
= new wxEndProcessData
;
558 // we may have process for capturing the program output, but it's
559 // not used in wxEndProcessData in the case of sync execution
560 data
->process
= NULL
;
562 // sync execution: indicate it by negating the pid
564 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
566 close(end_proc_detect
[1]); // close writing side
571 // it will be set to 0 from GTK_EndProcessDetector
572 while (data
->pid
!= 0)
575 int exitcode
= data
->exitcode
;
581 else // async execution
583 // async execution, nothing special to do - caller will be
584 // notified about the process termination if process != NULL, data
585 // will be deleted in GTK_EndProcessDetector
586 data
->process
= process
;
588 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
590 close(end_proc_detect
[1]); // close writing side
595 wxASSERT_MSG( sync
, wxT("async execution not supported yet") );
598 if ( waitpid(pid
, &exitcode
, 0) == -1 || !WIFEXITED(exitcode
) )
600 wxLogSysError(_("Waiting for subprocess termination failed"));
612 // ----------------------------------------------------------------------------
613 // file and directory functions
614 // ----------------------------------------------------------------------------
616 const wxChar
* wxGetHomeDir( wxString
*home
)
618 *home
= wxGetUserHome( wxString() );
619 if ( home
->IsEmpty() )
622 return home
->c_str();
626 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
627 #else // just for binary compatibility -- there is no 'const' here
628 char *wxGetUserHome( const wxString
&user
)
631 struct passwd
*who
= (struct passwd
*) NULL
;
637 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
641 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
643 who
= getpwnam(wxConvertWX2MB(ptr
));
646 // We now make sure the the user exists!
649 who
= getpwuid(getuid());
654 who
= getpwnam (user
.mb_str());
657 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
660 // ----------------------------------------------------------------------------
661 // network and user id routines
662 // ----------------------------------------------------------------------------
664 // retrieve either the hostname or FQDN depending on platform (caller must
665 // check whether it's one or the other, this is why this function is for
667 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
669 wxCHECK_MSG( buf
, FALSE
, wxT("NULL pointer in wxGetHostNameInternal") );
673 // we're using uname() which is POSIX instead of less standard sysinfo()
674 #if defined(HAVE_UNAME)
676 bool ok
= uname(&uts
) != -1;
679 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
682 #elif defined(HAVE_GETHOSTNAME)
683 bool ok
= gethostname(buf
, sz
) != -1;
684 #else // no uname, no gethostname
685 wxFAIL_MSG(wxT("don't know host name for this machine"));
688 #endif // uname/gethostname
692 wxLogSysError(_("Cannot get the hostname"));
698 bool wxGetHostName(wxChar
*buf
, int sz
)
700 bool ok
= wxGetHostNameInternal(buf
, sz
);
704 // BSD systems return the FQDN, we only want the hostname, so extract
705 // it (we consider that dots are domain separators)
706 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
717 bool wxGetFullHostName(wxChar
*buf
, int sz
)
719 bool ok
= wxGetHostNameInternal(buf
, sz
);
723 if ( !wxStrchr(buf
, wxT('.')) )
725 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
728 wxLogSysError(_("Cannot get the official hostname"));
734 // the canonical name
735 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
738 //else: it's already a FQDN (BSD behaves this way)
744 bool wxGetUserId(wxChar
*buf
, int sz
)
749 if ((who
= getpwuid(getuid ())) != NULL
)
751 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
758 bool wxGetUserName(wxChar
*buf
, int sz
)
763 if ((who
= getpwuid (getuid ())) != NULL
)
765 // pw_gecos field in struct passwd is not standard
767 char *comma
= strchr(who
->pw_gecos
, ',');
769 *comma
= '\0'; // cut off non-name comment fields
770 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
771 #else // !HAVE_PW_GECOS
772 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
773 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
780 wxString
wxGetOsDescription()
782 #ifndef WXWIN_OS_DESCRIPTION
783 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
785 return WXWIN_OS_DESCRIPTION
;
789 // ----------------------------------------------------------------------------
791 // ----------------------------------------------------------------------------
793 #if wxUSE_ON_FATAL_EXCEPTION
797 static void wxFatalSignalHandler(int signal
)
801 // give the user a chance to do something special about this
802 wxTheApp
->OnFatalException();
808 bool wxHandleFatalExceptions(bool doit
)
811 static bool s_savedHandlers
= FALSE
;
812 static struct sigaction s_handlerFPE
,
818 if ( doit
&& !s_savedHandlers
)
820 // install the signal handler
821 struct sigaction act
;
823 // some systems extend it with non std fields, so zero everything
824 memset(&act
, 0, sizeof(act
));
826 act
.sa_handler
= wxFatalSignalHandler
;
827 sigemptyset(&act
.sa_mask
);
830 ok
&= sigaction(SIGFPE
, &act
, &s_handlerFPE
) == 0;
831 ok
&= sigaction(SIGILL
, &act
, &s_handlerILL
) == 0;
832 ok
&= sigaction(SIGBUS
, &act
, &s_handlerBUS
) == 0;
833 ok
&= sigaction(SIGSEGV
, &act
, &s_handlerSEGV
) == 0;
836 wxLogDebug(_T("Failed to install our signal handler."));
839 s_savedHandlers
= TRUE
;
841 else if ( s_savedHandlers
)
843 // uninstall the signal handler
844 ok
&= sigaction(SIGFPE
, &s_handlerFPE
, NULL
) == 0;
845 ok
&= sigaction(SIGILL
, &s_handlerILL
, NULL
) == 0;
846 ok
&= sigaction(SIGBUS
, &s_handlerBUS
, NULL
) == 0;
847 ok
&= sigaction(SIGSEGV
, &s_handlerSEGV
, NULL
) == 0;
850 wxLogDebug(_T("Failed to uninstall our signal handler."));
853 s_savedHandlers
= FALSE
;
855 //else: nothing to do
860 #endif // wxUSE_ON_FATAL_EXCEPTION
862 // ----------------------------------------------------------------------------
863 // error and debug output routines (deprecated, use wxLog)
864 // ----------------------------------------------------------------------------
866 void wxDebugMsg( const char *format
, ... )
869 va_start( ap
, format
);
870 vfprintf( stderr
, format
, ap
);
875 void wxError( const wxString
&msg
, const wxString
&title
)
877 wxFprintf( stderr
, _("Error ") );
878 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
879 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
880 wxFprintf( stderr
, wxT(".\n") );
883 void wxFatalError( const wxString
&msg
, const wxString
&title
)
885 wxFprintf( stderr
, _("Error ") );
886 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
887 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
888 wxFprintf( stderr
, wxT(".\n") );
889 exit(3); // the same exit code as for abort()