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