]> git.saurik.com Git - wxWidgets.git/blame - src/unix/utilsunx.cpp
better learn the operators...
[wxWidgets.git] / src / unix / utilsunx.cpp
CommitLineData
518b5d2f
VZ
1/////////////////////////////////////////////////////////////////////////////
2// Name: utilsunx.cpp
3// Purpose: generic Unix implementation of many wx functions
4// Author: Vadim Zeitlin
5// Id: $Id$
6// Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
7// Licence: wxWindows licence
8/////////////////////////////////////////////////////////////////////////////
9
10// ============================================================================
11// declarations
12// ============================================================================
13
14// ----------------------------------------------------------------------------
15// headers
16// ----------------------------------------------------------------------------
17
18#include "wx/defs.h"
19#include "wx/string.h"
20
21#include "wx/intl.h"
22#include "wx/log.h"
a37a5a73 23#include "wx/app.h"
518b5d2f
VZ
24
25#include "wx/utils.h"
26#include "wx/process.h"
bdc72a22 27#include "wx/thread.h"
518b5d2f 28
8b33ae2d
GL
29#include "wx/stream.h"
30
eadd7bd2
VZ
31#ifdef HAVE_STATFS
32 #include <sys/vfs.h>
33#endif // HAVE_STATFS
34
6dc6fda6
VZ
35#if wxUSE_GUI
36 #include "wx/unix/execute.h"
37#endif
518b5d2f 38
f6bcfd97
BP
39// SGI signal.h defines signal handler arguments differently depending on
40// whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
41#if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
42 #define _LANGUAGE_C_PLUS_PLUS 1
43#endif // SGI hack
44
518b5d2f
VZ
45#include <stdarg.h>
46#include <dirent.h>
47#include <string.h>
48#include <sys/stat.h>
49#include <sys/types.h>
50#include <unistd.h>
51#include <sys/wait.h>
52#include <pwd.h>
53#include <errno.h>
54#include <netdb.h>
55#include <signal.h>
56#include <fcntl.h> // for O_WRONLY and friends
57#include <time.h> // nanosleep() and/or usleep()
fad866f4 58#include <ctype.h> // isspace()
b12915c1 59#include <sys/time.h> // needed for FD_SETSIZE
7bcb11d3 60
0fcdf6dc 61#ifdef HAVE_UNAME
518b5d2f
VZ
62 #include <sys/utsname.h> // for uname()
63#endif // HAVE_UNAME
64
65// ----------------------------------------------------------------------------
66// conditional compilation
67// ----------------------------------------------------------------------------
68
69// many versions of Unices have this function, but it is not defined in system
70// headers - please add your system here if it is the case for your OS.
71// SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
1363811b
VZ
72#if !defined(HAVE_USLEEP) && \
73 (defined(__SUN__) && !defined(__SunOs_5_6) && \
518b5d2f 74 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
fd9811b1 75 defined(__osf__) || defined(__EMX__)
518b5d2f
VZ
76 extern "C"
77 {
1363811b
VZ
78 #ifdef __SUN__
79 int usleep(unsigned int usec);
80 #else // !Sun
bdc72a22
VZ
81 #ifdef __EMX__
82 /* I copied this from the XFree86 diffs. AV. */
83 #define INCL_DOSPROCESS
84 #include <os2.h>
85 inline void usleep(unsigned long delay)
86 {
87 DosSleep(delay ? (delay/1000l) : 1l);
88 }
89 #else // !Sun && !EMX
90 void usleep(unsigned long usec);
91 #endif
e6daf794 92 #endif // Sun/EMX/Something else
518b5d2f 93 };
bdc72a22
VZ
94
95 #define HAVE_USLEEP 1
518b5d2f
VZ
96#endif // Unices without usleep()
97
518b5d2f
VZ
98// ============================================================================
99// implementation
100// ============================================================================
101
102// ----------------------------------------------------------------------------
103// sleeping
104// ----------------------------------------------------------------------------
105
106void wxSleep(int nSecs)
107{
108 sleep(nSecs);
109}
110
111void wxUsleep(unsigned long milliseconds)
112{
b12915c1 113#if defined(HAVE_NANOSLEEP)
518b5d2f 114 timespec tmReq;
13111b2a 115 tmReq.tv_sec = (time_t)(milliseconds / 1000);
518b5d2f
VZ
116 tmReq.tv_nsec = (milliseconds % 1000) * 1000 * 1000;
117
118 // we're not interested in remaining time nor in return value
119 (void)nanosleep(&tmReq, (timespec *)NULL);
b12915c1 120#elif defined(HAVE_USLEEP)
518b5d2f
VZ
121 // uncomment this if you feel brave or if you are sure that your version
122 // of Solaris has a safe usleep() function but please notice that usleep()
123 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
124 // documented as MT-Safe
ea18eed9 125 #if defined(__SUN__) && wxUSE_THREADS
518b5d2f
VZ
126 #error "usleep() cannot be used in MT programs under Solaris."
127 #endif // Sun
128
129 usleep(milliseconds * 1000); // usleep(3) wants microseconds
b12915c1
VZ
130#elif defined(HAVE_SLEEP)
131 // under BeOS sleep() takes seconds (what about other platforms, if any?)
132 sleep(milliseconds * 1000);
518b5d2f
VZ
133#else // !sleep function
134 #error "usleep() or nanosleep() function required for wxUsleep"
135#endif // sleep function
136}
137
138// ----------------------------------------------------------------------------
139// process management
140// ----------------------------------------------------------------------------
141
50567b69 142int wxKill(long pid, wxSignal sig, wxKillError *rc)
518b5d2f 143{
50567b69
VZ
144 int err = kill((pid_t)pid, (int)sig);
145 if ( rc )
146 {
147 switch ( err )
148 {
149 case 0:
150 *rc = wxKILL_OK;
151 break;
152
153 case EINVAL:
154 *rc = wxKILL_BAD_SIGNAL;
155 break;
156
157 case EPERM:
158 *rc = wxKILL_ACCESS_DENIED;
159 break;
160
161 case ESRCH:
162 *rc = wxKILL_NO_PROCESS;
163 break;
164
165 default:
166 // this goes against Unix98 docs so log it
167 wxLogDebug(_T("unexpected kill(2) return value %d"), err);
168
169 // something else...
170 *rc = wxKILL_ERROR;
171 }
172 }
173
174 return err;
518b5d2f
VZ
175}
176
fad866f4
KB
177#define WXEXECUTE_NARGS 127
178
518b5d2f
VZ
179long wxExecute( const wxString& command, bool sync, wxProcess *process )
180{
223d09f6 181 wxCHECK_MSG( !command.IsEmpty(), 0, wxT("can't exec empty command") );
518b5d2f
VZ
182
183 int argc = 0;
05079acc 184 wxChar *argv[WXEXECUTE_NARGS];
fad866f4 185 wxString argument;
05079acc 186 const wxChar *cptr = command.c_str();
223d09f6 187 wxChar quotechar = wxT('\0'); // is arg quoted?
fad866f4 188 bool escaped = FALSE;
518b5d2f 189
0ed9a934 190 // split the command line in arguments
fad866f4
KB
191 do
192 {
223d09f6
KB
193 argument=wxT("");
194 quotechar = wxT('\0');
0ed9a934 195
fad866f4 196 // eat leading whitespace:
05079acc 197 while ( wxIsspace(*cptr) )
fad866f4 198 cptr++;
0ed9a934 199
223d09f6 200 if ( *cptr == wxT('\'') || *cptr == wxT('"') )
fad866f4 201 quotechar = *cptr++;
0ed9a934 202
fad866f4
KB
203 do
204 {
223d09f6 205 if ( *cptr == wxT('\\') && ! escaped )
fad866f4
KB
206 {
207 escaped = TRUE;
208 cptr++;
209 continue;
210 }
0ed9a934 211
fad866f4 212 // all other characters:
0ed9a934 213 argument += *cptr++;
fad866f4 214 escaped = FALSE;
0ed9a934
VZ
215
216 // have we reached the end of the argument?
217 if ( (*cptr == quotechar && ! escaped)
223d09f6
KB
218 || (quotechar == wxT('\0') && wxIsspace(*cptr))
219 || *cptr == wxT('\0') )
fad866f4 220 {
0ed9a934 221 wxASSERT_MSG( argc < WXEXECUTE_NARGS,
223d09f6 222 wxT("too many arguments in wxExecute") );
0ed9a934 223
05079acc
OK
224 argv[argc] = new wxChar[argument.length() + 1];
225 wxStrcpy(argv[argc], argument.c_str());
fad866f4 226 argc++;
0ed9a934 227
fad866f4 228 // if not at end of buffer, swallow last character:
0ed9a934
VZ
229 if(*cptr)
230 cptr++;
231
fad866f4
KB
232 break; // done with this one, start over
233 }
0ed9a934
VZ
234 } while(*cptr);
235 } while(*cptr);
fad866f4 236 argv[argc] = NULL;
0ed9a934
VZ
237
238 // do execute the command
518b5d2f
VZ
239 long lRc = wxExecute(argv, sync, process);
240
0ed9a934 241 // clean up
fad866f4 242 argc = 0;
0ed9a934 243 while( argv[argc] )
fad866f4 244 delete [] argv[argc++];
518b5d2f
VZ
245
246 return lRc;
247}
248
2c8e4738
VZ
249// ----------------------------------------------------------------------------
250// wxShell
251// ----------------------------------------------------------------------------
252
253static wxString wxMakeShellCommand(const wxString& command)
518b5d2f
VZ
254{
255 wxString cmd;
cd6ce4a9 256 if ( !command )
2c8e4738
VZ
257 {
258 // just an interactive shell
cd6ce4a9 259 cmd = _T("xterm");
2c8e4738 260 }
518b5d2f 261 else
2c8e4738
VZ
262 {
263 // execute command in a shell
264 cmd << _T("/bin/sh -c '") << command << _T('\'');
265 }
266
267 return cmd;
268}
269
270bool wxShell(const wxString& command)
271{
272 return wxExecute(wxMakeShellCommand(command), TRUE /* sync */) == 0;
273}
274
275bool wxShell(const wxString& command, wxArrayString& output)
276{
277 wxCHECK_MSG( !!command, FALSE, _T("can't exec shell non interactively") );
518b5d2f 278
2c8e4738 279 return wxExecute(wxMakeShellCommand(command), output);
518b5d2f
VZ
280}
281
6dc6fda6
VZ
282#if wxUSE_GUI
283
518b5d2f
VZ
284void wxHandleProcessTermination(wxEndProcessData *proc_data)
285{
286 int pid = (proc_data->pid > 0) ? proc_data->pid : -(proc_data->pid);
287
0ed9a934
VZ
288 // waitpid is POSIX so should be available everywhere, however on older
289 // systems wait() might be used instead in a loop (until the right pid
290 // terminates)
518b5d2f 291 int status = 0;
ab857a4e
KB
292 int rc;
293
bdc72a22 294 // wait for child termination and if waitpid() was interrupted, try again
ab857a4e 295 do
bdc72a22 296 {
ab857a4e 297 rc = waitpid(pid, &status, 0);
bdc72a22
VZ
298 }
299 while ( rc == -1 && errno == EINTR );
300
c556f198
JS
301 if (rc == -1)
302 {
303 // JACS: this could happen if the process was terminated and waitpid called,
304 // so commenting out for now.
305 //wxLogSysError(_("Waiting for subprocess termination failed (return code = -1)"));
306 }
307 else if (! (WIFEXITED(status)))
0ed9a934 308 {
c556f198
JS
309 wxLogSysError(_("Waiting for subprocess termination failed (WIFEXITED returned zero)"));
310
311 /* AFAIK, this can only happen if something went wrong within
312 wxGTK, i.e. due to a race condition or some serious bug.
313 After having fixed the order of statements in
314 GTK_EndProcessDetector(). (KB)
315 */
316 }
317 else if (WIFSIGNALED(status))
318 {
319 wxLogSysError(_("Waiting for subprocess termination failed (signal not caught)"));
320
ab857a4e 321 /* AFAIK, this can only happen if something went wrong within
bdc72a22 322 wxGTK, i.e. due to a race condition or some serious bug.
ab857a4e
KB
323 After having fixed the order of statements in
324 GTK_EndProcessDetector(). (KB)
325 */
0ed9a934 326 }
09d68ec1 327 // else
0ed9a934
VZ
328 {
329 // notify user about termination if required
330 if (proc_data->process)
331 {
332 proc_data->process->OnTerminate(proc_data->pid,
333 WEXITSTATUS(status));
334 }
ab857a4e
KB
335 // clean up
336 if ( proc_data->pid > 0 )
337 {
338 delete proc_data;
339 }
340 else
341 {
342 // wxExecute() will know about it
343 proc_data->exitcode = status;
bdc72a22 344
ab857a4e
KB
345 proc_data->pid = 0;
346 }
518b5d2f
VZ
347 }
348}
349
6dc6fda6
VZ
350#endif // wxUSE_GUI
351
cd6ce4a9
VZ
352// ----------------------------------------------------------------------------
353// wxStream classes to support IO redirection in wxExecute
354// ----------------------------------------------------------------------------
6dc6fda6 355
1e6feb95
VZ
356#if wxUSE_STREAMS
357
cd6ce4a9
VZ
358class wxProcessFileInputStream : public wxInputStream
359{
360public:
361 wxProcessFileInputStream(int fd) { m_fd = fd; }
362 ~wxProcessFileInputStream() { close(m_fd); }
8b33ae2d 363
cd6ce4a9 364 virtual bool Eof() const;
8b33ae2d 365
cd6ce4a9 366protected:
8b33ae2d
GL
367 size_t OnSysRead(void *buffer, size_t bufsize);
368
cd6ce4a9 369protected:
8b33ae2d
GL
370 int m_fd;
371};
372
cd6ce4a9
VZ
373class wxProcessFileOutputStream : public wxOutputStream
374{
375public:
376 wxProcessFileOutputStream(int fd) { m_fd = fd; }
377 ~wxProcessFileOutputStream() { close(m_fd); }
8b33ae2d 378
cd6ce4a9 379protected:
8b33ae2d
GL
380 size_t OnSysWrite(const void *buffer, size_t bufsize);
381
cd6ce4a9 382protected:
8b33ae2d
GL
383 int m_fd;
384};
385
cd6ce4a9 386bool wxProcessFileInputStream::Eof() const
8b33ae2d 387{
cd6ce4a9
VZ
388 if ( m_lasterror == wxSTREAM_EOF )
389 return TRUE;
390
391 // check if there is any input available
392 struct timeval tv;
393 tv.tv_sec = 0;
394 tv.tv_usec = 0;
395
396 fd_set readfds;
397 FD_ZERO(&readfds);
398 FD_SET(m_fd, &readfds);
399 switch ( select(m_fd + 1, &readfds, NULL, NULL, &tv) )
400 {
401 case -1:
402 wxLogSysError(_("Impossible to get child process input"));
403 // fall through
8b33ae2d 404
cd6ce4a9
VZ
405 case 0:
406 return TRUE;
8b33ae2d 407
cd6ce4a9
VZ
408 default:
409 wxFAIL_MSG(_T("unexpected select() return value"));
410 // still fall through
411
412 case 1:
413 // input available: check if there is any
414 return wxInputStream::Eof();
8b33ae2d 415 }
8b33ae2d
GL
416}
417
cd6ce4a9 418size_t wxProcessFileInputStream::OnSysRead(void *buffer, size_t bufsize)
8b33ae2d 419{
cd6ce4a9
VZ
420 int ret = read(m_fd, buffer, bufsize);
421 if ( ret == 0 )
422 {
423 m_lasterror = wxSTREAM_EOF;
424 }
425 else if ( ret == -1 )
426 {
427 m_lasterror = wxSTREAM_READ_ERROR;
428 ret = 0;
429 }
430 else
431 {
432 m_lasterror = wxSTREAM_NOERROR;
433 }
8b33ae2d 434
cd6ce4a9 435 return ret;
8b33ae2d
GL
436}
437
438size_t wxProcessFileOutputStream::OnSysWrite(const void *buffer, size_t bufsize)
439{
cd6ce4a9
VZ
440 int ret = write(m_fd, buffer, bufsize);
441 if ( ret == -1 )
442 {
443 m_lasterror = wxSTREAM_WRITE_ERROR;
444 ret = 0;
8b33ae2d 445 }
cd6ce4a9
VZ
446 else
447 {
448 m_lasterror = wxSTREAM_NOERROR;
449 }
450
8b33ae2d
GL
451 return ret;
452}
453
1e6feb95
VZ
454#endif // wxUSE_STREAMS
455
6dc6fda6
VZ
456long wxExecute(wxChar **argv,
457 bool sync,
cd6ce4a9 458 wxProcess *process)
518b5d2f 459{
f6bcfd97 460 // for the sync execution, we return -1 to indicate failure, but for async
accb3257
VZ
461 // case we return 0 which is never a valid PID
462 //
463 // we define this as a macro, not a variable, to avoid compiler warnings
464 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
465 #define ERROR_RETURN_CODE ((sync) ? -1 : 0)
f6bcfd97 466
accb3257 467 wxCHECK_MSG( *argv, ERROR_RETURN_CODE, wxT("can't exec empty command") );
518b5d2f 468
05079acc
OK
469#if wxUSE_UNICODE
470 int mb_argc = 0;
471 char *mb_argv[WXEXECUTE_NARGS];
472
e90c1d2a
VZ
473 while (argv[mb_argc])
474 {
cd6ce4a9
VZ
475 wxWX2MBbuf mb_arg = wxConvertWX2MB(argv[mb_argc]);
476 mb_argv[mb_argc] = strdup(mb_arg);
477 mb_argc++;
05079acc
OK
478 }
479 mb_argv[mb_argc] = (char *) NULL;
e90c1d2a
VZ
480
481 // this macro will free memory we used above
482 #define ARGS_CLEANUP \
345b0247 483 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
e90c1d2a
VZ
484 free(mb_argv[mb_argc])
485#else // ANSI
486 // no need for cleanup
487 #define ARGS_CLEANUP
488
05079acc 489 wxChar **mb_argv = argv;
e90c1d2a 490#endif // Unicode/ANSI
518b5d2f 491
e90c1d2a 492#if wxUSE_GUI
518b5d2f 493 // create pipes
e90c1d2a 494 int end_proc_detect[2];
cd6ce4a9 495 if ( pipe(end_proc_detect) == -1 )
518b5d2f
VZ
496 {
497 wxLogSysError( _("Pipe creation failed") );
cd6ce4a9 498 wxLogError( _("Failed to execute '%s'\n"), *argv );
e90c1d2a
VZ
499
500 ARGS_CLEANUP;
501
accb3257 502 return ERROR_RETURN_CODE;
518b5d2f 503 }
e90c1d2a 504#endif // wxUSE_GUI
518b5d2f 505
f6bcfd97
BP
506 // pipes for inter process communication
507 int pipeIn[2], // stdin
508 pipeOut[2], // stdout
509 pipeErr[2]; // stderr
510
cd6ce4a9 511 pipeIn[0] = pipeIn[1] =
f6bcfd97
BP
512 pipeOut[0] = pipeOut[1] =
513 pipeErr[0] = pipeErr[1] = -1;
cd6ce4a9
VZ
514
515 if ( process && process->IsRedirected() )
8b33ae2d 516 {
f6bcfd97 517 if ( pipe(pipeIn) == -1 || pipe(pipeOut) == -1 || pipe(pipeErr) == -1 )
8b33ae2d 518 {
cd6ce4a9
VZ
519#if wxUSE_GUI
520 // free previously allocated resources
8b33ae2d
GL
521 close(end_proc_detect[0]);
522 close(end_proc_detect[1]);
cd6ce4a9
VZ
523#endif // wxUSE_GUI
524
525 wxLogSysError( _("Pipe creation failed") );
526 wxLogError( _("Failed to execute '%s'\n"), *argv );
8b33ae2d
GL
527
528 ARGS_CLEANUP;
529
accb3257 530 return ERROR_RETURN_CODE;
8b33ae2d
GL
531 }
532 }
8b33ae2d 533
518b5d2f 534 // fork the process
0fcdf6dc 535#ifdef HAVE_VFORK
518b5d2f
VZ
536 pid_t pid = vfork();
537#else
538 pid_t pid = fork();
539#endif
cd6ce4a9
VZ
540
541 if ( pid == -1 ) // error?
518b5d2f 542 {
8b33ae2d
GL
543#if wxUSE_GUI
544 close(end_proc_detect[0]);
545 close(end_proc_detect[1]);
cd6ce4a9
VZ
546 close(pipeIn[0]);
547 close(pipeIn[1]);
548 close(pipeOut[0]);
549 close(pipeOut[1]);
f6bcfd97
BP
550 close(pipeErr[0]);
551 close(pipeErr[1]);
cd6ce4a9
VZ
552#endif // wxUSE_GUI
553
518b5d2f 554 wxLogSysError( _("Fork failed") );
e90c1d2a
VZ
555
556 ARGS_CLEANUP;
557
accb3257 558 return ERROR_RETURN_CODE;
518b5d2f 559 }
cd6ce4a9 560 else if ( pid == 0 ) // we're in child
518b5d2f 561 {
e90c1d2a 562#if wxUSE_GUI
518b5d2f 563 close(end_proc_detect[0]); // close reading side
e90c1d2a 564#endif // wxUSE_GUI
518b5d2f 565
cd6ce4a9 566 // These lines close the open file descriptors to to avoid any
518b5d2f 567 // input/output which might block the process or irritate the user. If
cd6ce4a9
VZ
568 // one wants proper IO for the subprocess, the right thing to do is to
569 // start an xterm executing it.
570 if ( !sync )
518b5d2f 571 {
518b5d2f
VZ
572 for ( int fd = 0; fd < FD_SETSIZE; fd++ )
573 {
f6bcfd97 574 if ( fd == pipeIn[0] || fd == pipeOut[1] || fd == pipeErr[1]
e90c1d2a 575#if wxUSE_GUI
cd6ce4a9 576 || fd == end_proc_detect[1]
e90c1d2a 577#endif // wxUSE_GUI
cd6ce4a9
VZ
578 )
579 {
580 // don't close this one, we still need it
581 continue;
582 }
e90c1d2a 583
cd6ce4a9 584 // leave stderr opened too, it won't do any hurm
e90c1d2a 585 if ( fd != STDERR_FILENO )
518b5d2f
VZ
586 close(fd);
587 }
588 }
589
f6bcfd97 590 // redirect stdio, stdout and stderr
cd6ce4a9
VZ
591 if ( pipeIn[0] != -1 )
592 {
593 if ( dup2(pipeIn[0], STDIN_FILENO) == -1 ||
f6bcfd97
BP
594 dup2(pipeOut[1], STDOUT_FILENO) == -1 ||
595 dup2(pipeErr[1], STDERR_FILENO) == -1 )
cd6ce4a9 596 {
f6bcfd97 597 wxLogSysError(_("Failed to redirect child process input/output"));
cd6ce4a9 598 }
518b5d2f 599
cd6ce4a9
VZ
600 close(pipeIn[0]);
601 close(pipeOut[1]);
f6bcfd97 602 close(pipeErr[1]);
cd6ce4a9 603 }
518b5d2f 604
05079acc 605 execvp (*mb_argv, mb_argv);
518b5d2f
VZ
606
607 // there is no return after successful exec()
518b5d2f 608 _exit(-1);
1d8dd65e
VZ
609
610 // some compilers complain about missing return - of course, they
611 // should know that exit() doesn't return but what else can we do if
612 // they don't?
613#if defined(__VMS) || defined(__INTEL_COMPILER)
614 return 0;
615#endif
518b5d2f 616 }
cd6ce4a9 617 else // we're in parent
518b5d2f 618 {
cd6ce4a9
VZ
619 ARGS_CLEANUP;
620
621 // pipe initialization: construction of the wxStreams
622 if ( process && process->IsRedirected() )
623 {
1e6feb95 624#if wxUSE_STREAMS
cd6ce4a9
VZ
625 // These two streams are relative to this process.
626 wxOutputStream *outStream = new wxProcessFileOutputStream(pipeIn[1]);
627 wxInputStream *inStream = new wxProcessFileInputStream(pipeOut[0]);
f6bcfd97
BP
628 wxInputStream *errStream = new wxProcessFileInputStream(pipeErr[0]);
629
1e6feb95
VZ
630 process->SetPipeStreams(inStream, outStream, errStream);
631#endif // wxUSE_STREAMS
632
cd6ce4a9
VZ
633 close(pipeIn[0]); // close reading side
634 close(pipeOut[1]); // close writing side
f6bcfd97 635 close(pipeErr[1]); // close writing side
cd6ce4a9
VZ
636 }
637
fac3b423 638#if wxUSE_GUI && !defined(__WXMICROWIN__)
518b5d2f 639 wxEndProcessData *data = new wxEndProcessData;
ab857a4e 640
518b5d2f
VZ
641 if ( sync )
642 {
cd6ce4a9
VZ
643 // we may have process for capturing the program output, but it's
644 // not used in wxEndProcessData in the case of sync execution
518b5d2f
VZ
645 data->process = NULL;
646
647 // sync execution: indicate it by negating the pid
cd6ce4a9
VZ
648 data->pid = -pid;
649 data->tag = wxAddProcessCallback(data, end_proc_detect[0]);
650
ab857a4e 651 close(end_proc_detect[1]); // close writing side
518b5d2f 652
cd6ce4a9
VZ
653 wxBusyCursor bc;
654 wxWindowDisabler wd;
655
518b5d2f
VZ
656 // it will be set to 0 from GTK_EndProcessDetector
657 while (data->pid != 0)
658 wxYield();
659
660 int exitcode = data->exitcode;
661
662 delete data;
663
664 return exitcode;
665 }
cd6ce4a9 666 else // async execution
518b5d2f
VZ
667 {
668 // async execution, nothing special to do - caller will be
ab857a4e 669 // notified about the process termination if process != NULL, data
518b5d2f 670 // will be deleted in GTK_EndProcessDetector
8b33ae2d
GL
671 data->process = process;
672 data->pid = pid;
673 data->tag = wxAddProcessCallback(data, end_proc_detect[0]);
cd6ce4a9 674
ab857a4e 675 close(end_proc_detect[1]); // close writing side
518b5d2f
VZ
676
677 return pid;
678 }
e90c1d2a 679#else // !wxUSE_GUI
223d09f6 680 wxASSERT_MSG( sync, wxT("async execution not supported yet") );
e90c1d2a
VZ
681
682 int exitcode = 0;
683 if ( waitpid(pid, &exitcode, 0) == -1 || !WIFEXITED(exitcode) )
684 {
685 wxLogSysError(_("Waiting for subprocess termination failed"));
686 }
687
688 return exitcode;
689#endif // wxUSE_GUI
518b5d2f
VZ
690 }
691}
692
accb3257 693#undef ERROR_RETURN_CODE
f6bcfd97
BP
694#undef ARGS_CLEANUP
695
518b5d2f
VZ
696// ----------------------------------------------------------------------------
697// file and directory functions
698// ----------------------------------------------------------------------------
699
05079acc 700const wxChar* wxGetHomeDir( wxString *home )
518b5d2f
VZ
701{
702 *home = wxGetUserHome( wxString() );
181cbcf4 703 wxString tmp;
518b5d2f 704 if ( home->IsEmpty() )
223d09f6 705 *home = wxT("/");
181cbcf4
JJ
706#ifdef __VMS
707 tmp = *home;
708 if ( tmp.Last() != wxT(']'))
709 if ( tmp.Last() != wxT('/')) *home << wxT('/');
710#endif
518b5d2f
VZ
711 return home->c_str();
712}
713
05079acc
OK
714#if wxUSE_UNICODE
715const wxMB2WXbuf wxGetUserHome( const wxString &user )
e90c1d2a 716#else // just for binary compatibility -- there is no 'const' here
518b5d2f 717char *wxGetUserHome( const wxString &user )
05079acc 718#endif
518b5d2f
VZ
719{
720 struct passwd *who = (struct passwd *) NULL;
721
0fb67cd1 722 if ( !user )
518b5d2f 723 {
e90c1d2a 724 wxChar *ptr;
518b5d2f 725
223d09f6 726 if ((ptr = wxGetenv(wxT("HOME"))) != NULL)
518b5d2f
VZ
727 {
728 return ptr;
729 }
223d09f6 730 if ((ptr = wxGetenv(wxT("USER"))) != NULL || (ptr = wxGetenv(wxT("LOGNAME"))) != NULL)
518b5d2f 731 {
e90c1d2a 732 who = getpwnam(wxConvertWX2MB(ptr));
518b5d2f
VZ
733 }
734
735 // We now make sure the the user exists!
736 if (who == NULL)
737 {
738 who = getpwuid(getuid());
739 }
740 }
741 else
742 {
05079acc 743 who = getpwnam (user.mb_str());
518b5d2f
VZ
744 }
745
af111fc3 746 return wxConvertMB2WX(who ? who->pw_dir : 0);
518b5d2f
VZ
747}
748
749// ----------------------------------------------------------------------------
0fb67cd1 750// network and user id routines
518b5d2f
VZ
751// ----------------------------------------------------------------------------
752
0fb67cd1
VZ
753// retrieve either the hostname or FQDN depending on platform (caller must
754// check whether it's one or the other, this is why this function is for
755// private use only)
05079acc 756static bool wxGetHostNameInternal(wxChar *buf, int sz)
518b5d2f 757{
223d09f6 758 wxCHECK_MSG( buf, FALSE, wxT("NULL pointer in wxGetHostNameInternal") );
518b5d2f 759
223d09f6 760 *buf = wxT('\0');
518b5d2f
VZ
761
762 // we're using uname() which is POSIX instead of less standard sysinfo()
763#if defined(HAVE_UNAME)
cc743a6f 764 struct utsname uts;
518b5d2f
VZ
765 bool ok = uname(&uts) != -1;
766 if ( ok )
767 {
e90c1d2a 768 wxStrncpy(buf, wxConvertMB2WX(uts.nodename), sz - 1);
223d09f6 769 buf[sz] = wxT('\0');
518b5d2f
VZ
770 }
771#elif defined(HAVE_GETHOSTNAME)
772 bool ok = gethostname(buf, sz) != -1;
0fb67cd1 773#else // no uname, no gethostname
223d09f6 774 wxFAIL_MSG(wxT("don't know host name for this machine"));
518b5d2f
VZ
775
776 bool ok = FALSE;
0fb67cd1 777#endif // uname/gethostname
518b5d2f
VZ
778
779 if ( !ok )
780 {
781 wxLogSysError(_("Cannot get the hostname"));
782 }
783
784 return ok;
785}
786
05079acc 787bool wxGetHostName(wxChar *buf, int sz)
0fb67cd1
VZ
788{
789 bool ok = wxGetHostNameInternal(buf, sz);
790
791 if ( ok )
792 {
793 // BSD systems return the FQDN, we only want the hostname, so extract
794 // it (we consider that dots are domain separators)
223d09f6 795 wxChar *dot = wxStrchr(buf, wxT('.'));
0fb67cd1
VZ
796 if ( dot )
797 {
798 // nuke it
223d09f6 799 *dot = wxT('\0');
0fb67cd1
VZ
800 }
801 }
802
803 return ok;
804}
805
05079acc 806bool wxGetFullHostName(wxChar *buf, int sz)
0fb67cd1
VZ
807{
808 bool ok = wxGetHostNameInternal(buf, sz);
809
810 if ( ok )
811 {
223d09f6 812 if ( !wxStrchr(buf, wxT('.')) )
0fb67cd1 813 {
e90c1d2a 814 struct hostent *host = gethostbyname(wxConvertWX2MB(buf));
0fb67cd1
VZ
815 if ( !host )
816 {
817 wxLogSysError(_("Cannot get the official hostname"));
818
819 ok = FALSE;
820 }
821 else
822 {
823 // the canonical name
e90c1d2a 824 wxStrncpy(buf, wxConvertMB2WX(host->h_name), sz);
0fb67cd1
VZ
825 }
826 }
827 //else: it's already a FQDN (BSD behaves this way)
828 }
829
830 return ok;
831}
832
05079acc 833bool wxGetUserId(wxChar *buf, int sz)
518b5d2f
VZ
834{
835 struct passwd *who;
836
223d09f6 837 *buf = wxT('\0');
518b5d2f
VZ
838 if ((who = getpwuid(getuid ())) != NULL)
839 {
e90c1d2a 840 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
518b5d2f
VZ
841 return TRUE;
842 }
843
844 return FALSE;
845}
846
05079acc 847bool wxGetUserName(wxChar *buf, int sz)
518b5d2f
VZ
848{
849 struct passwd *who;
518b5d2f 850
223d09f6 851 *buf = wxT('\0');
b12915c1
VZ
852 if ((who = getpwuid (getuid ())) != NULL)
853 {
854 // pw_gecos field in struct passwd is not standard
bd3277fe 855#ifdef HAVE_PW_GECOS
b12915c1 856 char *comma = strchr(who->pw_gecos, ',');
518b5d2f
VZ
857 if (comma)
858 *comma = '\0'; // cut off non-name comment fields
e90c1d2a 859 wxStrncpy (buf, wxConvertMB2WX(who->pw_gecos), sz - 1);
b12915c1 860#else // !HAVE_PW_GECOS
0fcdf6dc 861 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
b12915c1 862#endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
518b5d2f
VZ
863 return TRUE;
864 }
865
866 return FALSE;
867}
868
bdc72a22
VZ
869wxString wxGetOsDescription()
870{
871#ifndef WXWIN_OS_DESCRIPTION
872 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
873#else
874 return WXWIN_OS_DESCRIPTION;
875#endif
876}
877
bd3277fe
VZ
878// this function returns the GUI toolkit version in GUI programs, but OS
879// version in non-GUI ones
880#if !wxUSE_GUI
881
882int wxGetOsVersion(int *majorVsn, int *minorVsn)
883{
884 int major, minor;
885 char name[256];
886
887 if ( sscanf(WXWIN_OS_DESCRIPTION, "%s %d.%d", name, &major, &minor) != 3 )
888 {
889 // unreckognized uname string format
890 major = minor = -1;
891 }
892
893 if ( majorVsn )
894 *majorVsn = major;
895 if ( minorVsn )
896 *minorVsn = minor;
897
898 return wxUNIX;
899}
900
901#endif // !wxUSE_GUI
902
903long wxGetFreeMemory()
904{
905#if defined(__LINUX__)
906 // get it from /proc/meminfo
907 FILE *fp = fopen("/proc/meminfo", "r");
908 if ( fp )
909 {
910 long memFree = -1;
911
912 char buf[1024];
913 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
914 {
915 long memTotal, memUsed;
916 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
917 }
918
919 fclose(fp);
920
921 return memFree;
922 }
923#elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
924 return sysconf(_SC_AVPHYS_PAGES)*sysconf(_SC_PAGESIZE);
925//#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
926#endif
927
928 // can't find it out
929 return -1;
930}
931
eadd7bd2
VZ
932bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
933{
934#ifdef HAVE_STATFS
935
936 struct statfs fs;
937 if ( statfs(path, &fs) != 0 )
938 {
939 wxLogSysError("Failed to get file system statistics");
940
941 return FALSE;
942 }
943
944 if ( pTotal )
945 {
946 *pTotal = wxLongLong(fs.f_blocks) * fs.f_bsize;
947 }
948
949 if ( pFree )
950 {
951 *pFree = wxLongLong(fs.f_bavail) * fs.f_bsize;
952 }
953
954 return TRUE;
955#endif // HAVE_STATFS
956
957 return FALSE;
958}
959
8fd0d89b
VZ
960// ----------------------------------------------------------------------------
961// env vars
962// ----------------------------------------------------------------------------
963
97b305b7 964bool wxGetEnv(const wxString& var, wxString *value)
308978f6
VZ
965{
966 // wxGetenv is defined as getenv()
967 wxChar *p = wxGetenv(var);
968 if ( !p )
969 return FALSE;
970
971 if ( value )
972 {
973 *value = p;
974 }
975
976 return TRUE;
977}
978
8fd0d89b
VZ
979bool wxSetEnv(const wxString& variable, const wxChar *value)
980{
981#if defined(HAVE_SETENV)
982 return setenv(variable.mb_str(), value ? wxString(value).mb_str().data()
983 : NULL, 1 /* overwrite */) == 0;
984#elif defined(HAVE_PUTENV)
985 wxString s = variable;
986 if ( value )
987 s << _T('=') << value;
988
989 // transform to ANSI
990 const char *p = s.mb_str();
991
992 // the string will be free()d by libc
993 char *buf = (char *)malloc(strlen(p) + 1);
994 strcpy(buf, p);
995
996 return putenv(buf) == 0;
997#else // no way to set an env var
998 return FALSE;
999#endif
1000}
1001
a37a5a73
VZ
1002// ----------------------------------------------------------------------------
1003// signal handling
1004// ----------------------------------------------------------------------------
1005
1006#if wxUSE_ON_FATAL_EXCEPTION
1007
1008#include <signal.h>
1009
f6bcfd97 1010static void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
a37a5a73
VZ
1011{
1012 if ( wxTheApp )
1013 {
1014 // give the user a chance to do something special about this
1015 wxTheApp->OnFatalException();
1016 }
1017
1018 abort();
1019}
1020
1021bool wxHandleFatalExceptions(bool doit)
1022{
1023 // old sig handlers
1024 static bool s_savedHandlers = FALSE;
1025 static struct sigaction s_handlerFPE,
1026 s_handlerILL,
1027 s_handlerBUS,
1028 s_handlerSEGV;
1029
1030 bool ok = TRUE;
1031 if ( doit && !s_savedHandlers )
1032 {
1033 // install the signal handler
1034 struct sigaction act;
1035
1036 // some systems extend it with non std fields, so zero everything
1037 memset(&act, 0, sizeof(act));
1038
1039 act.sa_handler = wxFatalSignalHandler;
1040 sigemptyset(&act.sa_mask);
1041 act.sa_flags = 0;
1042
1043 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1044 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1045 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1046 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1047 if ( !ok )
1048 {
1049 wxLogDebug(_T("Failed to install our signal handler."));
1050 }
1051
1052 s_savedHandlers = TRUE;
1053 }
1054 else if ( s_savedHandlers )
1055 {
1056 // uninstall the signal handler
1057 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1058 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1059 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1060 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1061 if ( !ok )
1062 {
1063 wxLogDebug(_T("Failed to uninstall our signal handler."));
1064 }
1065
1066 s_savedHandlers = FALSE;
1067 }
1068 //else: nothing to do
1069
1070 return ok;
1071}
1072
1073#endif // wxUSE_ON_FATAL_EXCEPTION
1074
518b5d2f
VZ
1075// ----------------------------------------------------------------------------
1076// error and debug output routines (deprecated, use wxLog)
1077// ----------------------------------------------------------------------------
1078
1079void wxDebugMsg( const char *format, ... )
1080{
1081 va_list ap;
1082 va_start( ap, format );
1083 vfprintf( stderr, format, ap );
1084 fflush( stderr );
1085 va_end(ap);
1086}
1087
1088void wxError( const wxString &msg, const wxString &title )
1089{
05079acc 1090 wxFprintf( stderr, _("Error ") );
223d09f6
KB
1091 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1092 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1093 wxFprintf( stderr, wxT(".\n") );
518b5d2f
VZ
1094}
1095
1096void wxFatalError( const wxString &msg, const wxString &title )
1097{
05079acc 1098 wxFprintf( stderr, _("Error ") );
223d09f6
KB
1099 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1100 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1101 wxFprintf( stderr, wxT(".\n") );
518b5d2f
VZ
1102 exit(3); // the same exit code as for abort()
1103}
93ccaed8 1104