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