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