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