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