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"
25 #include "wx/process.h"
26 #include "wx/thread.h"
28 #include "wx/stream.h"
31 #include "wx/unix/execute.h"
38 #include <sys/types.h>
45 #include <fcntl.h> // for O_WRONLY and friends
46 #include <time.h> // nanosleep() and/or usleep()
47 #include <ctype.h> // isspace()
48 #include <sys/time.h> // needed for FD_SETSIZE
51 #include <sys/utsname.h> // for uname()
54 // ----------------------------------------------------------------------------
55 // conditional compilation
56 // ----------------------------------------------------------------------------
58 // many versions of Unices have this function, but it is not defined in system
59 // headers - please add your system here if it is the case for your OS.
60 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
61 #if !defined(HAVE_USLEEP) && \
62 (defined(__SUN__) && !defined(__SunOs_5_6) && \
63 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
64 defined(__osf__) || defined(__EMX__)
68 int usleep(unsigned int usec
);
71 /* I copied this from the XFree86 diffs. AV. */
72 #define INCL_DOSPROCESS
74 inline void usleep(unsigned long delay
)
76 DosSleep(delay
? (delay
/1000l) : 1l);
79 void usleep(unsigned long usec
);
81 #endif // Sun/EMX/Something else
85 #endif // Unices without usleep()
87 // ============================================================================
89 // ============================================================================
91 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
95 void wxSleep(int nSecs
)
100 void wxUsleep(unsigned long milliseconds
)
102 #if defined(HAVE_NANOSLEEP)
104 tmReq
.tv_sec
= (time_t)(milliseconds
/ 1000);
105 tmReq
.tv_nsec
= (milliseconds
% 1000) * 1000 * 1000;
107 // we're not interested in remaining time nor in return value
108 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
109 #elif defined(HAVE_USLEEP)
110 // uncomment this if you feel brave or if you are sure that your version
111 // of Solaris has a safe usleep() function but please notice that usleep()
112 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
113 // documented as MT-Safe
114 #if defined(__SUN__) && wxUSE_THREADS
115 #error "usleep() cannot be used in MT programs under Solaris."
118 usleep(milliseconds
* 1000); // usleep(3) wants microseconds
119 #elif defined(HAVE_SLEEP)
120 // under BeOS sleep() takes seconds (what about other platforms, if any?)
121 sleep(milliseconds
* 1000);
122 #else // !sleep function
123 #error "usleep() or nanosleep() function required for wxUsleep"
124 #endif // sleep function
127 // ----------------------------------------------------------------------------
128 // process management
129 // ----------------------------------------------------------------------------
131 int wxKill(long pid
, wxSignal sig
)
133 return kill((pid_t
)pid
, (int)sig
);
136 #define WXEXECUTE_NARGS 127
138 long wxExecute( const wxString
& command
, bool sync
, wxProcess
*process
)
140 wxCHECK_MSG( !command
.IsEmpty(), 0, wxT("can't exec empty command") );
143 wxChar
*argv
[WXEXECUTE_NARGS
];
145 const wxChar
*cptr
= command
.c_str();
146 wxChar quotechar
= wxT('\0'); // is arg quoted?
147 bool escaped
= FALSE
;
149 // split the command line in arguments
153 quotechar
= wxT('\0');
155 // eat leading whitespace:
156 while ( wxIsspace(*cptr
) )
159 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
164 if ( *cptr
== wxT('\\') && ! escaped
)
171 // all other characters:
175 // have we reached the end of the argument?
176 if ( (*cptr
== quotechar
&& ! escaped
)
177 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
178 || *cptr
== wxT('\0') )
180 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
181 wxT("too many arguments in wxExecute") );
183 argv
[argc
] = new wxChar
[argument
.length() + 1];
184 wxStrcpy(argv
[argc
], argument
.c_str());
187 // if not at end of buffer, swallow last character:
191 break; // done with this one, start over
197 // do execute the command
198 long lRc
= wxExecute(argv
, sync
, process
);
203 delete [] argv
[argc
++];
208 // ----------------------------------------------------------------------------
210 // ----------------------------------------------------------------------------
212 static wxString
wxMakeShellCommand(const wxString
& command
)
217 // just an interactive shell
222 // execute command in a shell
223 cmd
<< _T("/bin/sh -c '") << command
<< _T('\'');
229 bool wxShell(const wxString
& command
)
231 return wxExecute(wxMakeShellCommand(command
), TRUE
/* sync */) == 0;
234 bool wxShell(const wxString
& command
, wxArrayString
& output
)
236 wxCHECK_MSG( !!command
, FALSE
, _T("can't exec shell non interactively") );
238 return wxExecute(wxMakeShellCommand(command
), output
);
243 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
245 int pid
= (proc_data
->pid
> 0) ? proc_data
->pid
: -(proc_data
->pid
);
247 // waitpid is POSIX so should be available everywhere, however on older
248 // systems wait() might be used instead in a loop (until the right pid
253 // wait for child termination and if waitpid() was interrupted, try again
256 rc
= waitpid(pid
, &status
, 0);
258 while ( rc
== -1 && errno
== EINTR
);
261 if( rc
== -1 || ! (WIFEXITED(status
) || WIFSIGNALED(status
)) )
263 wxLogSysError(_("Waiting for subprocess termination failed"));
264 /* AFAIK, this can only happen if something went wrong within
265 wxGTK, i.e. due to a race condition or some serious bug.
266 After having fixed the order of statements in
267 GTK_EndProcessDetector(). (KB)
272 // notify user about termination if required
273 if (proc_data
->process
)
275 proc_data
->process
->OnTerminate(proc_data
->pid
,
276 WEXITSTATUS(status
));
279 if ( proc_data
->pid
> 0 )
285 // wxExecute() will know about it
286 proc_data
->exitcode
= status
;
295 // ----------------------------------------------------------------------------
296 // wxStream classes to support IO redirection in wxExecute
297 // ----------------------------------------------------------------------------
299 class wxProcessFileInputStream
: public wxInputStream
302 wxProcessFileInputStream(int fd
) { m_fd
= fd
; }
303 ~wxProcessFileInputStream() { close(m_fd
); }
305 virtual bool Eof() const;
308 size_t OnSysRead(void *buffer
, size_t bufsize
);
314 class wxProcessFileOutputStream
: public wxOutputStream
317 wxProcessFileOutputStream(int fd
) { m_fd
= fd
; }
318 ~wxProcessFileOutputStream() { close(m_fd
); }
321 size_t OnSysWrite(const void *buffer
, size_t bufsize
);
327 bool wxProcessFileInputStream::Eof() const
329 if ( m_lasterror
== wxSTREAM_EOF
)
332 // check if there is any input available
339 FD_SET(m_fd
, &readfds
);
340 switch ( select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
) )
343 wxLogSysError(_("Impossible to get child process input"));
350 wxFAIL_MSG(_T("unexpected select() return value"));
351 // still fall through
354 // input available: check if there is any
355 return wxInputStream::Eof();
359 size_t wxProcessFileInputStream::OnSysRead(void *buffer
, size_t bufsize
)
361 int ret
= read(m_fd
, buffer
, bufsize
);
364 m_lasterror
= wxSTREAM_EOF
;
366 else if ( ret
== -1 )
368 m_lasterror
= wxSTREAM_READ_ERROR
;
373 m_lasterror
= wxSTREAM_NOERROR
;
379 size_t wxProcessFileOutputStream::OnSysWrite(const void *buffer
, size_t bufsize
)
381 int ret
= write(m_fd
, buffer
, bufsize
);
384 m_lasterror
= wxSTREAM_WRITE_ERROR
;
389 m_lasterror
= wxSTREAM_NOERROR
;
395 long wxExecute(wxChar
**argv
,
399 wxCHECK_MSG( *argv
, 0, wxT("can't exec empty command") );
403 char *mb_argv
[WXEXECUTE_NARGS
];
405 while (argv
[mb_argc
])
407 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
408 mb_argv
[mb_argc
] = strdup(mb_arg
);
411 mb_argv
[mb_argc
] = (char *) NULL
;
413 // this macro will free memory we used above
414 #define ARGS_CLEANUP \
415 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
416 free(mb_argv[mb_argc])
418 // no need for cleanup
421 wxChar
**mb_argv
= argv
;
422 #endif // Unicode/ANSI
426 int end_proc_detect
[2];
427 if ( pipe(end_proc_detect
) == -1 )
429 wxLogSysError( _("Pipe creation failed") );
430 wxLogError( _("Failed to execute '%s'\n"), *argv
);
440 pipeIn
[0] = pipeIn
[1] =
441 pipeOut
[0] = pipeOut
[1] = -1;
443 if ( process
&& process
->IsRedirected() )
445 if ( pipe(pipeIn
) == -1 || pipe(pipeOut
) == -1 )
448 // free previously allocated resources
449 close(end_proc_detect
[0]);
450 close(end_proc_detect
[1]);
453 wxLogSysError( _("Pipe creation failed") );
454 wxLogError( _("Failed to execute '%s'\n"), *argv
);
469 if ( pid
== -1 ) // error?
472 close(end_proc_detect
[0]);
473 close(end_proc_detect
[1]);
480 wxLogSysError( _("Fork failed") );
486 else if ( pid
== 0 ) // we're in child
489 close(end_proc_detect
[0]); // close reading side
492 // These lines close the open file descriptors to to avoid any
493 // input/output which might block the process or irritate the user. If
494 // one wants proper IO for the subprocess, the right thing to do is to
495 // start an xterm executing it.
498 for ( int fd
= 0; fd
< FD_SETSIZE
; fd
++ )
500 if ( fd
== pipeIn
[0] || fd
== pipeOut
[1]
502 || fd
== end_proc_detect
[1]
506 // don't close this one, we still need it
510 // leave stderr opened too, it won't do any hurm
511 if ( fd
!= STDERR_FILENO
)
516 // redirect stdio and stdout
517 // (TODO: what about stderr?)
518 if ( pipeIn
[0] != -1 )
520 if ( dup2(pipeIn
[0], STDIN_FILENO
) == -1 ||
521 dup2(pipeOut
[1], STDOUT_FILENO
) == -1 )
523 wxLogSysError(_("Failed to redirect child process "
531 execvp (*mb_argv
, mb_argv
);
533 // there is no return after successful exec()
536 else // we're in parent
540 // pipe initialization: construction of the wxStreams
541 if ( process
&& process
->IsRedirected() )
543 // These two streams are relative to this process.
544 wxOutputStream
*outStream
= new wxProcessFileOutputStream(pipeIn
[1]);
545 wxInputStream
*inStream
= new wxProcessFileInputStream(pipeOut
[0]);
546 close(pipeIn
[0]); // close reading side
547 close(pipeOut
[1]); // close writing side
549 process
->SetPipeStreams(inStream
, outStream
);
553 wxEndProcessData
*data
= new wxEndProcessData
;
557 // we may have process for capturing the program output, but it's
558 // not used in wxEndProcessData in the case of sync execution
559 data
->process
= NULL
;
561 // sync execution: indicate it by negating the pid
563 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
565 close(end_proc_detect
[1]); // close writing side
570 // it will be set to 0 from GTK_EndProcessDetector
571 while (data
->pid
!= 0)
574 int exitcode
= data
->exitcode
;
580 else // async execution
582 // async execution, nothing special to do - caller will be
583 // notified about the process termination if process != NULL, data
584 // will be deleted in GTK_EndProcessDetector
585 data
->process
= process
;
587 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
589 close(end_proc_detect
[1]); // close writing side
594 wxASSERT_MSG( sync
, wxT("async execution not supported yet") );
597 if ( waitpid(pid
, &exitcode
, 0) == -1 || !WIFEXITED(exitcode
) )
599 wxLogSysError(_("Waiting for subprocess termination failed"));
611 // ----------------------------------------------------------------------------
612 // file and directory functions
613 // ----------------------------------------------------------------------------
615 const wxChar
* wxGetHomeDir( wxString
*home
)
617 *home
= wxGetUserHome( wxString() );
618 if ( home
->IsEmpty() )
621 return home
->c_str();
625 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
626 #else // just for binary compatibility -- there is no 'const' here
627 char *wxGetUserHome( const wxString
&user
)
630 struct passwd
*who
= (struct passwd
*) NULL
;
636 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
640 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
642 who
= getpwnam(wxConvertWX2MB(ptr
));
645 // We now make sure the the user exists!
648 who
= getpwuid(getuid());
653 who
= getpwnam (user
.mb_str());
656 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
659 // ----------------------------------------------------------------------------
660 // network and user id routines
661 // ----------------------------------------------------------------------------
663 // retrieve either the hostname or FQDN depending on platform (caller must
664 // check whether it's one or the other, this is why this function is for
666 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
668 wxCHECK_MSG( buf
, FALSE
, wxT("NULL pointer in wxGetHostNameInternal") );
672 // we're using uname() which is POSIX instead of less standard sysinfo()
673 #if defined(HAVE_UNAME)
675 bool ok
= uname(&uts
) != -1;
678 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
681 #elif defined(HAVE_GETHOSTNAME)
682 bool ok
= gethostname(buf
, sz
) != -1;
683 #else // no uname, no gethostname
684 wxFAIL_MSG(wxT("don't know host name for this machine"));
687 #endif // uname/gethostname
691 wxLogSysError(_("Cannot get the hostname"));
697 bool wxGetHostName(wxChar
*buf
, int sz
)
699 bool ok
= wxGetHostNameInternal(buf
, sz
);
703 // BSD systems return the FQDN, we only want the hostname, so extract
704 // it (we consider that dots are domain separators)
705 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
716 bool wxGetFullHostName(wxChar
*buf
, int sz
)
718 bool ok
= wxGetHostNameInternal(buf
, sz
);
722 if ( !wxStrchr(buf
, wxT('.')) )
724 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
727 wxLogSysError(_("Cannot get the official hostname"));
733 // the canonical name
734 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
737 //else: it's already a FQDN (BSD behaves this way)
743 bool wxGetUserId(wxChar
*buf
, int sz
)
748 if ((who
= getpwuid(getuid ())) != NULL
)
750 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
757 bool wxGetUserName(wxChar
*buf
, int sz
)
762 if ((who
= getpwuid (getuid ())) != NULL
)
764 // pw_gecos field in struct passwd is not standard
766 char *comma
= strchr(who
->pw_gecos
, ',');
768 *comma
= '\0'; // cut off non-name comment fields
769 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
770 #else // !HAVE_PW_GECOS
771 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
772 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
779 wxString
wxGetOsDescription()
781 #ifndef WXWIN_OS_DESCRIPTION
782 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
784 return WXWIN_OS_DESCRIPTION
;
788 // ----------------------------------------------------------------------------
789 // error and debug output routines (deprecated, use wxLog)
790 // ----------------------------------------------------------------------------
792 void wxDebugMsg( const char *format
, ... )
795 va_start( ap
, format
);
796 vfprintf( stderr
, format
, ap
);
801 void wxError( const wxString
&msg
, const wxString
&title
)
803 wxFprintf( stderr
, _("Error ") );
804 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
805 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
806 wxFprintf( stderr
, wxT(".\n") );
809 void wxFatalError( const wxString
&msg
, const wxString
&title
)
811 wxFprintf( stderr
, _("Error ") );
812 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
813 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
814 wxFprintf( stderr
, wxT(".\n") );
815 exit(3); // the same exit code as for abort()