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