]> git.saurik.com Git - wxWidgets.git/blame - src/unix/utilsunx.cpp
check for wxUSE_TIMER in headers, not the files including them
[wxWidgets.git] / src / unix / utilsunx.cpp
CommitLineData
518b5d2f 1/////////////////////////////////////////////////////////////////////////////
7520f3da 2// Name: src/unix/utilsunx.cpp
518b5d2f
VZ
3// Purpose: generic Unix implementation of many wx functions
4// Author: Vadim Zeitlin
5// Id: $Id$
6// Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
65571936 7// Licence: wxWindows licence
518b5d2f
VZ
8/////////////////////////////////////////////////////////////////////////////
9
10// ============================================================================
11// declarations
12// ============================================================================
13
14// ----------------------------------------------------------------------------
15// headers
16// ----------------------------------------------------------------------------
17
14f355c2
VS
18// for compilers that support precompilation, includes "wx.h".
19#include "wx/wxprec.h"
20
88a7a4e1
WS
21#include "wx/utils.h"
22
7520f3da
WS
23#ifndef WX_PRECOMP
24 #include "wx/string.h"
88a7a4e1 25 #include "wx/intl.h"
e4db172a 26 #include "wx/log.h"
670f9935 27 #include "wx/app.h"
0cb7e05c 28 #include "wx/wxcrtvararg.h"
7520f3da 29#endif
518b5d2f 30
46446cc2 31#include "wx/apptrait.h"
518b5d2f 32
518b5d2f 33#include "wx/process.h"
bdc72a22 34#include "wx/thread.h"
518b5d2f 35
80d6dc0a 36#include "wx/wfstream.h"
8b33ae2d 37
e2478fde 38#include "wx/unix/execute.h"
17a1ebd1
VZ
39#include "wx/unix/private.h"
40
41#include <pwd.h>
bc855d09 42#include <sys/wait.h> // waitpid()
e2478fde 43
bc023abb
MW
44#ifdef HAVE_SYS_SELECT_H
45# include <sys/select.h>
46#endif
47
1f3b2af0
VS
48#define HAS_PIPE_INPUT_STREAM (wxUSE_STREAMS && wxUSE_FILE)
49
50#if HAS_PIPE_INPUT_STREAM
2887179b
VZ
51
52// define this to let wxexec.cpp know that we know what we're doing
53#define _WX_USED_BY_WXEXECUTE_
54#include "../common/execcmn.cpp"
55
1f3b2af0 56#endif // HAS_PIPE_INPUT_STREAM
2887179b 57
ec67cff1 58#if wxUSE_BASE
e2478fde 59
74c719ed
VZ
60#if defined(__MWERKS__) && defined(__MACH__)
61 #ifndef WXWIN_OS_DESCRIPTION
62 #define WXWIN_OS_DESCRIPTION "MacOS X"
63 #endif
64 #ifndef HAVE_NANOSLEEP
65 #define HAVE_NANOSLEEP
66 #endif
67 #ifndef HAVE_UNAME
68 #define HAVE_UNAME
69 #endif
70
71 // our configure test believes we can use sigaction() if the function is
72 // available but Metrowekrs with MSL run-time does have the function but
73 // doesn't have sigaction struct so finally we can't use it...
74 #ifdef __MSL__
75 #undef wxUSE_ON_FATAL_EXCEPTION
76 #define wxUSE_ON_FATAL_EXCEPTION 0
77 #endif
8d4f85ce
SC
78#endif
79
85da04e9
VZ
80// not only the statfs syscall is called differently depending on platform, but
81// one of its incarnations, statvfs(), takes different arguments under
82// different platforms and even different versions of the same system (Solaris
83// 7 and 8): if you want to test for this, don't forget that the problems only
84// appear if the large files support is enabled
eadd7bd2 85#ifdef HAVE_STATFS
85da04e9
VZ
86 #ifdef __BSD__
87 #include <sys/param.h>
88 #include <sys/mount.h>
89 #else // !__BSD__
90 #include <sys/vfs.h>
91 #endif // __BSD__/!__BSD__
92
93 #define wxStatfs statfs
84ae7ca4
VZ
94
95 #ifndef HAVE_STATFS_DECL
96 // some systems lack statfs() prototype in the system headers (AIX 4)
97 extern "C" int statfs(const char *path, struct statfs *buf);
98 #endif
eadd7bd2
VZ
99#endif // HAVE_STATFS
100
9952adac
VZ
101#ifdef HAVE_STATVFS
102 #include <sys/statvfs.h>
103
85da04e9
VZ
104 #define wxStatfs statvfs
105#endif // HAVE_STATVFS
106
107#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
108 // WX_STATFS_T is detected by configure
109 #define wxStatfs_t WX_STATFS_T
110#endif
9952adac 111
f6bcfd97
BP
112// SGI signal.h defines signal handler arguments differently depending on
113// whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
114#if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
115 #define _LANGUAGE_C_PLUS_PLUS 1
116#endif // SGI hack
117
518b5d2f
VZ
118#include <stdarg.h>
119#include <dirent.h>
120#include <string.h>
121#include <sys/stat.h>
122#include <sys/types.h>
518b5d2f 123#include <sys/wait.h>
e2478fde 124#include <unistd.h>
518b5d2f
VZ
125#include <errno.h>
126#include <netdb.h>
127#include <signal.h>
128#include <fcntl.h> // for O_WRONLY and friends
129#include <time.h> // nanosleep() and/or usleep()
fad866f4 130#include <ctype.h> // isspace()
b12915c1 131#include <sys/time.h> // needed for FD_SETSIZE
7bcb11d3 132
0fcdf6dc 133#ifdef HAVE_UNAME
518b5d2f
VZ
134 #include <sys/utsname.h> // for uname()
135#endif // HAVE_UNAME
136
9ad34f61
VZ
137// Used by wxGetFreeMemory().
138#ifdef __SGI__
139 #include <sys/sysmp.h>
140 #include <sys/sysinfo.h> // for SAGET and MINFO structures
141#endif
142
518b5d2f
VZ
143// ----------------------------------------------------------------------------
144// conditional compilation
145// ----------------------------------------------------------------------------
146
147// many versions of Unices have this function, but it is not defined in system
148// headers - please add your system here if it is the case for your OS.
149// SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
1363811b 150#if !defined(HAVE_USLEEP) && \
d67fee71 151 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
518b5d2f 152 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
d67fee71 153 defined(__osf__) || defined(__EMX__))
518b5d2f
VZ
154 extern "C"
155 {
1a5e269b
VZ
156 #ifdef __EMX__
157 /* I copied this from the XFree86 diffs. AV. */
158 #define INCL_DOSPROCESS
159 #include <os2.h>
160 inline void usleep(unsigned long delay)
161 {
162 DosSleep(delay ? (delay/1000l) : 1l);
163 }
164 #else // Unix
1363811b 165 int usleep(unsigned int usec);
1a5e269b 166 #endif // __EMX__/Unix
518b5d2f 167 };
bdc72a22
VZ
168
169 #define HAVE_USLEEP 1
518b5d2f
VZ
170#endif // Unices without usleep()
171
518b5d2f
VZ
172// ============================================================================
173// implementation
174// ============================================================================
175
176// ----------------------------------------------------------------------------
177// sleeping
178// ----------------------------------------------------------------------------
179
180void wxSleep(int nSecs)
181{
182 sleep(nSecs);
183}
184
66cd9d7f 185void wxMicroSleep(unsigned long microseconds)
518b5d2f 186{
b12915c1 187#if defined(HAVE_NANOSLEEP)
518b5d2f 188 timespec tmReq;
66cd9d7f
VZ
189 tmReq.tv_sec = (time_t)(microseconds / 1000000);
190 tmReq.tv_nsec = (microseconds % 1000000) * 1000;
518b5d2f
VZ
191
192 // we're not interested in remaining time nor in return value
193 (void)nanosleep(&tmReq, (timespec *)NULL);
b12915c1 194#elif defined(HAVE_USLEEP)
518b5d2f
VZ
195 // uncomment this if you feel brave or if you are sure that your version
196 // of Solaris has a safe usleep() function but please notice that usleep()
197 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
198 // documented as MT-Safe
ea18eed9 199 #if defined(__SUN__) && wxUSE_THREADS
518b5d2f
VZ
200 #error "usleep() cannot be used in MT programs under Solaris."
201 #endif // Sun
202
66cd9d7f 203 usleep(microseconds);
b12915c1
VZ
204#elif defined(HAVE_SLEEP)
205 // under BeOS sleep() takes seconds (what about other platforms, if any?)
66cd9d7f 206 sleep(microseconds * 1000000);
518b5d2f 207#else // !sleep function
66cd9d7f 208 #error "usleep() or nanosleep() function required for wxMicroSleep"
518b5d2f
VZ
209#endif // sleep function
210}
211
66cd9d7f
VZ
212void wxMilliSleep(unsigned long milliseconds)
213{
214 wxMicroSleep(milliseconds*1000);
215}
216
518b5d2f
VZ
217// ----------------------------------------------------------------------------
218// process management
219// ----------------------------------------------------------------------------
220
e0f6b731 221int wxKill(long pid, wxSignal sig, wxKillError *rc, int flags)
518b5d2f 222{
e0f6b731 223 int err = kill((pid_t) (flags & wxKILL_CHILDREN) ? -pid : pid, (int)sig);
50567b69
VZ
224 if ( rc )
225 {
f0bce4d4 226 switch ( err ? errno : 0 )
50567b69
VZ
227 {
228 case 0:
229 *rc = wxKILL_OK;
230 break;
231
232 case EINVAL:
233 *rc = wxKILL_BAD_SIGNAL;
234 break;
235
236 case EPERM:
237 *rc = wxKILL_ACCESS_DENIED;
238 break;
239
240 case ESRCH:
241 *rc = wxKILL_NO_PROCESS;
242 break;
243
244 default:
245 // this goes against Unix98 docs so log it
246 wxLogDebug(_T("unexpected kill(2) return value %d"), err);
247
248 // something else...
249 *rc = wxKILL_ERROR;
250 }
251 }
252
253 return err;
518b5d2f
VZ
254}
255
fad866f4
KB
256#define WXEXECUTE_NARGS 127
257
62705a27
RN
258#if defined(__DARWIN__)
259long wxMacExecute(wxChar **argv,
260 int flags,
261 wxProcess *process);
262#endif
263
fbf456aa 264long wxExecute( const wxString& command, int flags, wxProcess *process )
518b5d2f 265{
8ea92b4d 266 wxCHECK_MSG( !command.empty(), 0, wxT("can't exec empty command") );
ba2eff22
VZ
267
268 wxLogTrace(wxT("exec"), wxT("Executing \"%s\""), command.c_str());
518b5d2f 269
647b8e37
VZ
270#if wxUSE_THREADS
271 // fork() doesn't mix well with POSIX threads: on many systems the program
272 // deadlocks or crashes for some reason. Probably our code is buggy and
273 // doesn't do something which must be done to allow this to work, but I
274 // don't know what yet, so for now just warn the user (this is the least we
275 // can do) about it
276 wxASSERT_MSG( wxThread::IsMain(),
277 _T("wxExecute() can be called only from the main thread") );
278#endif // wxUSE_THREADS
279
518b5d2f 280 int argc = 0;
05079acc 281 wxChar *argv[WXEXECUTE_NARGS];
fad866f4 282 wxString argument;
05079acc 283 const wxChar *cptr = command.c_str();
223d09f6 284 wxChar quotechar = wxT('\0'); // is arg quoted?
9d8aca48 285 bool escaped = false;
518b5d2f 286
0ed9a934 287 // split the command line in arguments
fad866f4
KB
288 do
289 {
7520f3da 290 argument = wxEmptyString;
223d09f6 291 quotechar = wxT('\0');
0ed9a934 292
fad866f4 293 // eat leading whitespace:
05079acc 294 while ( wxIsspace(*cptr) )
fad866f4 295 cptr++;
0ed9a934 296
223d09f6 297 if ( *cptr == wxT('\'') || *cptr == wxT('"') )
fad866f4 298 quotechar = *cptr++;
0ed9a934 299
fad866f4
KB
300 do
301 {
223d09f6 302 if ( *cptr == wxT('\\') && ! escaped )
fad866f4 303 {
9d8aca48 304 escaped = true;
fad866f4
KB
305 cptr++;
306 continue;
307 }
0ed9a934 308
fad866f4 309 // all other characters:
0ed9a934 310 argument += *cptr++;
9d8aca48 311 escaped = false;
0ed9a934
VZ
312
313 // have we reached the end of the argument?
314 if ( (*cptr == quotechar && ! escaped)
223d09f6
KB
315 || (quotechar == wxT('\0') && wxIsspace(*cptr))
316 || *cptr == wxT('\0') )
fad866f4 317 {
0ed9a934 318 wxASSERT_MSG( argc < WXEXECUTE_NARGS,
223d09f6 319 wxT("too many arguments in wxExecute") );
0ed9a934 320
05079acc
OK
321 argv[argc] = new wxChar[argument.length() + 1];
322 wxStrcpy(argv[argc], argument.c_str());
fad866f4 323 argc++;
0ed9a934 324
fad866f4 325 // if not at end of buffer, swallow last character:
0ed9a934
VZ
326 if(*cptr)
327 cptr++;
328
fad866f4
KB
329 break; // done with this one, start over
330 }
0ed9a934
VZ
331 } while(*cptr);
332 } while(*cptr);
fad866f4 333 argv[argc] = NULL;
0ed9a934 334
62705a27
RN
335 long lRc;
336#if defined(__DARWIN__)
3afdfec4 337 // wxMacExecute only executes app bundles.
fb19fbab
SC
338 // It returns an error code if the target is not an app bundle, thus falling
339 // through to the regular wxExecute for non app bundles.
3afdfec4 340 lRc = wxMacExecute(argv, flags, process);
fb19fbab 341 if( lRc != ((flags & wxEXEC_SYNC) ? -1 : 0))
62705a27
RN
342 return lRc;
343#endif
344
0ed9a934 345 // do execute the command
62705a27 346 lRc = wxExecute(argv, flags, process);
518b5d2f 347
0ed9a934 348 // clean up
fad866f4 349 argc = 0;
0ed9a934 350 while( argv[argc] )
fad866f4 351 delete [] argv[argc++];
518b5d2f
VZ
352
353 return lRc;
354}
355
2c8e4738
VZ
356// ----------------------------------------------------------------------------
357// wxShell
358// ----------------------------------------------------------------------------
359
360static wxString wxMakeShellCommand(const wxString& command)
518b5d2f
VZ
361{
362 wxString cmd;
cd6ce4a9 363 if ( !command )
2c8e4738
VZ
364 {
365 // just an interactive shell
cd6ce4a9 366 cmd = _T("xterm");
2c8e4738 367 }
518b5d2f 368 else
2c8e4738
VZ
369 {
370 // execute command in a shell
371 cmd << _T("/bin/sh -c '") << command << _T('\'');
372 }
373
374 return cmd;
375}
376
377bool wxShell(const wxString& command)
378{
fbf456aa 379 return wxExecute(wxMakeShellCommand(command), wxEXEC_SYNC) == 0;
2c8e4738
VZ
380}
381
382bool wxShell(const wxString& command, wxArrayString& output)
383{
9d8aca48 384 wxCHECK_MSG( !command.empty(), false, _T("can't exec shell non interactively") );
518b5d2f 385
2c8e4738 386 return wxExecute(wxMakeShellCommand(command), output);
518b5d2f
VZ
387}
388
f6ba47d9
VZ
389// Shutdown or reboot the PC
390bool wxShutdown(wxShutdownFlags wFlags)
391{
392 wxChar level;
393 switch ( wFlags )
394 {
395 case wxSHUTDOWN_POWEROFF:
396 level = _T('0');
397 break;
398
399 case wxSHUTDOWN_REBOOT:
400 level = _T('6');
401 break;
402
403 default:
404 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
9d8aca48 405 return false;
f6ba47d9
VZ
406 }
407
408 return system(wxString::Format(_T("init %c"), level).mb_str()) == 0;
409}
410
cd6ce4a9
VZ
411// ----------------------------------------------------------------------------
412// wxStream classes to support IO redirection in wxExecute
413// ----------------------------------------------------------------------------
6dc6fda6 414
1f3b2af0 415#if HAS_PIPE_INPUT_STREAM
1e6feb95 416
2b5f62a0 417bool wxPipeInputStream::CanRead() const
8b33ae2d 418{
cd6ce4a9 419 if ( m_lasterror == wxSTREAM_EOF )
9d8aca48 420 return false;
cd6ce4a9
VZ
421
422 // check if there is any input available
423 struct timeval tv;
424 tv.tv_sec = 0;
425 tv.tv_usec = 0;
426
80d6dc0a
VZ
427 const int fd = m_file->fd();
428
cd6ce4a9 429 fd_set readfds;
17a1ebd1
VZ
430
431 wxFD_ZERO(&readfds);
432 wxFD_SET(fd, &readfds);
433
80d6dc0a 434 switch ( select(fd + 1, &readfds, NULL, NULL, &tv) )
cd6ce4a9
VZ
435 {
436 case -1:
437 wxLogSysError(_("Impossible to get child process input"));
438 // fall through
8b33ae2d 439
cd6ce4a9 440 case 0:
9d8aca48 441 return false;
8b33ae2d 442
cd6ce4a9
VZ
443 default:
444 wxFAIL_MSG(_T("unexpected select() return value"));
445 // still fall through
446
447 case 1:
6f3d3c68
VZ
448 // input available -- or maybe not, as select() returns 1 when a
449 // read() will complete without delay, but it could still not read
450 // anything
451 return !Eof();
cd6ce4a9 452 }
8b33ae2d
GL
453}
454
1f3b2af0 455#endif // HAS_PIPE_INPUT_STREAM
1e6feb95 456
b477f956
VZ
457// ----------------------------------------------------------------------------
458// wxExecute: the real worker function
459// ----------------------------------------------------------------------------
79066131 460
17a1ebd1 461long wxExecute(wxChar **argv, int flags, wxProcess *process)
518b5d2f 462{
f6bcfd97 463 // for the sync execution, we return -1 to indicate failure, but for async
accb3257
VZ
464 // case we return 0 which is never a valid PID
465 //
466 // we define this as a macro, not a variable, to avoid compiler warnings
467 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
fbf456aa 468 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
f6bcfd97 469
accb3257 470 wxCHECK_MSG( *argv, ERROR_RETURN_CODE, wxT("can't exec empty command") );
518b5d2f 471
05079acc
OK
472#if wxUSE_UNICODE
473 int mb_argc = 0;
474 char *mb_argv[WXEXECUTE_NARGS];
475
e90c1d2a
VZ
476 while (argv[mb_argc])
477 {
69c928ef 478 wxWX2MBbuf mb_arg = wxSafeConvertWX2MB(argv[mb_argc]);
cd6ce4a9
VZ
479 mb_argv[mb_argc] = strdup(mb_arg);
480 mb_argc++;
05079acc
OK
481 }
482 mb_argv[mb_argc] = (char *) NULL;
e90c1d2a
VZ
483
484 // this macro will free memory we used above
485 #define ARGS_CLEANUP \
345b0247 486 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
e90c1d2a
VZ
487 free(mb_argv[mb_argc])
488#else // ANSI
489 // no need for cleanup
490 #define ARGS_CLEANUP
491
05079acc 492 wxChar **mb_argv = argv;
e90c1d2a 493#endif // Unicode/ANSI
518b5d2f 494
e2478fde
VZ
495 // we want this function to work even if there is no wxApp so ensure that
496 // we have a valid traits pointer
497 wxConsoleAppTraits traitsConsole;
498 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
499 if ( !traits )
500 traits = &traitsConsole;
501
502 // this struct contains all information which we pass to and from
503 // wxAppTraits methods
504 wxExecuteData execData;
505 execData.flags = flags;
506 execData.process = process;
507
518b5d2f 508 // create pipes
e2478fde 509 if ( !traits->CreateEndProcessPipe(execData) )
518b5d2f 510 {
cd6ce4a9 511 wxLogError( _("Failed to execute '%s'\n"), *argv );
e90c1d2a
VZ
512
513 ARGS_CLEANUP;
514
accb3257 515 return ERROR_RETURN_CODE;
518b5d2f
VZ
516 }
517
f6bcfd97 518 // pipes for inter process communication
b477f956
VZ
519 wxPipe pipeIn, // stdin
520 pipeOut, // stdout
521 pipeErr; // stderr
cd6ce4a9
VZ
522
523 if ( process && process->IsRedirected() )
8b33ae2d 524 {
b477f956 525 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
8b33ae2d 526 {
cd6ce4a9 527 wxLogError( _("Failed to execute '%s'\n"), *argv );
8b33ae2d
GL
528
529 ARGS_CLEANUP;
530
accb3257 531 return ERROR_RETURN_CODE;
8b33ae2d
GL
532 }
533 }
8b33ae2d 534
518b5d2f 535 // fork the process
ef5f8ab6
VZ
536 //
537 // NB: do *not* use vfork() here, it completely breaks this code for some
538 // reason under Solaris (and maybe others, although not under Linux)
b2ddee86
JJ
539 // But on OpenVMS we do not have fork so we have to use vfork and
540 // cross our fingers that it works.
541#ifdef __VMS
542 pid_t pid = vfork();
543#else
544 pid_t pid = fork();
545#endif
546 if ( pid == -1 ) // error?
518b5d2f
VZ
547 {
548 wxLogSysError( _("Fork failed") );
e90c1d2a
VZ
549
550 ARGS_CLEANUP;
551
accb3257 552 return ERROR_RETURN_CODE;
518b5d2f 553 }
cd6ce4a9 554 else if ( pid == 0 ) // we're in child
518b5d2f 555 {
cd6ce4a9 556 // These lines close the open file descriptors to to avoid any
518b5d2f 557 // input/output which might block the process or irritate the user. If
cd6ce4a9
VZ
558 // one wants proper IO for the subprocess, the right thing to do is to
559 // start an xterm executing it.
fbf456aa 560 if ( !(flags & wxEXEC_SYNC) )
518b5d2f 561 {
35ef537b
VZ
562 // FD_SETSIZE is unsigned under BSD, signed under other platforms
563 // so we need a cast to avoid warnings on all platforms
564 for ( int fd = 0; fd < (int)FD_SETSIZE; fd++ )
518b5d2f 565 {
b477f956
VZ
566 if ( fd == pipeIn[wxPipe::Read]
567 || fd == pipeOut[wxPipe::Write]
568 || fd == pipeErr[wxPipe::Write]
e2478fde 569 || traits->IsWriteFDOfEndProcessPipe(execData, fd) )
cd6ce4a9
VZ
570 {
571 // don't close this one, we still need it
572 continue;
573 }
e90c1d2a 574
b477f956 575 // leave stderr opened too, it won't do any harm
e90c1d2a 576 if ( fd != STDERR_FILENO )
518b5d2f
VZ
577 close(fd);
578 }
0c9c4401 579 }
e1082c9f 580
e8e776aa 581#if !defined(__VMS) && !defined(__EMX__)
0c9c4401
VZ
582 if ( flags & wxEXEC_MAKE_GROUP_LEADER )
583 {
584 // Set process group to child process' pid. Then killing -pid
585 // of the parent will kill the process and all of its children.
586 setsid();
518b5d2f 587 }
0c9c4401
VZ
588#endif // !__VMS
589
0c9c4401
VZ
590 // reading side can be safely closed but we should keep the write one
591 // opened
e2478fde 592 traits->DetachWriteFDOfEndProcessPipe(execData);
518b5d2f 593
80d6dc0a 594 // redirect stdin, stdout and stderr
b477f956 595 if ( pipeIn.IsOk() )
cd6ce4a9 596 {
b477f956
VZ
597 if ( dup2(pipeIn[wxPipe::Read], STDIN_FILENO) == -1 ||
598 dup2(pipeOut[wxPipe::Write], STDOUT_FILENO) == -1 ||
599 dup2(pipeErr[wxPipe::Write], STDERR_FILENO) == -1 )
cd6ce4a9 600 {
f6bcfd97 601 wxLogSysError(_("Failed to redirect child process input/output"));
cd6ce4a9 602 }
518b5d2f 603
b477f956
VZ
604 pipeIn.Close();
605 pipeOut.Close();
606 pipeErr.Close();
cd6ce4a9 607 }
518b5d2f 608
05079acc 609 execvp (*mb_argv, mb_argv);
17a1ebd1 610
d264d709 611 fprintf(stderr, "execvp(");
8d4f85ce
SC
612 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
613 for ( char **ppc_ = mb_argv; *ppc_; ppc_++ )
614 fprintf(stderr, "%s%s", ppc_ == mb_argv ? "" : ", ", *ppc_);
d264d709
VZ
615 fprintf(stderr, ") failed with error %d!\n", errno);
616
518b5d2f 617 // there is no return after successful exec()
518b5d2f 618 _exit(-1);
1d8dd65e
VZ
619
620 // some compilers complain about missing return - of course, they
621 // should know that exit() doesn't return but what else can we do if
622 // they don't?
b477f956
VZ
623 //
624 // and, sure enough, other compilers complain about unreachable code
625 // after exit() call, so we can just always have return here...
1d8dd65e
VZ
626#if defined(__VMS) || defined(__INTEL_COMPILER)
627 return 0;
628#endif
518b5d2f 629 }
cd6ce4a9 630 else // we're in parent
518b5d2f 631 {
cd6ce4a9
VZ
632 ARGS_CLEANUP;
633
7764f973
VZ
634 // save it for WaitForChild() use
635 execData.pid = pid;
636
80d6dc0a
VZ
637 // prepare for IO redirection
638
1f3b2af0 639#if HAS_PIPE_INPUT_STREAM
80d6dc0a
VZ
640 // the input buffer bufOut is connected to stdout, this is why it is
641 // called bufOut and not bufIn
642 wxStreamTempInputBuffer bufOut,
643 bufErr;
1f3b2af0 644#endif // HAS_PIPE_INPUT_STREAM
0e300ddd 645
cd6ce4a9
VZ
646 if ( process && process->IsRedirected() )
647 {
1f3b2af0 648#if HAS_PIPE_INPUT_STREAM
80d6dc0a
VZ
649 wxOutputStream *inStream =
650 new wxFileOutputStream(pipeIn.Detach(wxPipe::Write));
b477f956 651
79066131
VZ
652 wxPipeInputStream *outStream =
653 new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
b477f956 654
79066131
VZ
655 wxPipeInputStream *errStream =
656 new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
f6bcfd97 657
80d6dc0a 658 process->SetPipeStreams(outStream, inStream, errStream);
0e300ddd 659
80d6dc0a 660 bufOut.Init(outStream);
b477f956 661 bufErr.Init(errStream);
e2478fde
VZ
662
663 execData.bufOut = &bufOut;
664 execData.bufErr = &bufErr;
1f3b2af0 665#endif // HAS_PIPE_INPUT_STREAM
b477f956 666 }
1e6feb95 667
b477f956
VZ
668 if ( pipeIn.IsOk() )
669 {
670 pipeIn.Close();
671 pipeOut.Close();
672 pipeErr.Close();
cd6ce4a9
VZ
673 }
674
e2478fde 675 return traits->WaitForChild(execData);
518b5d2f 676 }
79656e30 677
17a1ebd1 678#if !defined(__VMS) && !defined(__INTEL_COMPILER)
79656e30 679 return ERROR_RETURN_CODE;
ef0ed19e 680#endif
17a1ebd1 681}
518b5d2f 682
accb3257 683#undef ERROR_RETURN_CODE
f6bcfd97
BP
684#undef ARGS_CLEANUP
685
518b5d2f
VZ
686// ----------------------------------------------------------------------------
687// file and directory functions
688// ----------------------------------------------------------------------------
689
05079acc 690const wxChar* wxGetHomeDir( wxString *home )
518b5d2f 691{
8ea92b4d 692 *home = wxGetUserHome( wxEmptyString );
79066131 693 wxString tmp;
8ea92b4d 694 if ( home->empty() )
223d09f6 695 *home = wxT("/");
181cbcf4 696#ifdef __VMS
79066131
VZ
697 tmp = *home;
698 if ( tmp.Last() != wxT(']'))
699 if ( tmp.Last() != wxT('/')) *home << wxT('/');
181cbcf4 700#endif
518b5d2f
VZ
701 return home->c_str();
702}
703
05079acc
OK
704#if wxUSE_UNICODE
705const wxMB2WXbuf wxGetUserHome( const wxString &user )
e90c1d2a 706#else // just for binary compatibility -- there is no 'const' here
518b5d2f 707char *wxGetUserHome( const wxString &user )
05079acc 708#endif
518b5d2f
VZ
709{
710 struct passwd *who = (struct passwd *) NULL;
711
0fb67cd1 712 if ( !user )
518b5d2f 713 {
e90c1d2a 714 wxChar *ptr;
518b5d2f 715
223d09f6 716 if ((ptr = wxGetenv(wxT("HOME"))) != NULL)
518b5d2f 717 {
2b5f62a0
VZ
718#if wxUSE_UNICODE
719 wxWCharBuffer buffer( ptr );
720 return buffer;
721#else
518b5d2f 722 return ptr;
2b5f62a0 723#endif
518b5d2f 724 }
223d09f6 725 if ((ptr = wxGetenv(wxT("USER"))) != NULL || (ptr = wxGetenv(wxT("LOGNAME"))) != NULL)
518b5d2f 726 {
69c928ef 727 who = getpwnam(wxSafeConvertWX2MB(ptr));
518b5d2f
VZ
728 }
729
730 // We now make sure the the user exists!
731 if (who == NULL)
732 {
733 who = getpwuid(getuid());
734 }
735 }
736 else
737 {
05079acc 738 who = getpwnam (user.mb_str());
518b5d2f
VZ
739 }
740
69c928ef 741 return wxSafeConvertMB2WX(who ? who->pw_dir : 0);
518b5d2f
VZ
742}
743
744// ----------------------------------------------------------------------------
0fb67cd1 745// network and user id routines
518b5d2f
VZ
746// ----------------------------------------------------------------------------
747
8bb6b2c0
VZ
748// private utility function which returns output of the given command, removing
749// the trailing newline
750static wxString wxGetCommandOutput(const wxString &cmd)
751{
752 FILE *f = popen(cmd.ToAscii(), "r");
753 if ( !f )
754 {
755 wxLogSysError(_T("Executing \"%s\" failed"), cmd.c_str());
756 return wxEmptyString;
757 }
758
759 wxString s;
760 char buf[256];
761 while ( !feof(f) )
762 {
763 if ( !fgets(buf, sizeof(buf), f) )
764 break;
765
766 s += wxString::FromAscii(buf);
767 }
768
769 pclose(f);
770
771 if ( !s.empty() && s.Last() == _T('\n') )
772 s.RemoveLast();
773
774 return s;
775}
776
0fb67cd1
VZ
777// retrieve either the hostname or FQDN depending on platform (caller must
778// check whether it's one or the other, this is why this function is for
779// private use only)
05079acc 780static bool wxGetHostNameInternal(wxChar *buf, int sz)
518b5d2f 781{
9d8aca48 782 wxCHECK_MSG( buf, false, wxT("NULL pointer in wxGetHostNameInternal") );
518b5d2f 783
223d09f6 784 *buf = wxT('\0');
518b5d2f
VZ
785
786 // we're using uname() which is POSIX instead of less standard sysinfo()
787#if defined(HAVE_UNAME)
cc743a6f 788 struct utsname uts;
518b5d2f
VZ
789 bool ok = uname(&uts) != -1;
790 if ( ok )
791 {
69c928ef 792 wxStrncpy(buf, wxSafeConvertMB2WX(uts.nodename), sz - 1);
223d09f6 793 buf[sz] = wxT('\0');
518b5d2f
VZ
794 }
795#elif defined(HAVE_GETHOSTNAME)
1870f50b
RD
796 char cbuf[sz];
797 bool ok = gethostname(cbuf, sz) != -1;
798 if ( ok )
799 {
69c928ef 800 wxStrncpy(buf, wxSafeConvertMB2WX(cbuf), sz - 1);
1870f50b
RD
801 buf[sz] = wxT('\0');
802 }
0fb67cd1 803#else // no uname, no gethostname
223d09f6 804 wxFAIL_MSG(wxT("don't know host name for this machine"));
518b5d2f 805
9d8aca48 806 bool ok = false;
0fb67cd1 807#endif // uname/gethostname
518b5d2f
VZ
808
809 if ( !ok )
810 {
811 wxLogSysError(_("Cannot get the hostname"));
812 }
813
814 return ok;
815}
816
05079acc 817bool wxGetHostName(wxChar *buf, int sz)
0fb67cd1
VZ
818{
819 bool ok = wxGetHostNameInternal(buf, sz);
820
821 if ( ok )
822 {
823 // BSD systems return the FQDN, we only want the hostname, so extract
824 // it (we consider that dots are domain separators)
223d09f6 825 wxChar *dot = wxStrchr(buf, wxT('.'));
0fb67cd1
VZ
826 if ( dot )
827 {
828 // nuke it
223d09f6 829 *dot = wxT('\0');
0fb67cd1
VZ
830 }
831 }
832
833 return ok;
834}
835
05079acc 836bool wxGetFullHostName(wxChar *buf, int sz)
0fb67cd1
VZ
837{
838 bool ok = wxGetHostNameInternal(buf, sz);
839
840 if ( ok )
841 {
223d09f6 842 if ( !wxStrchr(buf, wxT('.')) )
0fb67cd1 843 {
69c928ef 844 struct hostent *host = gethostbyname(wxSafeConvertWX2MB(buf));
0fb67cd1
VZ
845 if ( !host )
846 {
847 wxLogSysError(_("Cannot get the official hostname"));
848
9d8aca48 849 ok = false;
0fb67cd1
VZ
850 }
851 else
852 {
853 // the canonical name
69c928ef 854 wxStrncpy(buf, wxSafeConvertMB2WX(host->h_name), sz);
0fb67cd1
VZ
855 }
856 }
857 //else: it's already a FQDN (BSD behaves this way)
858 }
859
860 return ok;
861}
862
05079acc 863bool wxGetUserId(wxChar *buf, int sz)
518b5d2f
VZ
864{
865 struct passwd *who;
866
223d09f6 867 *buf = wxT('\0');
518b5d2f
VZ
868 if ((who = getpwuid(getuid ())) != NULL)
869 {
69c928ef 870 wxStrncpy (buf, wxSafeConvertMB2WX(who->pw_name), sz - 1);
9d8aca48 871 return true;
518b5d2f
VZ
872 }
873
9d8aca48 874 return false;
518b5d2f
VZ
875}
876
05079acc 877bool wxGetUserName(wxChar *buf, int sz)
518b5d2f 878{
69c928ef 879#ifdef HAVE_PW_GECOS
518b5d2f 880 struct passwd *who;
518b5d2f 881
223d09f6 882 *buf = wxT('\0');
b12915c1
VZ
883 if ((who = getpwuid (getuid ())) != NULL)
884 {
b12915c1 885 char *comma = strchr(who->pw_gecos, ',');
518b5d2f
VZ
886 if (comma)
887 *comma = '\0'; // cut off non-name comment fields
69c928ef 888 wxStrncpy (buf, wxSafeConvertMB2WX(who->pw_gecos), sz - 1);
9d8aca48 889 return true;
518b5d2f
VZ
890 }
891
9d8aca48 892 return false;
69c928ef
VZ
893#else // !HAVE_PW_GECOS
894 return wxGetUserId(buf, sz);
895#endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
518b5d2f
VZ
896}
897
c655557f
VZ
898bool wxIsPlatform64Bit()
899{
2f6aa043
VZ
900 const wxString machine = wxGetCommandOutput(wxT("uname -m"));
901
902 // the test for "64" is obviously not 100% reliable but seems to work fine
903 // in practice
904 return machine.Contains(wxT("64")) ||
905 machine.Contains(wxT("alpha"));
c655557f
VZ
906}
907
908// these functions are in mac/utils.cpp for wxMac
909#ifndef __WXMAC__
910
8bb6b2c0
VZ
911wxOperatingSystemId wxGetOsVersion(int *verMaj, int *verMin)
912{
913 // get OS version
914 int major, minor;
915 wxString release = wxGetCommandOutput(wxT("uname -r"));
86501081
VS
916 if ( release.empty() ||
917 wxSscanf(release.c_str(), wxT("%d.%d"), &major, &minor) != 2 )
8bb6b2c0 918 {
e1379e29 919 // failed to get version string or unrecognized format
8bb6b2c0
VZ
920 major =
921 minor = -1;
922 }
923
924 if ( verMaj )
925 *verMaj = major;
926 if ( verMin )
927 *verMin = minor;
928
929 // try to understand which OS are we running
930 wxString kernel = wxGetCommandOutput(wxT("uname -s"));
931 if ( kernel.empty() )
932 kernel = wxGetCommandOutput(wxT("uname -o"));
933
934 if ( kernel.empty() )
935 return wxOS_UNKNOWN;
936
937 return wxPlatformInfo::GetOperatingSystemId(kernel);
938}
939
bdc72a22
VZ
940wxString wxGetOsDescription()
941{
8bb6b2c0 942 return wxGetCommandOutput(wxT("uname -s -r -m"));
bdc72a22
VZ
943}
944
e2478fde 945#endif // !__WXMAC__
bd3277fe 946
c1cb4153
VZ
947unsigned long wxGetProcessId()
948{
949 return (unsigned long)getpid();
950}
951
9d8aca48 952wxMemorySize wxGetFreeMemory()
bd3277fe
VZ
953{
954#if defined(__LINUX__)
955 // get it from /proc/meminfo
956 FILE *fp = fopen("/proc/meminfo", "r");
957 if ( fp )
958 {
959 long memFree = -1;
960
961 char buf[1024];
962 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
963 {
7c28d921
VZ
964 // /proc/meminfo changed its format in kernel 2.6
965 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
966 {
967 unsigned long cached, buffers;
968 sscanf(buf, "MemFree: %ld", &memFree);
969
970 fgets(buf, WXSIZEOF(buf), fp);
971 sscanf(buf, "Buffers: %lu", &buffers);
972
973 fgets(buf, WXSIZEOF(buf), fp);
974 sscanf(buf, "Cached: %lu", &cached);
975
976 // add to "MemFree" also the "Buffers" and "Cached" values as
977 // free(1) does as otherwise the value never makes sense: for
978 // kernel 2.6 it's always almost 0
979 memFree += buffers + cached;
980
981 // values here are always expressed in kB and we want bytes
982 memFree *= 1024;
983 }
984 else // Linux 2.4 (or < 2.6, anyhow)
985 {
986 long memTotal, memUsed;
987 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
988 }
bd3277fe
VZ
989 }
990
991 fclose(fp);
992
9d8aca48 993 return (wxMemorySize)memFree;
bd3277fe 994 }
9ad34f61
VZ
995#elif defined(__SGI__)
996 struct rminfo realmem;
997 if ( sysmp(MP_SAGET, MPSA_RMINFO, &realmem, sizeof realmem) == 0 )
998 return ((wxMemorySize)realmem.physmem * sysconf(_SC_PAGESIZE));
40f00746
VZ
999#elif defined(_SC_AVPHYS_PAGES)
1000 return ((wxMemorySize)sysconf(_SC_AVPHYS_PAGES))*sysconf(_SC_PAGESIZE);
bd3277fe
VZ
1001//#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1002#endif
1003
1004 // can't find it out
1005 return -1;
1006}
1007
7ba7c4e6 1008bool wxGetDiskSpace(const wxString& path, wxDiskspaceSize_t *pTotal, wxDiskspaceSize_t *pFree)
eadd7bd2 1009{
9952adac 1010#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
fbfb3fb3 1011 // the case to "char *" is needed for AIX 4.3
85da04e9
VZ
1012 wxStatfs_t fs;
1013 if ( wxStatfs((char *)(const char*)path.fn_str(), &fs) != 0 )
eadd7bd2 1014 {
401eb3de 1015 wxLogSysError( wxT("Failed to get file system statistics") );
eadd7bd2 1016
9d8aca48 1017 return false;
eadd7bd2
VZ
1018 }
1019
125cb99b
VZ
1020 // under Solaris we also have to use f_frsize field instead of f_bsize
1021 // which is in general a multiple of f_frsize
1022#ifdef HAVE_STATVFS
7ba7c4e6 1023 wxDiskspaceSize_t blockSize = fs.f_frsize;
125cb99b 1024#else // HAVE_STATFS
7ba7c4e6 1025 wxDiskspaceSize_t blockSize = fs.f_bsize;
125cb99b 1026#endif // HAVE_STATVFS/HAVE_STATFS
9952adac 1027
eadd7bd2
VZ
1028 if ( pTotal )
1029 {
7ba7c4e6 1030 *pTotal = wxDiskspaceSize_t(fs.f_blocks) * blockSize;
eadd7bd2
VZ
1031 }
1032
1033 if ( pFree )
1034 {
7ba7c4e6 1035 *pFree = wxDiskspaceSize_t(fs.f_bavail) * blockSize;
eadd7bd2
VZ
1036 }
1037
9d8aca48 1038 return true;
125cb99b 1039#else // !HAVE_STATFS && !HAVE_STATVFS
9d8aca48 1040 return false;
125cb99b 1041#endif // HAVE_STATFS
eadd7bd2
VZ
1042}
1043
8fd0d89b
VZ
1044// ----------------------------------------------------------------------------
1045// env vars
1046// ----------------------------------------------------------------------------
1047
97b305b7 1048bool wxGetEnv(const wxString& var, wxString *value)
308978f6
VZ
1049{
1050 // wxGetenv is defined as getenv()
86501081 1051 char *p = wxGetenv(var);
308978f6 1052 if ( !p )
9d8aca48 1053 return false;
308978f6
VZ
1054
1055 if ( value )
1056 {
1057 *value = p;
1058 }
1059
9d8aca48 1060 return true;
308978f6
VZ
1061}
1062
90a77e64 1063static bool wxDoSetEnv(const wxString& variable, const char *value)
8fd0d89b
VZ
1064{
1065#if defined(HAVE_SETENV)
90a77e64 1066 return setenv(variable.mb_str(), value, 1 /* overwrite */) == 0;
8fd0d89b
VZ
1067#elif defined(HAVE_PUTENV)
1068 wxString s = variable;
1069 if ( value )
1070 s << _T('=') << value;
1071
1072 // transform to ANSI
67479dbd 1073 const wxWX2MBbuf p = s.mb_str();
8fd0d89b
VZ
1074
1075 // the string will be free()d by libc
1076 char *buf = (char *)malloc(strlen(p) + 1);
1077 strcpy(buf, p);
1078
1079 return putenv(buf) == 0;
1080#else // no way to set an env var
67479dbd 1081 return false;
8fd0d89b
VZ
1082#endif
1083}
1084
90a77e64
VS
1085bool wxSetEnv(const wxString& variable, const wxString& value)
1086{
1087 return wxDoSetEnv(variable, value.mb_str());
1088}
1089
1090bool wxUnsetEnv(const wxString& variable)
1091{
1092 return wxDoSetEnv(variable, NULL);
1093}
1094
a37a5a73
VZ
1095// ----------------------------------------------------------------------------
1096// signal handling
1097// ----------------------------------------------------------------------------
1098
1099#if wxUSE_ON_FATAL_EXCEPTION
1100
1101#include <signal.h>
1102
90350682 1103extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
a37a5a73
VZ
1104{
1105 if ( wxTheApp )
1106 {
1107 // give the user a chance to do something special about this
1108 wxTheApp->OnFatalException();
1109 }
1110
1111 abort();
1112}
1113
1114bool wxHandleFatalExceptions(bool doit)
1115{
1116 // old sig handlers
9d8aca48 1117 static bool s_savedHandlers = false;
a37a5a73
VZ
1118 static struct sigaction s_handlerFPE,
1119 s_handlerILL,
1120 s_handlerBUS,
1121 s_handlerSEGV;
1122
9d8aca48 1123 bool ok = true;
a37a5a73
VZ
1124 if ( doit && !s_savedHandlers )
1125 {
1126 // install the signal handler
1127 struct sigaction act;
1128
1129 // some systems extend it with non std fields, so zero everything
1130 memset(&act, 0, sizeof(act));
1131
1132 act.sa_handler = wxFatalSignalHandler;
1133 sigemptyset(&act.sa_mask);
1134 act.sa_flags = 0;
1135
1136 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1137 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1138 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1139 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1140 if ( !ok )
1141 {
1142 wxLogDebug(_T("Failed to install our signal handler."));
1143 }
1144
9d8aca48 1145 s_savedHandlers = true;
a37a5a73
VZ
1146 }
1147 else if ( s_savedHandlers )
1148 {
1149 // uninstall the signal handler
1150 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1151 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1152 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1153 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1154 if ( !ok )
1155 {
1156 wxLogDebug(_T("Failed to uninstall our signal handler."));
1157 }
1158
9d8aca48 1159 s_savedHandlers = false;
a37a5a73
VZ
1160 }
1161 //else: nothing to do
1162
1163 return ok;
1164}
1165
1166#endif // wxUSE_ON_FATAL_EXCEPTION
1167
ec67cff1 1168#endif // wxUSE_BASE
e2478fde
VZ
1169
1170#if wxUSE_GUI
1171
1172// ----------------------------------------------------------------------------
1173// wxExecute support
1174// ----------------------------------------------------------------------------
1175
1176// Darwin doesn't use the same process end detection mechanisms so we don't
1177// need wxExecute-related helpers for it
1178#if !(defined(__DARWIN__) && defined(__WXMAC__))
1179
1180bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData& execData)
1181{
1182 return execData.pipeEndProcDetect.Create();
1183}
1184
1185bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData& execData, int fd)
1186{
46446cc2 1187 return fd == (execData.pipeEndProcDetect)[wxPipe::Write];
e2478fde
VZ
1188}
1189
1190void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData& execData)
1191{
1192 execData.pipeEndProcDetect.Detach(wxPipe::Write);
1193 execData.pipeEndProcDetect.Close();
1194}
1195
1196#else // !Darwin
1197
1198bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData& WXUNUSED(execData))
1199{
1200 return true;
1201}
1202
1203bool
1204wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData& WXUNUSED(execData),
1205 int WXUNUSED(fd))
1206{
1207 return false;
1208}
1209
1210void
1211wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData& WXUNUSED(execData))
1212{
1213 // nothing to do here, we don't use the pipe
1214}
1215
1216#endif // !Darwin/Darwin
1217
1218int wxGUIAppTraits::WaitForChild(wxExecuteData& execData)
1219{
1220 wxEndProcessData *endProcData = new wxEndProcessData;
1221
f38f6899
VZ
1222 const int flags = execData.flags;
1223
e2478fde
VZ
1224 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1225 // callback function directly if the process terminates before
1226 // the callback can be added to the run loop. Set up the endProcData.
f38f6899 1227 if ( flags & wxEXEC_SYNC )
e2478fde
VZ
1228 {
1229 // we may have process for capturing the program output, but it's
1230 // not used in wxEndProcessData in the case of sync execution
1231 endProcData->process = NULL;
1232
1233 // sync execution: indicate it by negating the pid
1234 endProcData->pid = -execData.pid;
1235 }
1236 else
1237 {
1238 // async execution, nothing special to do -- caller will be
1239 // notified about the process termination if process != NULL, endProcData
1240 // will be deleted in GTK_EndProcessDetector
1241 endProcData->process = execData.process;
1242 endProcData->pid = execData.pid;
1243 }
1244
1245
bc855d09
VZ
1246 if ( !(flags & wxEXEC_NOEVENTS) )
1247 {
f7ef0602 1248#if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
bc855d09 1249 endProcData->tag = wxAddProcessCallbackForPid(endProcData, execData.pid);
e2478fde 1250#else
bc855d09
VZ
1251 endProcData->tag = wxAddProcessCallback
1252 (
1253 endProcData,
1254 execData.pipeEndProcDetect.Detach(wxPipe::Read)
1255 );
e2478fde 1256
bc855d09 1257 execData.pipeEndProcDetect.Close();
f7ef0602 1258#endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
bc855d09 1259 }
e2478fde 1260
f38f6899 1261 if ( flags & wxEXEC_SYNC )
e2478fde
VZ
1262 {
1263 wxBusyCursor bc;
bc855d09
VZ
1264 int exitcode = 0;
1265
1266 wxWindowDisabler *wd = flags & (wxEXEC_NODISABLE | wxEXEC_NOEVENTS)
1267 ? NULL
1268 : new wxWindowDisabler;
e2478fde 1269
bc855d09 1270 if ( flags & wxEXEC_NOEVENTS )
e2478fde 1271 {
bc855d09
VZ
1272 // just block waiting for the child to exit
1273 int status = 0;
05df0f1b 1274
bc855d09
VZ
1275 int result = waitpid(execData.pid, &status, 0);
1276
1277 if ( result == -1 )
05df0f1b 1278 {
bc855d09
VZ
1279 wxLogLastError(_T("waitpid"));
1280 exitcode = -1;
05df0f1b 1281 }
bc855d09 1282 else
05df0f1b 1283 {
bc855d09
VZ
1284 wxASSERT_MSG( result == execData.pid,
1285 _T("unexpected waitpid() return value") );
1286
1287 if ( WIFEXITED(status) )
1288 {
1289 exitcode = WEXITSTATUS(status);
1290 }
1291 else // abnormal termination?
1292 {
1293 wxASSERT_MSG( WIFSIGNALED(status),
1294 _T("unexpected child wait status") );
1295 exitcode = -1;
1296 }
05df0f1b 1297 }
bc855d09
VZ
1298 }
1299 else // !wxEXEC_NOEVENTS
1300 {
1301 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1302 // process terminates
1303 while ( endProcData->pid != 0 )
1304 {
1305 bool idle = true;
1306
1307#if HAS_PIPE_INPUT_STREAM
1308 if ( execData.bufOut )
1309 {
1310 execData.bufOut->Update();
1311 idle = false;
1312 }
1313
1314 if ( execData.bufErr )
1315 {
1316 execData.bufErr->Update();
1317 idle = false;
1318 }
1f3b2af0 1319#endif // HAS_PIPE_INPUT_STREAM
e2478fde 1320
bc855d09
VZ
1321 // don't consume 100% of the CPU while we're sitting in this
1322 // loop
1323 if ( idle )
1324 wxMilliSleep(1);
05df0f1b 1325
bc855d09
VZ
1326 // give GTK+ a chance to call GTK_EndProcessDetector here and
1327 // also repaint the GUI
1328 wxYield();
1329 }
e2478fde 1330
bc855d09
VZ
1331 exitcode = endProcData->exitcode;
1332 }
e2478fde 1333
f38f6899 1334 delete wd;
e2478fde
VZ
1335 delete endProcData;
1336
1337 return exitcode;
1338 }
1339 else // async execution
1340 {
1341 return execData.pid;
1342 }
1343}
1344
2dbc444a
RD
1345#endif // wxUSE_GUI
1346#if wxUSE_BASE
1347
e2478fde
VZ
1348void wxHandleProcessTermination(wxEndProcessData *proc_data)
1349{
1350 // notify user about termination if required
1351 if ( proc_data->process )
1352 {
1353 proc_data->process->OnTerminate(proc_data->pid, proc_data->exitcode);
1354 }
1355
1356 // clean up
1357 if ( proc_data->pid > 0 )
1358 {
1359 delete proc_data;
1360 }
1361 else
1362 {
1363 // let wxExecute() know that the process has terminated
1364 proc_data->pid = 0;
1365 }
1366}
1367
2dbc444a 1368#endif // wxUSE_BASE