]> git.saurik.com Git - wxWidgets.git/blame - src/unix/utilsunx.cpp
removing outdated files for mac
[wxWidgets.git] / src / unix / utilsunx.cpp
CommitLineData
518b5d2f 1/////////////////////////////////////////////////////////////////////////////
7520f3da 2// Name: src/unix/utilsunx.cpp
518b5d2f
VZ
3// Purpose: generic Unix implementation of many wx functions
4// Author: Vadim Zeitlin
5// Id: $Id$
6// Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
65571936 7// Licence: wxWindows licence
518b5d2f
VZ
8/////////////////////////////////////////////////////////////////////////////
9
10// ============================================================================
11// declarations
12// ============================================================================
13
14// ----------------------------------------------------------------------------
15// headers
16// ----------------------------------------------------------------------------
17
14f355c2
VS
18// for compilers that support precompilation, includes "wx.h".
19#include "wx/wxprec.h"
20
88a7a4e1
WS
21#include "wx/utils.h"
22
c0472c7c
VZ
23#define USE_PUTENV (!defined(HAVE_SETENV) && defined(HAVE_PUTENV))
24
7520f3da
WS
25#ifndef WX_PRECOMP
26 #include "wx/string.h"
88a7a4e1 27 #include "wx/intl.h"
e4db172a 28 #include "wx/log.h"
670f9935 29 #include "wx/app.h"
0cb7e05c 30 #include "wx/wxcrtvararg.h"
c0472c7c
VZ
31 #if USE_PUTENV
32 #include "wx/module.h"
33 #include "wx/hashmap.h"
34 #endif
7520f3da 35#endif
518b5d2f 36
46446cc2 37#include "wx/apptrait.h"
518b5d2f 38
518b5d2f 39#include "wx/process.h"
bdc72a22 40#include "wx/thread.h"
518b5d2f 41
80d6dc0a 42#include "wx/wfstream.h"
8b33ae2d 43
33343395 44#include "wx/private/selectdispatcher.h"
1d043598 45#include "wx/private/fdiodispatcher.h"
e2478fde 46#include "wx/unix/execute.h"
17a1ebd1
VZ
47#include "wx/unix/private.h"
48
46c7e1a1
VS
49#ifdef wxHAS_GENERIC_PROCESS_CALLBACK
50#include "wx/private/fdiodispatcher.h"
51#endif
52
17a1ebd1 53#include <pwd.h>
bc855d09 54#include <sys/wait.h> // waitpid()
e2478fde 55
bc023abb
MW
56#ifdef HAVE_SYS_SELECT_H
57# include <sys/select.h>
58#endif
59
1f3b2af0
VS
60#define HAS_PIPE_INPUT_STREAM (wxUSE_STREAMS && wxUSE_FILE)
61
62#if HAS_PIPE_INPUT_STREAM
2887179b
VZ
63
64// define this to let wxexec.cpp know that we know what we're doing
65#define _WX_USED_BY_WXEXECUTE_
66#include "../common/execcmn.cpp"
67
1f3b2af0 68#endif // HAS_PIPE_INPUT_STREAM
2887179b 69
74c719ed
VZ
70#if defined(__MWERKS__) && defined(__MACH__)
71 #ifndef WXWIN_OS_DESCRIPTION
72 #define WXWIN_OS_DESCRIPTION "MacOS X"
73 #endif
74 #ifndef HAVE_NANOSLEEP
75 #define HAVE_NANOSLEEP
76 #endif
77 #ifndef HAVE_UNAME
78 #define HAVE_UNAME
79 #endif
80
81 // our configure test believes we can use sigaction() if the function is
82 // available but Metrowekrs with MSL run-time does have the function but
83 // doesn't have sigaction struct so finally we can't use it...
84 #ifdef __MSL__
85 #undef wxUSE_ON_FATAL_EXCEPTION
86 #define wxUSE_ON_FATAL_EXCEPTION 0
87 #endif
8d4f85ce
SC
88#endif
89
85da04e9
VZ
90// not only the statfs syscall is called differently depending on platform, but
91// one of its incarnations, statvfs(), takes different arguments under
92// different platforms and even different versions of the same system (Solaris
93// 7 and 8): if you want to test for this, don't forget that the problems only
94// appear if the large files support is enabled
eadd7bd2 95#ifdef HAVE_STATFS
85da04e9
VZ
96 #ifdef __BSD__
97 #include <sys/param.h>
98 #include <sys/mount.h>
99 #else // !__BSD__
100 #include <sys/vfs.h>
101 #endif // __BSD__/!__BSD__
102
103 #define wxStatfs statfs
84ae7ca4
VZ
104
105 #ifndef HAVE_STATFS_DECL
106 // some systems lack statfs() prototype in the system headers (AIX 4)
107 extern "C" int statfs(const char *path, struct statfs *buf);
108 #endif
eadd7bd2
VZ
109#endif // HAVE_STATFS
110
9952adac
VZ
111#ifdef HAVE_STATVFS
112 #include <sys/statvfs.h>
113
85da04e9
VZ
114 #define wxStatfs statvfs
115#endif // HAVE_STATVFS
116
117#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
118 // WX_STATFS_T is detected by configure
119 #define wxStatfs_t WX_STATFS_T
120#endif
9952adac 121
f6bcfd97
BP
122// SGI signal.h defines signal handler arguments differently depending on
123// whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
124#if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
125 #define _LANGUAGE_C_PLUS_PLUS 1
126#endif // SGI hack
127
518b5d2f
VZ
128#include <stdarg.h>
129#include <dirent.h>
130#include <string.h>
131#include <sys/stat.h>
132#include <sys/types.h>
518b5d2f 133#include <sys/wait.h>
e2478fde 134#include <unistd.h>
518b5d2f
VZ
135#include <errno.h>
136#include <netdb.h>
137#include <signal.h>
138#include <fcntl.h> // for O_WRONLY and friends
139#include <time.h> // nanosleep() and/or usleep()
fad866f4 140#include <ctype.h> // isspace()
b12915c1 141#include <sys/time.h> // needed for FD_SETSIZE
7bcb11d3 142
0fcdf6dc 143#ifdef HAVE_UNAME
518b5d2f
VZ
144 #include <sys/utsname.h> // for uname()
145#endif // HAVE_UNAME
146
9ad34f61
VZ
147// Used by wxGetFreeMemory().
148#ifdef __SGI__
149 #include <sys/sysmp.h>
150 #include <sys/sysinfo.h> // for SAGET and MINFO structures
151#endif
152
518b5d2f
VZ
153// ----------------------------------------------------------------------------
154// conditional compilation
155// ----------------------------------------------------------------------------
156
157// many versions of Unices have this function, but it is not defined in system
158// headers - please add your system here if it is the case for your OS.
159// SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
1363811b 160#if !defined(HAVE_USLEEP) && \
d67fee71 161 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
518b5d2f 162 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
d67fee71 163 defined(__osf__) || defined(__EMX__))
518b5d2f
VZ
164 extern "C"
165 {
1a5e269b
VZ
166 #ifdef __EMX__
167 /* I copied this from the XFree86 diffs. AV. */
168 #define INCL_DOSPROCESS
169 #include <os2.h>
170 inline void usleep(unsigned long delay)
171 {
172 DosSleep(delay ? (delay/1000l) : 1l);
173 }
174 #else // Unix
1363811b 175 int usleep(unsigned int usec);
1a5e269b 176 #endif // __EMX__/Unix
518b5d2f 177 };
bdc72a22
VZ
178
179 #define HAVE_USLEEP 1
518b5d2f
VZ
180#endif // Unices without usleep()
181
518b5d2f
VZ
182// ============================================================================
183// implementation
184// ============================================================================
185
186// ----------------------------------------------------------------------------
187// sleeping
188// ----------------------------------------------------------------------------
189
190void wxSleep(int nSecs)
191{
192 sleep(nSecs);
193}
194
66cd9d7f 195void wxMicroSleep(unsigned long microseconds)
518b5d2f 196{
b12915c1 197#if defined(HAVE_NANOSLEEP)
518b5d2f 198 timespec tmReq;
66cd9d7f
VZ
199 tmReq.tv_sec = (time_t)(microseconds / 1000000);
200 tmReq.tv_nsec = (microseconds % 1000000) * 1000;
518b5d2f
VZ
201
202 // we're not interested in remaining time nor in return value
203 (void)nanosleep(&tmReq, (timespec *)NULL);
b12915c1 204#elif defined(HAVE_USLEEP)
518b5d2f
VZ
205 // uncomment this if you feel brave or if you are sure that your version
206 // of Solaris has a safe usleep() function but please notice that usleep()
207 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
208 // documented as MT-Safe
ea18eed9 209 #if defined(__SUN__) && wxUSE_THREADS
518b5d2f
VZ
210 #error "usleep() cannot be used in MT programs under Solaris."
211 #endif // Sun
212
66cd9d7f 213 usleep(microseconds);
b12915c1
VZ
214#elif defined(HAVE_SLEEP)
215 // under BeOS sleep() takes seconds (what about other platforms, if any?)
66cd9d7f 216 sleep(microseconds * 1000000);
518b5d2f 217#else // !sleep function
66cd9d7f 218 #error "usleep() or nanosleep() function required for wxMicroSleep"
518b5d2f
VZ
219#endif // sleep function
220}
221
66cd9d7f
VZ
222void wxMilliSleep(unsigned long milliseconds)
223{
224 wxMicroSleep(milliseconds*1000);
225}
226
518b5d2f
VZ
227// ----------------------------------------------------------------------------
228// process management
229// ----------------------------------------------------------------------------
230
e0f6b731 231int wxKill(long pid, wxSignal sig, wxKillError *rc, int flags)
518b5d2f 232{
e0f6b731 233 int err = kill((pid_t) (flags & wxKILL_CHILDREN) ? -pid : pid, (int)sig);
50567b69
VZ
234 if ( rc )
235 {
f0bce4d4 236 switch ( err ? errno : 0 )
50567b69
VZ
237 {
238 case 0:
239 *rc = wxKILL_OK;
240 break;
241
242 case EINVAL:
243 *rc = wxKILL_BAD_SIGNAL;
244 break;
245
246 case EPERM:
247 *rc = wxKILL_ACCESS_DENIED;
248 break;
249
250 case ESRCH:
251 *rc = wxKILL_NO_PROCESS;
252 break;
253
254 default:
255 // this goes against Unix98 docs so log it
256 wxLogDebug(_T("unexpected kill(2) return value %d"), err);
257
258 // something else...
259 *rc = wxKILL_ERROR;
260 }
261 }
262
263 return err;
518b5d2f
VZ
264}
265
05718a98
VZ
266// Shutdown or reboot the PC
267bool wxShutdown(wxShutdownFlags wFlags)
518b5d2f 268{
05718a98
VZ
269 wxChar level;
270 switch ( wFlags )
271 {
272 case wxSHUTDOWN_POWEROFF:
273 level = _T('0');
274 break;
647b8e37 275
05718a98
VZ
276 case wxSHUTDOWN_REBOOT:
277 level = _T('6');
278 break;
518b5d2f 279
05718a98
VZ
280 default:
281 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
282 return false;
283 }
0ed9a934 284
05718a98
VZ
285 return system(wxString::Format(_T("init %c"), level).mb_str()) == 0;
286}
0ed9a934 287
05718a98
VZ
288// ----------------------------------------------------------------------------
289// wxStream classes to support IO redirection in wxExecute
290// ----------------------------------------------------------------------------
0ed9a934 291
05718a98 292#if HAS_PIPE_INPUT_STREAM
0ed9a934 293
05718a98
VZ
294bool wxPipeInputStream::CanRead() const
295{
296 if ( m_lasterror == wxSTREAM_EOF )
297 return false;
0ed9a934 298
05718a98
VZ
299 // check if there is any input available
300 struct timeval tv;
301 tv.tv_sec = 0;
302 tv.tv_usec = 0;
0ed9a934 303
05718a98 304 const int fd = m_file->fd();
0ed9a934 305
05718a98 306 fd_set readfds;
0ed9a934 307
05718a98
VZ
308 wxFD_ZERO(&readfds);
309 wxFD_SET(fd, &readfds);
0ed9a934 310
05718a98
VZ
311 switch ( select(fd + 1, &readfds, NULL, NULL, &tv) )
312 {
313 case -1:
314 wxLogSysError(_("Impossible to get child process input"));
315 // fall through
62705a27 316
05718a98
VZ
317 case 0:
318 return false;
518b5d2f 319
05718a98
VZ
320 default:
321 wxFAIL_MSG(_T("unexpected select() return value"));
322 // still fall through
518b5d2f 323
05718a98
VZ
324 case 1:
325 // input available -- or maybe not, as select() returns 1 when a
326 // read() will complete without delay, but it could still not read
327 // anything
328 return !Eof();
329 }
518b5d2f
VZ
330}
331
05718a98
VZ
332#endif // HAS_PIPE_INPUT_STREAM
333
2c8e4738
VZ
334// ----------------------------------------------------------------------------
335// wxShell
336// ----------------------------------------------------------------------------
337
338static wxString wxMakeShellCommand(const wxString& command)
518b5d2f
VZ
339{
340 wxString cmd;
cd6ce4a9 341 if ( !command )
2c8e4738
VZ
342 {
343 // just an interactive shell
cd6ce4a9 344 cmd = _T("xterm");
2c8e4738 345 }
518b5d2f 346 else
2c8e4738
VZ
347 {
348 // execute command in a shell
349 cmd << _T("/bin/sh -c '") << command << _T('\'');
350 }
351
352 return cmd;
353}
354
355bool wxShell(const wxString& command)
356{
fbf456aa 357 return wxExecute(wxMakeShellCommand(command), wxEXEC_SYNC) == 0;
2c8e4738
VZ
358}
359
360bool wxShell(const wxString& command, wxArrayString& output)
361{
9d8aca48 362 wxCHECK_MSG( !command.empty(), false, _T("can't exec shell non interactively") );
518b5d2f 363
2c8e4738 364 return wxExecute(wxMakeShellCommand(command), output);
518b5d2f
VZ
365}
366
05718a98 367namespace
f6ba47d9 368{
05718a98
VZ
369
370// helper class for storing arguments as char** array suitable for passing to
371// execvp(), whatever form they were passed to us
372class ArgsArray
373{
374public:
375 ArgsArray(const wxArrayString& args)
f6ba47d9 376 {
05718a98 377 Init(args.size());
f6ba47d9 378
05718a98
VZ
379 for ( int i = 0; i < m_argc; i++ )
380 {
381 m_argv[i] = wxStrdup(args[i]);
382 }
383 }
f6ba47d9 384
d7ef641d 385#if wxUSE_UNICODE
05718a98
VZ
386 ArgsArray(wchar_t **wargv)
387 {
388 int argc = 0;
389 while ( *wargv++ )
390 argc++;
391
392 Init(argc);
393
394 for ( int i = 0; i < m_argc; i++ )
395 {
396 m_argv[i] = wxSafeConvertWX2MB(wargv[i]).release();
397 }
f6ba47d9 398 }
d7ef641d 399#endif // wxUSE_UNICODE
f6ba47d9 400
05718a98
VZ
401 ~ArgsArray()
402 {
403 for ( int i = 0; i < m_argc; i++ )
404 {
405 free(m_argv[i]);
406 }
407
408 delete [] m_argv;
409 }
410
411 operator char**() const { return m_argv; }
412
413private:
414 void Init(int argc)
415 {
416 m_argc = argc;
417 m_argv = new char *[m_argc + 1];
418 m_argv[m_argc] = NULL;
419 }
420
421 int m_argc;
422 char **m_argv;
423
9b4fd94a 424 DECLARE_NO_COPY_CLASS(ArgsArray)
05718a98
VZ
425};
426
427} // anonymous namespace
f6ba47d9 428
cd6ce4a9 429// ----------------------------------------------------------------------------
05718a98 430// wxExecute implementations
cd6ce4a9 431// ----------------------------------------------------------------------------
6dc6fda6 432
05718a98
VZ
433#if defined(__DARWIN__)
434bool wxMacLaunch(char **argv);
435#endif
1e6feb95 436
05718a98 437long wxExecute(const wxString& command, int flags, wxProcess *process)
8b33ae2d 438{
05718a98 439 wxArrayString args;
cd6ce4a9 440
05718a98 441 const char *cptr = command.c_str();
cd6ce4a9 442
05718a98
VZ
443 // split the command line in arguments
444 //
445 // TODO: combine this with wxCmdLineParser::ConvertStringToArgs(), it
446 // doesn't do exactly the same thing right now but it's pretty close
447 // and we shouldn't maintain 2 copies of this code
448 do
449 {
450 wxString argument;
451 char quotechar = '\0'; // is arg quoted?
452 bool escaped = false;
80d6dc0a 453
05718a98
VZ
454 // eat leading whitespace:
455 while ( wxIsspace(*cptr) )
456 cptr++;
17a1ebd1 457
05718a98
VZ
458 if ( *cptr == '\'' || *cptr == '"' )
459 quotechar = *cptr++;
17a1ebd1 460
05718a98
VZ
461 do
462 {
463 if ( *cptr == '\\' && !escaped )
464 {
465 escaped = true;
466 cptr++;
467 continue;
468 }
8b33ae2d 469
05718a98
VZ
470 // all other characters:
471 argument += *cptr++;
472 escaped = false;
8b33ae2d 473
05718a98
VZ
474 // have we reached the end of the argument?
475 if ( (*cptr == quotechar && !escaped)
476 || (quotechar == '\0' && wxIsspace(*cptr))
477 || *cptr == '\0' )
478 {
479 args.push_back(argument);
cd6ce4a9 480
05718a98
VZ
481 // if not at end of buffer, swallow last character:
482 if ( *cptr )
483 cptr++;
484
485 break; // done with this one, start over
486 }
487 } while ( *cptr );
488 } while ( *cptr );
489
490 ArgsArray argv(args);
491
492 // do execute the command
493 return wxExecute(argv, flags, process);
8b33ae2d
GL
494}
495
d7ef641d
VZ
496#if wxUSE_UNICODE
497
05718a98
VZ
498long wxExecute(wchar_t **wargv, int flags, wxProcess *process)
499{
500 ArgsArray argv(wargv);
1e6feb95 501
05718a98
VZ
502 return wxExecute(argv, flags, process);
503}
79066131 504
d7ef641d
VZ
505#endif // wxUSE_UNICODE
506
05718a98
VZ
507// wxExecute: the real worker function
508long wxExecute(char **argv, int flags, wxProcess *process)
518b5d2f 509{
f6bcfd97 510 // for the sync execution, we return -1 to indicate failure, but for async
accb3257
VZ
511 // case we return 0 which is never a valid PID
512 //
513 // we define this as a macro, not a variable, to avoid compiler warnings
514 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
fbf456aa 515 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
f6bcfd97 516
accb3257 517 wxCHECK_MSG( *argv, ERROR_RETURN_CODE, wxT("can't exec empty command") );
518b5d2f 518
05718a98
VZ
519#if wxUSE_THREADS
520 // fork() doesn't mix well with POSIX threads: on many systems the program
521 // deadlocks or crashes for some reason. Probably our code is buggy and
522 // doesn't do something which must be done to allow this to work, but I
523 // don't know what yet, so for now just warn the user (this is the least we
524 // can do) about it
525 wxASSERT_MSG( wxThread::IsMain(),
526 _T("wxExecute() can be called only from the main thread") );
527#endif // wxUSE_THREADS
05079acc 528
05718a98
VZ
529#if defined(__DARWIN__)
530 // wxMacLaunch() only executes app bundles and only does it asynchronously.
531 // It returns false if the target is not an app bundle, thus falling
532 // through to the regular code for non app bundles.
533 if ( !(flags & wxEXEC_SYNC) && wxMacLaunch(argv) )
e90c1d2a 534 {
05718a98
VZ
535 // we don't have any PID to return so just make up something non null
536 return -1;
05079acc 537 }
05718a98
VZ
538#endif // __DARWIN__
539
540
541 // this struct contains all information which we use for housekeeping
e2478fde
VZ
542 wxExecuteData execData;
543 execData.flags = flags;
544 execData.process = process;
545
518b5d2f 546 // create pipes
3bbd09c3 547 if ( !execData.pipeEndProcDetect.Create() )
518b5d2f 548 {
cd6ce4a9 549 wxLogError( _("Failed to execute '%s'\n"), *argv );
e90c1d2a 550
accb3257 551 return ERROR_RETURN_CODE;
518b5d2f
VZ
552 }
553
f6bcfd97 554 // pipes for inter process communication
b477f956
VZ
555 wxPipe pipeIn, // stdin
556 pipeOut, // stdout
557 pipeErr; // stderr
cd6ce4a9
VZ
558
559 if ( process && process->IsRedirected() )
8b33ae2d 560 {
b477f956 561 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
8b33ae2d 562 {
cd6ce4a9 563 wxLogError( _("Failed to execute '%s'\n"), *argv );
8b33ae2d 564
accb3257 565 return ERROR_RETURN_CODE;
8b33ae2d
GL
566 }
567 }
8b33ae2d 568
518b5d2f 569 // fork the process
ef5f8ab6
VZ
570 //
571 // NB: do *not* use vfork() here, it completely breaks this code for some
572 // reason under Solaris (and maybe others, although not under Linux)
b2ddee86
JJ
573 // But on OpenVMS we do not have fork so we have to use vfork and
574 // cross our fingers that it works.
575#ifdef __VMS
576 pid_t pid = vfork();
577#else
578 pid_t pid = fork();
579#endif
580 if ( pid == -1 ) // error?
518b5d2f
VZ
581 {
582 wxLogSysError( _("Fork failed") );
e90c1d2a 583
accb3257 584 return ERROR_RETURN_CODE;
518b5d2f 585 }
cd6ce4a9 586 else if ( pid == 0 ) // we're in child
518b5d2f 587 {
cd6ce4a9 588 // These lines close the open file descriptors to to avoid any
518b5d2f 589 // input/output which might block the process or irritate the user. If
cd6ce4a9
VZ
590 // one wants proper IO for the subprocess, the right thing to do is to
591 // start an xterm executing it.
fbf456aa 592 if ( !(flags & wxEXEC_SYNC) )
518b5d2f 593 {
35ef537b
VZ
594 // FD_SETSIZE is unsigned under BSD, signed under other platforms
595 // so we need a cast to avoid warnings on all platforms
596 for ( int fd = 0; fd < (int)FD_SETSIZE; fd++ )
518b5d2f 597 {
b477f956
VZ
598 if ( fd == pipeIn[wxPipe::Read]
599 || fd == pipeOut[wxPipe::Write]
600 || fd == pipeErr[wxPipe::Write]
3bbd09c3 601 || fd == (execData.pipeEndProcDetect)[wxPipe::Write] )
cd6ce4a9
VZ
602 {
603 // don't close this one, we still need it
604 continue;
605 }
e90c1d2a 606
b477f956 607 // leave stderr opened too, it won't do any harm
e90c1d2a 608 if ( fd != STDERR_FILENO )
518b5d2f
VZ
609 close(fd);
610 }
0c9c4401 611 }
e1082c9f 612
e8e776aa 613#if !defined(__VMS) && !defined(__EMX__)
0c9c4401
VZ
614 if ( flags & wxEXEC_MAKE_GROUP_LEADER )
615 {
616 // Set process group to child process' pid. Then killing -pid
617 // of the parent will kill the process and all of its children.
618 setsid();
518b5d2f 619 }
0c9c4401
VZ
620#endif // !__VMS
621
0c9c4401 622 // reading side can be safely closed but we should keep the write one
3bbd09c3
VZ
623 // opened, it will be only closed when the process terminates resulting
624 // in a read notification to the parent
625 execData.pipeEndProcDetect.Detach(wxPipe::Write);
626 execData.pipeEndProcDetect.Close();
518b5d2f 627
80d6dc0a 628 // redirect stdin, stdout and stderr
b477f956 629 if ( pipeIn.IsOk() )
cd6ce4a9 630 {
b477f956
VZ
631 if ( dup2(pipeIn[wxPipe::Read], STDIN_FILENO) == -1 ||
632 dup2(pipeOut[wxPipe::Write], STDOUT_FILENO) == -1 ||
633 dup2(pipeErr[wxPipe::Write], STDERR_FILENO) == -1 )
cd6ce4a9 634 {
f6bcfd97 635 wxLogSysError(_("Failed to redirect child process input/output"));
cd6ce4a9 636 }
518b5d2f 637
b477f956
VZ
638 pipeIn.Close();
639 pipeOut.Close();
640 pipeErr.Close();
cd6ce4a9 641 }
518b5d2f 642
05718a98 643 execvp(*argv, argv);
17a1ebd1 644
d264d709 645 fprintf(stderr, "execvp(");
05718a98
VZ
646 for ( char **a = argv; *a; a++ )
647 fprintf(stderr, "%s%s", a == argv ? "" : ", ", *a);
d264d709
VZ
648 fprintf(stderr, ") failed with error %d!\n", errno);
649
518b5d2f 650 // there is no return after successful exec()
518b5d2f 651 _exit(-1);
1d8dd65e
VZ
652
653 // some compilers complain about missing return - of course, they
654 // should know that exit() doesn't return but what else can we do if
655 // they don't?
b477f956
VZ
656 //
657 // and, sure enough, other compilers complain about unreachable code
658 // after exit() call, so we can just always have return here...
1d8dd65e
VZ
659#if defined(__VMS) || defined(__INTEL_COMPILER)
660 return 0;
661#endif
518b5d2f 662 }
cd6ce4a9 663 else // we're in parent
518b5d2f 664 {
7764f973
VZ
665 // save it for WaitForChild() use
666 execData.pid = pid;
667
80d6dc0a
VZ
668 // prepare for IO redirection
669
1f3b2af0 670#if HAS_PIPE_INPUT_STREAM
80d6dc0a
VZ
671 // the input buffer bufOut is connected to stdout, this is why it is
672 // called bufOut and not bufIn
673 wxStreamTempInputBuffer bufOut,
674 bufErr;
0e300ddd 675
cd6ce4a9
VZ
676 if ( process && process->IsRedirected() )
677 {
80d6dc0a
VZ
678 wxOutputStream *inStream =
679 new wxFileOutputStream(pipeIn.Detach(wxPipe::Write));
b477f956 680
33343395
VZ
681 const int fdOut = pipeOut.Detach(wxPipe::Read);
682 wxPipeInputStream *outStream = new wxPipeInputStream(fdOut);
b477f956 683
33343395
VZ
684 const int fdErr = pipeErr.Detach(wxPipe::Read);
685 wxPipeInputStream *errStream = new wxPipeInputStream(fdErr);
f6bcfd97 686
80d6dc0a 687 process->SetPipeStreams(outStream, inStream, errStream);
0e300ddd 688
80d6dc0a 689 bufOut.Init(outStream);
b477f956 690 bufErr.Init(errStream);
e2478fde
VZ
691
692 execData.bufOut = &bufOut;
693 execData.bufErr = &bufErr;
33343395
VZ
694
695 execData.fdOut = fdOut;
696 execData.fdErr = fdErr;
b477f956 697 }
33343395 698#endif // HAS_PIPE_INPUT_STREAM
1e6feb95 699
b477f956
VZ
700 if ( pipeIn.IsOk() )
701 {
702 pipeIn.Close();
703 pipeOut.Close();
704 pipeErr.Close();
cd6ce4a9
VZ
705 }
706
05718a98
VZ
707 // we want this function to work even if there is no wxApp so ensure
708 // that we have a valid traits pointer
709 wxConsoleAppTraits traitsConsole;
710 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
711 if ( !traits )
712 traits = &traitsConsole;
713
e2478fde 714 return traits->WaitForChild(execData);
518b5d2f 715 }
79656e30 716
17a1ebd1 717#if !defined(__VMS) && !defined(__INTEL_COMPILER)
79656e30 718 return ERROR_RETURN_CODE;
ef0ed19e 719#endif
17a1ebd1 720}
518b5d2f 721
accb3257 722#undef ERROR_RETURN_CODE
f6bcfd97 723
518b5d2f
VZ
724// ----------------------------------------------------------------------------
725// file and directory functions
726// ----------------------------------------------------------------------------
727
05079acc 728const wxChar* wxGetHomeDir( wxString *home )
518b5d2f 729{
14d63513 730 *home = wxGetUserHome();
79066131 731 wxString tmp;
8ea92b4d 732 if ( home->empty() )
223d09f6 733 *home = wxT("/");
181cbcf4 734#ifdef __VMS
79066131
VZ
735 tmp = *home;
736 if ( tmp.Last() != wxT(']'))
737 if ( tmp.Last() != wxT('/')) *home << wxT('/');
181cbcf4 738#endif
518b5d2f
VZ
739 return home->c_str();
740}
741
14d63513 742wxString wxGetUserHome( const wxString &user )
518b5d2f
VZ
743{
744 struct passwd *who = (struct passwd *) NULL;
745
0fb67cd1 746 if ( !user )
518b5d2f 747 {
e90c1d2a 748 wxChar *ptr;
518b5d2f 749
223d09f6 750 if ((ptr = wxGetenv(wxT("HOME"))) != NULL)
518b5d2f
VZ
751 {
752 return ptr;
753 }
14d63513
VZ
754
755 if ((ptr = wxGetenv(wxT("USER"))) != NULL ||
756 (ptr = wxGetenv(wxT("LOGNAME"))) != NULL)
518b5d2f 757 {
69c928ef 758 who = getpwnam(wxSafeConvertWX2MB(ptr));
518b5d2f
VZ
759 }
760
14d63513
VZ
761 // make sure the user exists!
762 if ( !who )
518b5d2f
VZ
763 {
764 who = getpwuid(getuid());
765 }
766 }
767 else
768 {
05079acc 769 who = getpwnam (user.mb_str());
518b5d2f
VZ
770 }
771
69c928ef 772 return wxSafeConvertMB2WX(who ? who->pw_dir : 0);
518b5d2f
VZ
773}
774
775// ----------------------------------------------------------------------------
0fb67cd1 776// network and user id routines
518b5d2f
VZ
777// ----------------------------------------------------------------------------
778
8bb6b2c0
VZ
779// private utility function which returns output of the given command, removing
780// the trailing newline
781static wxString wxGetCommandOutput(const wxString &cmd)
782{
783 FILE *f = popen(cmd.ToAscii(), "r");
784 if ( !f )
785 {
786 wxLogSysError(_T("Executing \"%s\" failed"), cmd.c_str());
787 return wxEmptyString;
788 }
789
790 wxString s;
791 char buf[256];
792 while ( !feof(f) )
793 {
794 if ( !fgets(buf, sizeof(buf), f) )
795 break;
796
797 s += wxString::FromAscii(buf);
798 }
799
800 pclose(f);
801
802 if ( !s.empty() && s.Last() == _T('\n') )
803 s.RemoveLast();
804
805 return s;
806}
807
0fb67cd1
VZ
808// retrieve either the hostname or FQDN depending on platform (caller must
809// check whether it's one or the other, this is why this function is for
810// private use only)
05079acc 811static bool wxGetHostNameInternal(wxChar *buf, int sz)
518b5d2f 812{
9d8aca48 813 wxCHECK_MSG( buf, false, wxT("NULL pointer in wxGetHostNameInternal") );
518b5d2f 814
223d09f6 815 *buf = wxT('\0');
518b5d2f
VZ
816
817 // we're using uname() which is POSIX instead of less standard sysinfo()
818#if defined(HAVE_UNAME)
cc743a6f 819 struct utsname uts;
518b5d2f
VZ
820 bool ok = uname(&uts) != -1;
821 if ( ok )
822 {
69c928ef 823 wxStrncpy(buf, wxSafeConvertMB2WX(uts.nodename), sz - 1);
223d09f6 824 buf[sz] = wxT('\0');
518b5d2f
VZ
825 }
826#elif defined(HAVE_GETHOSTNAME)
1870f50b
RD
827 char cbuf[sz];
828 bool ok = gethostname(cbuf, sz) != -1;
829 if ( ok )
830 {
69c928ef 831 wxStrncpy(buf, wxSafeConvertMB2WX(cbuf), sz - 1);
1870f50b
RD
832 buf[sz] = wxT('\0');
833 }
0fb67cd1 834#else // no uname, no gethostname
223d09f6 835 wxFAIL_MSG(wxT("don't know host name for this machine"));
518b5d2f 836
9d8aca48 837 bool ok = false;
0fb67cd1 838#endif // uname/gethostname
518b5d2f
VZ
839
840 if ( !ok )
841 {
842 wxLogSysError(_("Cannot get the hostname"));
843 }
844
845 return ok;
846}
847
05079acc 848bool wxGetHostName(wxChar *buf, int sz)
0fb67cd1
VZ
849{
850 bool ok = wxGetHostNameInternal(buf, sz);
851
852 if ( ok )
853 {
854 // BSD systems return the FQDN, we only want the hostname, so extract
855 // it (we consider that dots are domain separators)
223d09f6 856 wxChar *dot = wxStrchr(buf, wxT('.'));
0fb67cd1
VZ
857 if ( dot )
858 {
859 // nuke it
223d09f6 860 *dot = wxT('\0');
0fb67cd1
VZ
861 }
862 }
863
864 return ok;
865}
866
05079acc 867bool wxGetFullHostName(wxChar *buf, int sz)
0fb67cd1
VZ
868{
869 bool ok = wxGetHostNameInternal(buf, sz);
870
871 if ( ok )
872 {
223d09f6 873 if ( !wxStrchr(buf, wxT('.')) )
0fb67cd1 874 {
69c928ef 875 struct hostent *host = gethostbyname(wxSafeConvertWX2MB(buf));
0fb67cd1
VZ
876 if ( !host )
877 {
878 wxLogSysError(_("Cannot get the official hostname"));
879
9d8aca48 880 ok = false;
0fb67cd1
VZ
881 }
882 else
883 {
884 // the canonical name
69c928ef 885 wxStrncpy(buf, wxSafeConvertMB2WX(host->h_name), sz);
0fb67cd1
VZ
886 }
887 }
888 //else: it's already a FQDN (BSD behaves this way)
889 }
890
891 return ok;
892}
893
05079acc 894bool wxGetUserId(wxChar *buf, int sz)
518b5d2f
VZ
895{
896 struct passwd *who;
897
223d09f6 898 *buf = wxT('\0');
518b5d2f
VZ
899 if ((who = getpwuid(getuid ())) != NULL)
900 {
69c928ef 901 wxStrncpy (buf, wxSafeConvertMB2WX(who->pw_name), sz - 1);
9d8aca48 902 return true;
518b5d2f
VZ
903 }
904
9d8aca48 905 return false;
518b5d2f
VZ
906}
907
05079acc 908bool wxGetUserName(wxChar *buf, int sz)
518b5d2f 909{
69c928ef 910#ifdef HAVE_PW_GECOS
518b5d2f 911 struct passwd *who;
518b5d2f 912
223d09f6 913 *buf = wxT('\0');
b12915c1
VZ
914 if ((who = getpwuid (getuid ())) != NULL)
915 {
b12915c1 916 char *comma = strchr(who->pw_gecos, ',');
518b5d2f
VZ
917 if (comma)
918 *comma = '\0'; // cut off non-name comment fields
69c928ef 919 wxStrncpy (buf, wxSafeConvertMB2WX(who->pw_gecos), sz - 1);
9d8aca48 920 return true;
518b5d2f
VZ
921 }
922
9d8aca48 923 return false;
69c928ef
VZ
924#else // !HAVE_PW_GECOS
925 return wxGetUserId(buf, sz);
926#endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
518b5d2f
VZ
927}
928
c655557f
VZ
929bool wxIsPlatform64Bit()
930{
2f6aa043
VZ
931 const wxString machine = wxGetCommandOutput(wxT("uname -m"));
932
933 // the test for "64" is obviously not 100% reliable but seems to work fine
934 // in practice
935 return machine.Contains(wxT("64")) ||
936 machine.Contains(wxT("alpha"));
c655557f
VZ
937}
938
939// these functions are in mac/utils.cpp for wxMac
940#ifndef __WXMAC__
941
8bb6b2c0
VZ
942wxOperatingSystemId wxGetOsVersion(int *verMaj, int *verMin)
943{
944 // get OS version
945 int major, minor;
946 wxString release = wxGetCommandOutput(wxT("uname -r"));
86501081
VS
947 if ( release.empty() ||
948 wxSscanf(release.c_str(), wxT("%d.%d"), &major, &minor) != 2 )
8bb6b2c0 949 {
e1379e29 950 // failed to get version string or unrecognized format
8bb6b2c0
VZ
951 major =
952 minor = -1;
953 }
954
955 if ( verMaj )
956 *verMaj = major;
957 if ( verMin )
958 *verMin = minor;
959
960 // try to understand which OS are we running
961 wxString kernel = wxGetCommandOutput(wxT("uname -s"));
962 if ( kernel.empty() )
963 kernel = wxGetCommandOutput(wxT("uname -o"));
964
965 if ( kernel.empty() )
966 return wxOS_UNKNOWN;
967
968 return wxPlatformInfo::GetOperatingSystemId(kernel);
969}
970
bdc72a22
VZ
971wxString wxGetOsDescription()
972{
8bb6b2c0 973 return wxGetCommandOutput(wxT("uname -s -r -m"));
bdc72a22
VZ
974}
975
e2478fde 976#endif // !__WXMAC__
bd3277fe 977
c1cb4153
VZ
978unsigned long wxGetProcessId()
979{
980 return (unsigned long)getpid();
981}
982
9d8aca48 983wxMemorySize wxGetFreeMemory()
bd3277fe
VZ
984{
985#if defined(__LINUX__)
986 // get it from /proc/meminfo
987 FILE *fp = fopen("/proc/meminfo", "r");
988 if ( fp )
989 {
990 long memFree = -1;
991
992 char buf[1024];
993 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
994 {
7c28d921
VZ
995 // /proc/meminfo changed its format in kernel 2.6
996 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
997 {
998 unsigned long cached, buffers;
999 sscanf(buf, "MemFree: %ld", &memFree);
1000
1001 fgets(buf, WXSIZEOF(buf), fp);
1002 sscanf(buf, "Buffers: %lu", &buffers);
1003
1004 fgets(buf, WXSIZEOF(buf), fp);
1005 sscanf(buf, "Cached: %lu", &cached);
1006
1007 // add to "MemFree" also the "Buffers" and "Cached" values as
1008 // free(1) does as otherwise the value never makes sense: for
1009 // kernel 2.6 it's always almost 0
1010 memFree += buffers + cached;
1011
1012 // values here are always expressed in kB and we want bytes
1013 memFree *= 1024;
1014 }
1015 else // Linux 2.4 (or < 2.6, anyhow)
1016 {
1017 long memTotal, memUsed;
1018 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
1019 }
bd3277fe
VZ
1020 }
1021
1022 fclose(fp);
1023
9d8aca48 1024 return (wxMemorySize)memFree;
bd3277fe 1025 }
9ad34f61
VZ
1026#elif defined(__SGI__)
1027 struct rminfo realmem;
1028 if ( sysmp(MP_SAGET, MPSA_RMINFO, &realmem, sizeof realmem) == 0 )
1029 return ((wxMemorySize)realmem.physmem * sysconf(_SC_PAGESIZE));
40f00746
VZ
1030#elif defined(_SC_AVPHYS_PAGES)
1031 return ((wxMemorySize)sysconf(_SC_AVPHYS_PAGES))*sysconf(_SC_PAGESIZE);
bd3277fe
VZ
1032//#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1033#endif
1034
1035 // can't find it out
1036 return -1;
1037}
1038
7ba7c4e6 1039bool wxGetDiskSpace(const wxString& path, wxDiskspaceSize_t *pTotal, wxDiskspaceSize_t *pFree)
eadd7bd2 1040{
9952adac 1041#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
fbfb3fb3 1042 // the case to "char *" is needed for AIX 4.3
85da04e9
VZ
1043 wxStatfs_t fs;
1044 if ( wxStatfs((char *)(const char*)path.fn_str(), &fs) != 0 )
eadd7bd2 1045 {
401eb3de 1046 wxLogSysError( wxT("Failed to get file system statistics") );
eadd7bd2 1047
9d8aca48 1048 return false;
eadd7bd2
VZ
1049 }
1050
125cb99b
VZ
1051 // under Solaris we also have to use f_frsize field instead of f_bsize
1052 // which is in general a multiple of f_frsize
1053#ifdef HAVE_STATVFS
7ba7c4e6 1054 wxDiskspaceSize_t blockSize = fs.f_frsize;
125cb99b 1055#else // HAVE_STATFS
7ba7c4e6 1056 wxDiskspaceSize_t blockSize = fs.f_bsize;
125cb99b 1057#endif // HAVE_STATVFS/HAVE_STATFS
9952adac 1058
eadd7bd2
VZ
1059 if ( pTotal )
1060 {
7ba7c4e6 1061 *pTotal = wxDiskspaceSize_t(fs.f_blocks) * blockSize;
eadd7bd2
VZ
1062 }
1063
1064 if ( pFree )
1065 {
7ba7c4e6 1066 *pFree = wxDiskspaceSize_t(fs.f_bavail) * blockSize;
eadd7bd2
VZ
1067 }
1068
9d8aca48 1069 return true;
125cb99b 1070#else // !HAVE_STATFS && !HAVE_STATVFS
9d8aca48 1071 return false;
125cb99b 1072#endif // HAVE_STATFS
eadd7bd2
VZ
1073}
1074
8fd0d89b
VZ
1075// ----------------------------------------------------------------------------
1076// env vars
1077// ----------------------------------------------------------------------------
1078
c0472c7c
VZ
1079#if USE_PUTENV
1080
1081WX_DECLARE_STRING_HASH_MAP(char *, wxEnvVars);
1082
1083static wxEnvVars gs_envVars;
1084
1085class wxSetEnvModule : public wxModule
1086{
1087public:
1088 virtual bool OnInit() { return true; }
1089 virtual void OnExit()
1090 {
1091 for ( wxEnvVars::const_iterator i = gs_envVars.begin();
1092 i != gs_envVars.end();
1093 ++i )
1094 {
1095 free(i->second);
1096 }
1097
1098 gs_envVars.clear();
1099 }
1100
1101 DECLARE_DYNAMIC_CLASS(wxSetEnvModule)
1102};
1103
1104IMPLEMENT_DYNAMIC_CLASS(wxSetEnvModule, wxModule)
1105
1106#endif // USE_PUTENV
1107
97b305b7 1108bool wxGetEnv(const wxString& var, wxString *value)
308978f6
VZ
1109{
1110 // wxGetenv is defined as getenv()
86501081 1111 char *p = wxGetenv(var);
308978f6 1112 if ( !p )
9d8aca48 1113 return false;
308978f6
VZ
1114
1115 if ( value )
1116 {
1117 *value = p;
1118 }
1119
9d8aca48 1120 return true;
308978f6
VZ
1121}
1122
90a77e64 1123static bool wxDoSetEnv(const wxString& variable, const char *value)
8fd0d89b
VZ
1124{
1125#if defined(HAVE_SETENV)
a1353ea4
VZ
1126 if ( !value )
1127 {
1128#ifdef HAVE_UNSETENV
65fd2fc2
VZ
1129 // don't test unsetenv() return value: it's void on some systems (at
1130 // least Darwin)
1131 unsetenv(variable.mb_str());
022a8d02 1132 return true;
a1353ea4
VZ
1133#else
1134 value = ""; // we can't pass NULL to setenv()
1135#endif
1136 }
1137
90a77e64 1138 return setenv(variable.mb_str(), value, 1 /* overwrite */) == 0;
8fd0d89b
VZ
1139#elif defined(HAVE_PUTENV)
1140 wxString s = variable;
1141 if ( value )
1142 s << _T('=') << value;
1143
1144 // transform to ANSI
67479dbd 1145 const wxWX2MBbuf p = s.mb_str();
8fd0d89b 1146
8fd0d89b
VZ
1147 char *buf = (char *)malloc(strlen(p) + 1);
1148 strcpy(buf, p);
1149
c0472c7c
VZ
1150 // store the string to free() it later
1151 wxEnvVars::iterator i = gs_envVars.find(variable);
1152 if ( i != gs_envVars.end() )
1153 {
1154 free(i->second);
1155 i->second = buf;
1156 }
1157 else // this variable hadn't been set before
1158 {
1159 gs_envVars[variable] = buf;
1160 }
1161
8fd0d89b
VZ
1162 return putenv(buf) == 0;
1163#else // no way to set an env var
67479dbd 1164 return false;
8fd0d89b
VZ
1165#endif
1166}
1167
90a77e64
VS
1168bool wxSetEnv(const wxString& variable, const wxString& value)
1169{
1170 return wxDoSetEnv(variable, value.mb_str());
1171}
1172
1173bool wxUnsetEnv(const wxString& variable)
1174{
1175 return wxDoSetEnv(variable, NULL);
1176}
1177
a37a5a73
VZ
1178// ----------------------------------------------------------------------------
1179// signal handling
1180// ----------------------------------------------------------------------------
1181
1182#if wxUSE_ON_FATAL_EXCEPTION
1183
1184#include <signal.h>
1185
90350682 1186extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
a37a5a73
VZ
1187{
1188 if ( wxTheApp )
1189 {
1190 // give the user a chance to do something special about this
1191 wxTheApp->OnFatalException();
1192 }
1193
1194 abort();
1195}
1196
1197bool wxHandleFatalExceptions(bool doit)
1198{
1199 // old sig handlers
9d8aca48 1200 static bool s_savedHandlers = false;
a37a5a73
VZ
1201 static struct sigaction s_handlerFPE,
1202 s_handlerILL,
1203 s_handlerBUS,
1204 s_handlerSEGV;
1205
9d8aca48 1206 bool ok = true;
a37a5a73
VZ
1207 if ( doit && !s_savedHandlers )
1208 {
1209 // install the signal handler
1210 struct sigaction act;
1211
1212 // some systems extend it with non std fields, so zero everything
1213 memset(&act, 0, sizeof(act));
1214
1215 act.sa_handler = wxFatalSignalHandler;
1216 sigemptyset(&act.sa_mask);
1217 act.sa_flags = 0;
1218
1219 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1220 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1221 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1222 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1223 if ( !ok )
1224 {
1225 wxLogDebug(_T("Failed to install our signal handler."));
1226 }
1227
9d8aca48 1228 s_savedHandlers = true;
a37a5a73
VZ
1229 }
1230 else if ( s_savedHandlers )
1231 {
1232 // uninstall the signal handler
1233 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1234 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1235 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1236 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1237 if ( !ok )
1238 {
1239 wxLogDebug(_T("Failed to uninstall our signal handler."));
1240 }
1241
9d8aca48 1242 s_savedHandlers = false;
a37a5a73
VZ
1243 }
1244 //else: nothing to do
1245
1246 return ok;
1247}
1248
1249#endif // wxUSE_ON_FATAL_EXCEPTION
1250
e2478fde
VZ
1251// ----------------------------------------------------------------------------
1252// wxExecute support
1253// ----------------------------------------------------------------------------
1254
1d043598 1255int wxAppTraits::AddProcessCallback(wxEndProcessData *data, int fd)
e2478fde 1256{
1d043598
VZ
1257 // define a custom handler processing only the closure of the descriptor
1258 struct wxEndProcessFDIOHandler : public wxFDIOHandler
e2478fde 1259 {
1d043598
VZ
1260 wxEndProcessFDIOHandler(wxEndProcessData *data, int fd)
1261 : m_data(data), m_fd(fd)
b827d647
VZ
1262 {
1263 }
e2478fde 1264
1d043598 1265 virtual void OnReadWaiting()
e2478fde 1266 {
1d043598
VZ
1267 wxFDIODispatcher::Get()->UnregisterFD(m_fd);
1268 close(m_fd);
05df0f1b 1269
1d043598 1270 wxHandleProcessTermination(m_data);
e2478fde 1271
1d043598 1272 delete this;
bc855d09 1273 }
e2478fde 1274
b827d647
VZ
1275 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1276 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1277
1d043598
VZ
1278 wxEndProcessData * const m_data;
1279 const int m_fd;
1280 };
e2478fde 1281
1d043598
VZ
1282 wxFDIODispatcher::Get()->RegisterFD
1283 (
1284 fd,
1285 new wxEndProcessFDIOHandler(data, fd),
b827d647 1286 wxFDIO_INPUT
1d043598
VZ
1287 );
1288 return fd; // unused, but return something unique for the tag
e2478fde
VZ
1289}
1290
9d3845e8
VZ
1291bool wxAppTraits::CheckForRedirectedIO(wxExecuteData& execData)
1292{
1293#if HAS_PIPE_INPUT_STREAM
1294 bool hasIO = false;
1295
4d425dee 1296 if ( execData.bufOut && execData.bufOut->Update() )
9d3845e8 1297 hasIO = true;
9d3845e8 1298
4d425dee 1299 if ( execData.bufErr && execData.bufErr->Update() )
9d3845e8 1300 hasIO = true;
9d3845e8
VZ
1301
1302 return hasIO;
1303#else // !HAS_PIPE_INPUT_STREAM
1304 return false;
1305#endif // HAS_PIPE_INPUT_STREAM/!HAS_PIPE_INPUT_STREAM
1306}
1307
dbd1c638
VZ
1308// helper classes/functions used by WaitForChild()
1309namespace
1310{
1311
1312// convenient base class for IO handlers which are registered for read
1313// notifications only and which also stores the FD we're reading from
1314//
1315// the derived classes still have to implement OnReadWaiting()
33343395 1316class wxReadFDIOHandler : public wxFDIOHandler
46c7e1a1 1317{
33343395
VZ
1318public:
1319 wxReadFDIOHandler(wxFDIODispatcher& disp, int fd) : m_fd(fd)
46c7e1a1 1320 {
33343395
VZ
1321 if ( fd )
1322 disp.RegisterFD(fd, this, wxFDIO_INPUT);
1323 }
46c7e1a1 1324
33343395
VZ
1325 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1326 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
46c7e1a1 1327
dbd1c638 1328protected:
33343395
VZ
1329 const int m_fd;
1330
1331 DECLARE_NO_COPY_CLASS(wxReadFDIOHandler)
1332};
1333
dbd1c638
VZ
1334// class for monitoring our end of the process detection pipe, simply sets a
1335// flag when input on the pipe (which must be due to EOF) is detected
33343395
VZ
1336class wxEndHandler : public wxReadFDIOHandler
1337{
1338public:
1339 wxEndHandler(wxFDIODispatcher& disp, int fd)
1340 : wxReadFDIOHandler(disp, fd)
1341 {
1342 m_terminated = false;
1343 }
1344
1345 bool Terminated() const { return m_terminated; }
46c7e1a1 1346
33343395 1347 virtual void OnReadWaiting() { m_terminated = true; }
46c7e1a1 1348
33343395
VZ
1349private:
1350 bool m_terminated;
1351
1352 DECLARE_NO_COPY_CLASS(wxEndHandler)
1353};
1354
1355#if wxUSE_STREAMS
1356
dbd1c638
VZ
1357// class for monitoring our ends of child stdout/err, should be constructed
1358// with the FD and stream from wxExecuteData and will do nothing if they're
1359// invalid
1360//
1361// unlike wxEndHandler this class registers itself with the provided dispatcher
33343395
VZ
1362class wxRedirectedIOHandler : public wxReadFDIOHandler
1363{
1364public:
1365 wxRedirectedIOHandler(wxFDIODispatcher& disp,
1366 int fd,
1367 wxStreamTempInputBuffer *buf)
1368 : wxReadFDIOHandler(disp, fd),
1369 m_buf(buf)
1370 {
46c7e1a1 1371 }
33343395
VZ
1372
1373 virtual void OnReadWaiting()
1d043598 1374 {
33343395
VZ
1375 m_buf->Update();
1376 }
1377
1378private:
1379 wxStreamTempInputBuffer * const m_buf;
1380
1381 DECLARE_NO_COPY_CLASS(wxRedirectedIOHandler)
1382};
1383
1384#endif // wxUSE_STREAMS
1385
b827d647 1386// helper function which calls waitpid() and analyzes the result
b827d647
VZ
1387int DoWaitForChild(int pid, int flags = 0)
1388{
1389 wxASSERT_MSG( pid > 0, "invalid PID" );
1390
1391 int status, rc;
1392
1393 // loop while we're getting EINTR
1394 for ( ;; )
1395 {
1396 rc = waitpid(pid, &status, flags);
1397
1398 if ( rc != -1 || errno != EINTR )
1399 break;
1400 }
1401
1402 if ( rc == 0 )
1403 {
1404 // This can only happen if the child application closes our dummy pipe
1405 // that is used to monitor its lifetime; in that case, our best bet is
1406 // to pretend the process did terminate, because otherwise wxExecute()
1407 // would hang indefinitely (OnReadWaiting() won't be called again, the
1408 // descriptor is closed now).
1409 wxLogDebug("Child process (PID %d) still alive but pipe closed so "
1410 "generating a close notification", pid);
1411 }
1412 else if ( rc == -1 )
1413 {
1414 wxLogLastError(wxString::Format("waitpid(%d)", pid));
1415 }
1416 else // child did terminate
1417 {
1418 wxASSERT_MSG( rc == pid, "unexpected waitpid() return value" );
1419
1420 if ( WIFEXITED(status) )
1421 return WEXITSTATUS(status);
1422 else if ( WIFSIGNALED(status) )
1423 return -WTERMSIG(status);
1424 else
1425 {
1426 wxLogError("Child process (PID %d) exited for unknown reason, "
1427 "status = %d", pid, status);
1428 }
1429 }
1430
1431 return -1;
1432}
1433
1434} // anonymous namespace
1435
33343395
VZ
1436int wxAppTraits::WaitForChild(wxExecuteData& execData)
1437{
1438 if ( !(execData.flags & wxEXEC_SYNC) )
1439 {
e528a71b
VZ
1440 // asynchronous execution: just launch the process and return,
1441 // endProcData will be destroyed when it terminates (currently we leak
1442 // it if the process doesn't terminate before we do and this should be
1443 // fixed but it's not a real leak so it's not really very high
1444 // priority)
1d043598 1445 wxEndProcessData *endProcData = new wxEndProcessData;
e528a71b
VZ
1446 endProcData->process = execData.process;
1447 endProcData->pid = execData.pid;
1d043598
VZ
1448 endProcData->tag = AddProcessCallback
1449 (
1450 endProcData,
33343395 1451 execData.GetEndProcReadFD()
1d043598 1452 );
e528a71b 1453 endProcData->async = true;
46c7e1a1 1454
1d043598 1455 return execData.pid;
33343395 1456 }
e528a71b 1457 //else: synchronous execution case
33343395
VZ
1458
1459#if wxUSE_STREAMS
1460 wxProcess * const process = execData.process;
1461 if ( process && process->IsRedirected() )
1462 {
1463 // we can't simply block waiting for the child to terminate as we would
1464 // dead lock if it writes more than the pipe buffer size (typically
1465 // 4KB) bytes of output -- it would then block waiting for us to read
1466 // the data while we'd block waiting for it to terminate
1467 //
1468 // so multiplex here waiting for any input from the child or closure of
1469 // the pipe used to indicate its termination
1470 wxSelectDispatcher disp;
1471
1472 wxEndHandler endHandler(disp, execData.GetEndProcReadFD());
1473
1474 wxRedirectedIOHandler outHandler(disp, execData.fdOut, execData.bufOut),
1475 errHandler(disp, execData.fdErr, execData.bufErr);
1476
1477 while ( !endHandler.Terminated() )
1478 {
1479 disp.Dispatch();
1480 }
1481 }
1482 //else: no IO redirection, just block waiting for the child to exit
1483#endif // wxUSE_STREAMS
1484
b827d647 1485 return DoWaitForChild(execData.pid);
46c7e1a1 1486}
46c7e1a1 1487
b827d647 1488void wxHandleProcessTermination(wxEndProcessData *data)
e2478fde 1489{
b827d647
VZ
1490 data->exitcode = DoWaitForChild(data->pid, WNOHANG);
1491
e2478fde 1492 // notify user about termination if required
b827d647 1493 if ( data->process )
e2478fde 1494 {
b827d647 1495 data->process->OnTerminate(data->pid, data->exitcode);
e2478fde
VZ
1496 }
1497
e528a71b
VZ
1498 if ( data->async )
1499 {
1500 // in case of asynchronous execution we don't need this data any more
1501 // after the child terminates
1502 delete data;
1503 }
1504 else // sync execution
1505 {
1506 // let wxExecute() know that the process has terminated
1507 data->pid = 0;
1508 }
e2478fde
VZ
1509}
1510