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