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