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