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