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