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