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