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 bool wxShell(const wxString
& command
)
212 cmd
.Printf(wxT("xterm -e %s"), command
.c_str());
216 return wxExecute(cmd
) != 0;
221 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
223 int pid
= (proc_data
->pid
> 0) ? proc_data
->pid
: -(proc_data
->pid
);
225 // waitpid is POSIX so should be available everywhere, however on older
226 // systems wait() might be used instead in a loop (until the right pid
231 // wait for child termination and if waitpid() was interrupted, try again
234 rc
= waitpid(pid
, &status
, 0);
236 while ( rc
== -1 && errno
== EINTR
);
239 if( rc
== -1 || ! (WIFEXITED(status
) || WIFSIGNALED(status
)) )
241 wxLogSysError(_("Waiting for subprocess termination failed"));
242 /* AFAIK, this can only happen if something went wrong within
243 wxGTK, i.e. due to a race condition or some serious bug.
244 After having fixed the order of statements in
245 GTK_EndProcessDetector(). (KB)
250 // notify user about termination if required
251 if (proc_data
->process
)
253 proc_data
->process
->OnTerminate(proc_data
->pid
,
254 WEXITSTATUS(status
));
257 if ( proc_data
->pid
> 0 )
263 // wxExecute() will know about it
264 proc_data
->exitcode
= status
;
274 #define WXUNUSED_UNLESS_GUI(p) p
276 #define WXUNUSED_UNLESS_GUI(p)
279 // New wxStream classes to clean up the data when the process terminates
282 class wxProcessFileInputStream
: public wxInputStream
{
284 wxProcessFileInputStream(int fd
);
285 ~wxProcessFileInputStream();
288 size_t OnSysRead(void *buffer
, size_t bufsize
);
294 class wxProcessFileOutputStream
: public wxOutputStream
{
296 wxProcessFileOutputStream(int fd
);
297 ~wxProcessFileOutputStream();
300 size_t OnSysWrite(const void *buffer
, size_t bufsize
);
306 wxProcessFileInputStream::wxProcessFileInputStream(int fd
)
311 wxProcessFileInputStream::~wxProcessFileInputStream()
316 size_t wxProcessFileInputStream::OnSysRead(void *buffer
, size_t bufsize
)
320 ret
= read(m_fd
, buffer
, bufsize
);
321 m_lasterror
= wxSTREAM_NOERROR
;
323 m_lasterror
= wxSTREAM_EOF
;
325 m_lasterror
= wxSTREAM_READ_ERROR
;
331 wxProcessFileOutputStream::wxProcessFileOutputStream(int fd
)
336 wxProcessFileOutputStream::~wxProcessFileOutputStream()
341 size_t wxProcessFileOutputStream::OnSysWrite(const void *buffer
, size_t bufsize
)
345 ret
= write(m_fd
, buffer
, bufsize
);
346 m_lasterror
= wxSTREAM_NOERROR
;
348 m_lasterror
= wxSTREAM_WRITE_ERROR
;
356 long wxExecute(wxChar
**argv
,
358 wxProcess
* WXUNUSED_UNLESS_GUI(process
))
360 wxCHECK_MSG( *argv
, 0, wxT("can't exec empty command") );
364 char *mb_argv
[WXEXECUTE_NARGS
];
366 while (argv
[mb_argc
])
368 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
369 mb_argv
[mb_argc
] = strdup(mb_arg
);
372 mb_argv
[mb_argc
] = (char *) NULL
;
374 // this macro will free memory we used above
375 #define ARGS_CLEANUP \
376 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
377 free(mb_argv[mb_argc])
379 // no need for cleanup
382 wxChar
**mb_argv
= argv
;
383 #endif // Unicode/ANSI
387 int end_proc_detect
[2];
388 if (pipe(end_proc_detect
) == -1)
390 wxLogSysError( _("Pipe creation failed") );
399 int in_pipe
[2] = { -1, -1 };
400 int out_pipe
[2] = { -1, -1 };
401 // Only asynchronous mode is interresting
402 if (!sync
&& process
&& process
->NeedPipe())
404 if (pipe(in_pipe
) == -1 || pipe(out_pipe
) == -1)
407 close(end_proc_detect
[0]);
408 close(end_proc_detect
[1]);
409 wxLogSysError( _("Pipe creation failed (Console pipes)") );
427 close(end_proc_detect
[0]);
428 close(end_proc_detect
[1]);
434 wxLogSysError( _("Fork failed") );
444 close(end_proc_detect
[0]); // close reading side
447 // These three lines close the open file descriptors to to avoid any
448 // input/output which might block the process or irritate the user. If
449 // one wants proper IO for the subprocess, the right thing to do is
450 // to start an xterm executing it.
453 // leave stderr opened, it won't do any hurm
454 for ( int fd
= 0; fd
< FD_SETSIZE
; fd
++ )
457 if ( fd
== end_proc_detect
[1] || fd
== in_pipe
[0] || fd
== out_pipe
[1] )
461 if ( fd
!= STDERR_FILENO
)
466 // Fake a console by duplicating pipes
468 if (in_pipe
[0] != -1) {
469 dup2(in_pipe
[0], STDIN_FILENO
);
470 dup2(out_pipe
[1], STDOUT_FILENO
);
477 close(STDERR_FILENO
);
479 // some programs complain about stderr not being open, so redirect
481 open("/dev/null", O_RDONLY
); // stdin
482 open("/dev/null", O_WRONLY
); // stdout
483 open("/dev/null", O_WRONLY
); // stderr
486 execvp (*mb_argv
, mb_argv
);
488 // there is no return after successful exec()
489 wxFprintf(stderr
, _("Can't execute '%s'\n"), *argv
);
496 wxEndProcessData
*data
= new wxEndProcessData
;
502 wxASSERT_MSG( !process
, wxT("wxProcess param ignored for sync exec") );
503 data
->process
= NULL
;
505 // sync execution: indicate it by negating the pid
507 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
509 close(end_proc_detect
[1]); // close writing side
511 // it will be set to 0 from GTK_EndProcessDetector
512 while (data
->pid
!= 0)
515 int exitcode
= data
->exitcode
;
523 // pipe initialization: construction of the wxStreams
524 if (process
&& process
->NeedPipe()) {
525 // These two streams are relative to this process.
526 wxOutputStream
*my_output_stream
;
527 wxInputStream
*my_input_stream
;
529 my_output_stream
= new wxProcessFileOutputStream(in_pipe
[1]);
530 my_input_stream
= new wxProcessFileInputStream(out_pipe
[0]);
531 close(in_pipe
[0]); // close reading side
532 close(out_pipe
[1]); // close writing side
534 process
->SetPipeStreams(my_input_stream
, my_output_stream
);
537 // async execution, nothing special to do - caller will be
538 // notified about the process termination if process != NULL, data
539 // will be deleted in GTK_EndProcessDetector
540 data
->process
= process
;
542 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
544 close(end_proc_detect
[1]); // close writing side
549 wxASSERT_MSG( sync
, wxT("async execution not supported yet") );
552 if ( waitpid(pid
, &exitcode
, 0) == -1 || !WIFEXITED(exitcode
) )
554 wxLogSysError(_("Waiting for subprocess termination failed"));
565 // ----------------------------------------------------------------------------
566 // file and directory functions
567 // ----------------------------------------------------------------------------
569 const wxChar
* wxGetHomeDir( wxString
*home
)
571 *home
= wxGetUserHome( wxString() );
572 if ( home
->IsEmpty() )
575 return home
->c_str();
579 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
580 #else // just for binary compatibility -- there is no 'const' here
581 char *wxGetUserHome( const wxString
&user
)
584 struct passwd
*who
= (struct passwd
*) NULL
;
590 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
594 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
596 who
= getpwnam(wxConvertWX2MB(ptr
));
599 // We now make sure the the user exists!
602 who
= getpwuid(getuid());
607 who
= getpwnam (user
.mb_str());
610 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
613 // ----------------------------------------------------------------------------
614 // network and user id routines
615 // ----------------------------------------------------------------------------
617 // retrieve either the hostname or FQDN depending on platform (caller must
618 // check whether it's one or the other, this is why this function is for
620 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
622 wxCHECK_MSG( buf
, FALSE
, wxT("NULL pointer in wxGetHostNameInternal") );
626 // we're using uname() which is POSIX instead of less standard sysinfo()
627 #if defined(HAVE_UNAME)
629 bool ok
= uname(&uts
) != -1;
632 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
635 #elif defined(HAVE_GETHOSTNAME)
636 bool ok
= gethostname(buf
, sz
) != -1;
637 #else // no uname, no gethostname
638 wxFAIL_MSG(wxT("don't know host name for this machine"));
641 #endif // uname/gethostname
645 wxLogSysError(_("Cannot get the hostname"));
651 bool wxGetHostName(wxChar
*buf
, int sz
)
653 bool ok
= wxGetHostNameInternal(buf
, sz
);
657 // BSD systems return the FQDN, we only want the hostname, so extract
658 // it (we consider that dots are domain separators)
659 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
670 bool wxGetFullHostName(wxChar
*buf
, int sz
)
672 bool ok
= wxGetHostNameInternal(buf
, sz
);
676 if ( !wxStrchr(buf
, wxT('.')) )
678 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
681 wxLogSysError(_("Cannot get the official hostname"));
687 // the canonical name
688 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
691 //else: it's already a FQDN (BSD behaves this way)
697 bool wxGetUserId(wxChar
*buf
, int sz
)
702 if ((who
= getpwuid(getuid ())) != NULL
)
704 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
711 bool wxGetUserName(wxChar
*buf
, int sz
)
716 if ((who
= getpwuid (getuid ())) != NULL
)
718 // pw_gecos field in struct passwd is not standard
720 char *comma
= strchr(who
->pw_gecos
, ',');
722 *comma
= '\0'; // cut off non-name comment fields
723 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
724 #else // !HAVE_PW_GECOS
725 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
726 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
733 wxString
wxGetOsDescription()
735 #ifndef WXWIN_OS_DESCRIPTION
736 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
738 return WXWIN_OS_DESCRIPTION
;
742 // ----------------------------------------------------------------------------
743 // error and debug output routines (deprecated, use wxLog)
744 // ----------------------------------------------------------------------------
746 void wxDebugMsg( const char *format
, ... )
749 va_start( ap
, format
);
750 vfprintf( stderr
, format
, ap
);
755 void wxError( const wxString
&msg
, const wxString
&title
)
757 wxFprintf( stderr
, _("Error ") );
758 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
759 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
760 wxFprintf( stderr
, wxT(".\n") );
763 void wxFatalError( const wxString
&msg
, const wxString
&title
)
765 wxFprintf( stderr
, _("Error ") );
766 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
767 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
768 wxFprintf( stderr
, wxT(".\n") );
769 exit(3); // the same exit code as for abort()