]> git.saurik.com Git - wxWidgets.git/blame - src/unix/utilsunx.cpp
reformat for readability
[wxWidgets.git] / src / unix / utilsunx.cpp
CommitLineData
518b5d2f 1/////////////////////////////////////////////////////////////////////////////
79066131 2// Name: unix/utilsunx.cpp
518b5d2f
VZ
3// Purpose: generic Unix implementation of many wx functions
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
518b5d2f
VZ
21#include "wx/defs.h"
22#include "wx/string.h"
23
24#include "wx/intl.h"
25#include "wx/log.h"
a37a5a73 26#include "wx/app.h"
46446cc2 27#include "wx/apptrait.h"
518b5d2f
VZ
28
29#include "wx/utils.h"
30#include "wx/process.h"
bdc72a22 31#include "wx/thread.h"
518b5d2f 32
80d6dc0a 33#include "wx/wfstream.h"
8b33ae2d 34
e2478fde 35#include "wx/unix/execute.h"
17a1ebd1
VZ
36#include "wx/unix/private.h"
37
38#include <pwd.h>
e2478fde 39
2887179b
VZ
40#if wxUSE_STREAMS
41
42// define this to let wxexec.cpp know that we know what we're doing
43#define _WX_USED_BY_WXEXECUTE_
44#include "../common/execcmn.cpp"
45
46#endif // wxUSE_STREAMS
47
ec67cff1 48#if wxUSE_BASE
e2478fde 49
74c719ed
VZ
50#if defined(__MWERKS__) && defined(__MACH__)
51 #ifndef WXWIN_OS_DESCRIPTION
52 #define WXWIN_OS_DESCRIPTION "MacOS X"
53 #endif
54 #ifndef HAVE_NANOSLEEP
55 #define HAVE_NANOSLEEP
56 #endif
57 #ifndef HAVE_UNAME
58 #define HAVE_UNAME
59 #endif
60
61 // our configure test believes we can use sigaction() if the function is
62 // available but Metrowekrs with MSL run-time does have the function but
63 // doesn't have sigaction struct so finally we can't use it...
64 #ifdef __MSL__
65 #undef wxUSE_ON_FATAL_EXCEPTION
66 #define wxUSE_ON_FATAL_EXCEPTION 0
67 #endif
8d4f85ce
SC
68#endif
69
85da04e9
VZ
70// not only the statfs syscall is called differently depending on platform, but
71// one of its incarnations, statvfs(), takes different arguments under
72// different platforms and even different versions of the same system (Solaris
73// 7 and 8): if you want to test for this, don't forget that the problems only
74// appear if the large files support is enabled
eadd7bd2 75#ifdef HAVE_STATFS
85da04e9
VZ
76 #ifdef __BSD__
77 #include <sys/param.h>
78 #include <sys/mount.h>
79 #else // !__BSD__
80 #include <sys/vfs.h>
81 #endif // __BSD__/!__BSD__
82
83 #define wxStatfs statfs
84ae7ca4
VZ
84
85 #ifndef HAVE_STATFS_DECL
86 // some systems lack statfs() prototype in the system headers (AIX 4)
87 extern "C" int statfs(const char *path, struct statfs *buf);
88 #endif
eadd7bd2
VZ
89#endif // HAVE_STATFS
90
9952adac
VZ
91#ifdef HAVE_STATVFS
92 #include <sys/statvfs.h>
93
85da04e9
VZ
94 #define wxStatfs statvfs
95#endif // HAVE_STATVFS
96
97#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
98 // WX_STATFS_T is detected by configure
99 #define wxStatfs_t WX_STATFS_T
100#endif
9952adac 101
f6bcfd97
BP
102// SGI signal.h defines signal handler arguments differently depending on
103// whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
104#if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
105 #define _LANGUAGE_C_PLUS_PLUS 1
106#endif // SGI hack
107
518b5d2f
VZ
108#include <stdarg.h>
109#include <dirent.h>
110#include <string.h>
111#include <sys/stat.h>
112#include <sys/types.h>
518b5d2f 113#include <sys/wait.h>
e2478fde 114#include <unistd.h>
518b5d2f
VZ
115#include <errno.h>
116#include <netdb.h>
117#include <signal.h>
118#include <fcntl.h> // for O_WRONLY and friends
119#include <time.h> // nanosleep() and/or usleep()
fad866f4 120#include <ctype.h> // isspace()
b12915c1 121#include <sys/time.h> // needed for FD_SETSIZE
7bcb11d3 122
0fcdf6dc 123#ifdef HAVE_UNAME
518b5d2f
VZ
124 #include <sys/utsname.h> // for uname()
125#endif // HAVE_UNAME
126
9ad34f61
VZ
127// Used by wxGetFreeMemory().
128#ifdef __SGI__
129 #include <sys/sysmp.h>
130 #include <sys/sysinfo.h> // for SAGET and MINFO structures
131#endif
132
518b5d2f
VZ
133// ----------------------------------------------------------------------------
134// conditional compilation
135// ----------------------------------------------------------------------------
136
137// many versions of Unices have this function, but it is not defined in system
138// headers - please add your system here if it is the case for your OS.
139// SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
1363811b 140#if !defined(HAVE_USLEEP) && \
d67fee71 141 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
518b5d2f 142 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
d67fee71 143 defined(__osf__) || defined(__EMX__))
518b5d2f
VZ
144 extern "C"
145 {
1363811b
VZ
146 #ifdef __SUN__
147 int usleep(unsigned int usec);
148 #else // !Sun
bdc72a22
VZ
149 #ifdef __EMX__
150 /* I copied this from the XFree86 diffs. AV. */
151 #define INCL_DOSPROCESS
152 #include <os2.h>
153 inline void usleep(unsigned long delay)
154 {
155 DosSleep(delay ? (delay/1000l) : 1l);
156 }
157 #else // !Sun && !EMX
158 void usleep(unsigned long usec);
159 #endif
e6daf794 160 #endif // Sun/EMX/Something else
518b5d2f 161 };
bdc72a22
VZ
162
163 #define HAVE_USLEEP 1
518b5d2f
VZ
164#endif // Unices without usleep()
165
518b5d2f
VZ
166// ============================================================================
167// implementation
168// ============================================================================
169
170// ----------------------------------------------------------------------------
171// sleeping
172// ----------------------------------------------------------------------------
173
174void wxSleep(int nSecs)
175{
176 sleep(nSecs);
177}
178
66cd9d7f 179void wxMicroSleep(unsigned long microseconds)
518b5d2f 180{
b12915c1 181#if defined(HAVE_NANOSLEEP)
518b5d2f 182 timespec tmReq;
66cd9d7f
VZ
183 tmReq.tv_sec = (time_t)(microseconds / 1000000);
184 tmReq.tv_nsec = (microseconds % 1000000) * 1000;
518b5d2f
VZ
185
186 // we're not interested in remaining time nor in return value
187 (void)nanosleep(&tmReq, (timespec *)NULL);
b12915c1 188#elif defined(HAVE_USLEEP)
518b5d2f
VZ
189 // uncomment this if you feel brave or if you are sure that your version
190 // of Solaris has a safe usleep() function but please notice that usleep()
191 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
192 // documented as MT-Safe
ea18eed9 193 #if defined(__SUN__) && wxUSE_THREADS
518b5d2f
VZ
194 #error "usleep() cannot be used in MT programs under Solaris."
195 #endif // Sun
196
66cd9d7f 197 usleep(microseconds);
b12915c1
VZ
198#elif defined(HAVE_SLEEP)
199 // under BeOS sleep() takes seconds (what about other platforms, if any?)
66cd9d7f 200 sleep(microseconds * 1000000);
518b5d2f 201#else // !sleep function
66cd9d7f 202 #error "usleep() or nanosleep() function required for wxMicroSleep"
518b5d2f
VZ
203#endif // sleep function
204}
205
66cd9d7f
VZ
206void wxMilliSleep(unsigned long milliseconds)
207{
208 wxMicroSleep(milliseconds*1000);
209}
210
518b5d2f
VZ
211// ----------------------------------------------------------------------------
212// process management
213// ----------------------------------------------------------------------------
214
e0f6b731 215int wxKill(long pid, wxSignal sig, wxKillError *rc, int flags)
518b5d2f 216{
e0f6b731 217 int err = kill((pid_t) (flags & wxKILL_CHILDREN) ? -pid : pid, (int)sig);
50567b69
VZ
218 if ( rc )
219 {
f0bce4d4 220 switch ( err ? errno : 0 )
50567b69
VZ
221 {
222 case 0:
223 *rc = wxKILL_OK;
224 break;
225
226 case EINVAL:
227 *rc = wxKILL_BAD_SIGNAL;
228 break;
229
230 case EPERM:
231 *rc = wxKILL_ACCESS_DENIED;
232 break;
233
234 case ESRCH:
235 *rc = wxKILL_NO_PROCESS;
236 break;
237
238 default:
239 // this goes against Unix98 docs so log it
240 wxLogDebug(_T("unexpected kill(2) return value %d"), err);
241
242 // something else...
243 *rc = wxKILL_ERROR;
244 }
245 }
246
247 return err;
518b5d2f
VZ
248}
249
fad866f4
KB
250#define WXEXECUTE_NARGS 127
251
62705a27
RN
252#if defined(__DARWIN__)
253long wxMacExecute(wxChar **argv,
254 int flags,
255 wxProcess *process);
256#endif
257
fbf456aa 258long wxExecute( const wxString& command, int flags, wxProcess *process )
518b5d2f 259{
8ea92b4d 260 wxCHECK_MSG( !command.empty(), 0, wxT("can't exec empty command") );
3bdb628b 261 wxLogDebug(wxString(wxT("Launching: ")) + command);
518b5d2f 262
647b8e37
VZ
263#if wxUSE_THREADS
264 // fork() doesn't mix well with POSIX threads: on many systems the program
265 // deadlocks or crashes for some reason. Probably our code is buggy and
266 // doesn't do something which must be done to allow this to work, but I
267 // don't know what yet, so for now just warn the user (this is the least we
268 // can do) about it
269 wxASSERT_MSG( wxThread::IsMain(),
270 _T("wxExecute() can be called only from the main thread") );
271#endif // wxUSE_THREADS
272
518b5d2f 273 int argc = 0;
05079acc 274 wxChar *argv[WXEXECUTE_NARGS];
fad866f4 275 wxString argument;
05079acc 276 const wxChar *cptr = command.c_str();
223d09f6 277 wxChar quotechar = wxT('\0'); // is arg quoted?
9d8aca48 278 bool escaped = false;
518b5d2f 279
0ed9a934 280 // split the command line in arguments
fad866f4
KB
281 do
282 {
223d09f6
KB
283 argument=wxT("");
284 quotechar = wxT('\0');
0ed9a934 285
fad866f4 286 // eat leading whitespace:
05079acc 287 while ( wxIsspace(*cptr) )
fad866f4 288 cptr++;
0ed9a934 289
223d09f6 290 if ( *cptr == wxT('\'') || *cptr == wxT('"') )
fad866f4 291 quotechar = *cptr++;
0ed9a934 292
fad866f4
KB
293 do
294 {
223d09f6 295 if ( *cptr == wxT('\\') && ! escaped )
fad866f4 296 {
9d8aca48 297 escaped = true;
fad866f4
KB
298 cptr++;
299 continue;
300 }
0ed9a934 301
fad866f4 302 // all other characters:
0ed9a934 303 argument += *cptr++;
9d8aca48 304 escaped = false;
0ed9a934
VZ
305
306 // have we reached the end of the argument?
307 if ( (*cptr == quotechar && ! escaped)
223d09f6
KB
308 || (quotechar == wxT('\0') && wxIsspace(*cptr))
309 || *cptr == wxT('\0') )
fad866f4 310 {
0ed9a934 311 wxASSERT_MSG( argc < WXEXECUTE_NARGS,
223d09f6 312 wxT("too many arguments in wxExecute") );
0ed9a934 313
05079acc
OK
314 argv[argc] = new wxChar[argument.length() + 1];
315 wxStrcpy(argv[argc], argument.c_str());
fad866f4 316 argc++;
0ed9a934 317
fad866f4 318 // if not at end of buffer, swallow last character:
0ed9a934
VZ
319 if(*cptr)
320 cptr++;
321
fad866f4
KB
322 break; // done with this one, start over
323 }
0ed9a934
VZ
324 } while(*cptr);
325 } while(*cptr);
fad866f4 326 argv[argc] = NULL;
0ed9a934 327
62705a27
RN
328 long lRc;
329#if defined(__DARWIN__)
3afdfec4 330 // wxMacExecute only executes app bundles.
fb19fbab
SC
331 // It returns an error code if the target is not an app bundle, thus falling
332 // through to the regular wxExecute for non app bundles.
3afdfec4 333 lRc = wxMacExecute(argv, flags, process);
fb19fbab 334 if( lRc != ((flags & wxEXEC_SYNC) ? -1 : 0))
62705a27
RN
335 return lRc;
336#endif
337
0ed9a934 338 // do execute the command
62705a27 339 lRc = wxExecute(argv, flags, process);
518b5d2f 340
0ed9a934 341 // clean up
fad866f4 342 argc = 0;
0ed9a934 343 while( argv[argc] )
fad866f4 344 delete [] argv[argc++];
518b5d2f
VZ
345
346 return lRc;
347}
348
2c8e4738
VZ
349// ----------------------------------------------------------------------------
350// wxShell
351// ----------------------------------------------------------------------------
352
353static wxString wxMakeShellCommand(const wxString& command)
518b5d2f
VZ
354{
355 wxString cmd;
cd6ce4a9 356 if ( !command )
2c8e4738
VZ
357 {
358 // just an interactive shell
cd6ce4a9 359 cmd = _T("xterm");
2c8e4738 360 }
518b5d2f 361 else
2c8e4738
VZ
362 {
363 // execute command in a shell
364 cmd << _T("/bin/sh -c '") << command << _T('\'');
365 }
366
367 return cmd;
368}
369
370bool wxShell(const wxString& command)
371{
fbf456aa 372 return wxExecute(wxMakeShellCommand(command), wxEXEC_SYNC) == 0;
2c8e4738
VZ
373}
374
375bool wxShell(const wxString& command, wxArrayString& output)
376{
9d8aca48 377 wxCHECK_MSG( !command.empty(), false, _T("can't exec shell non interactively") );
518b5d2f 378
2c8e4738 379 return wxExecute(wxMakeShellCommand(command), output);
518b5d2f
VZ
380}
381
f6ba47d9
VZ
382// Shutdown or reboot the PC
383bool wxShutdown(wxShutdownFlags wFlags)
384{
385 wxChar level;
386 switch ( wFlags )
387 {
388 case wxSHUTDOWN_POWEROFF:
389 level = _T('0');
390 break;
391
392 case wxSHUTDOWN_REBOOT:
393 level = _T('6');
394 break;
395
396 default:
397 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
9d8aca48 398 return false;
f6ba47d9
VZ
399 }
400
401 return system(wxString::Format(_T("init %c"), level).mb_str()) == 0;
402}
403
8ea92b4d
WS
404wxPowerType wxGetPowerType()
405{
406 // TODO
407 return wxPOWER_UNKNOWN;
408}
409
410wxBatteryState wxGetBatteryState()
411{
412 // TODO
413 return wxBATTERY_UNKNOWN_STATE;
414}
f6ba47d9 415
cd6ce4a9
VZ
416// ----------------------------------------------------------------------------
417// wxStream classes to support IO redirection in wxExecute
418// ----------------------------------------------------------------------------
6dc6fda6 419
1e6feb95
VZ
420#if wxUSE_STREAMS
421
2b5f62a0 422bool wxPipeInputStream::CanRead() const
8b33ae2d 423{
cd6ce4a9 424 if ( m_lasterror == wxSTREAM_EOF )
9d8aca48 425 return false;
cd6ce4a9
VZ
426
427 // check if there is any input available
428 struct timeval tv;
429 tv.tv_sec = 0;
430 tv.tv_usec = 0;
431
80d6dc0a
VZ
432 const int fd = m_file->fd();
433
cd6ce4a9 434 fd_set readfds;
17a1ebd1
VZ
435
436 wxFD_ZERO(&readfds);
437 wxFD_SET(fd, &readfds);
438
80d6dc0a 439 switch ( select(fd + 1, &readfds, NULL, NULL, &tv) )
cd6ce4a9
VZ
440 {
441 case -1:
442 wxLogSysError(_("Impossible to get child process input"));
443 // fall through
8b33ae2d 444
cd6ce4a9 445 case 0:
9d8aca48 446 return false;
8b33ae2d 447
cd6ce4a9
VZ
448 default:
449 wxFAIL_MSG(_T("unexpected select() return value"));
450 // still fall through
451
452 case 1:
6f3d3c68
VZ
453 // input available -- or maybe not, as select() returns 1 when a
454 // read() will complete without delay, but it could still not read
455 // anything
456 return !Eof();
cd6ce4a9 457 }
8b33ae2d
GL
458}
459
1e6feb95
VZ
460#endif // wxUSE_STREAMS
461
b477f956
VZ
462// ----------------------------------------------------------------------------
463// wxExecute: the real worker function
464// ----------------------------------------------------------------------------
79066131 465
17a1ebd1 466long wxExecute(wxChar **argv, int flags, wxProcess *process)
518b5d2f 467{
f6bcfd97 468 // for the sync execution, we return -1 to indicate failure, but for async
accb3257
VZ
469 // case we return 0 which is never a valid PID
470 //
471 // we define this as a macro, not a variable, to avoid compiler warnings
472 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
fbf456aa 473 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
f6bcfd97 474
accb3257 475 wxCHECK_MSG( *argv, ERROR_RETURN_CODE, wxT("can't exec empty command") );
518b5d2f 476
05079acc
OK
477#if wxUSE_UNICODE
478 int mb_argc = 0;
479 char *mb_argv[WXEXECUTE_NARGS];
480
e90c1d2a
VZ
481 while (argv[mb_argc])
482 {
cd6ce4a9
VZ
483 wxWX2MBbuf mb_arg = wxConvertWX2MB(argv[mb_argc]);
484 mb_argv[mb_argc] = strdup(mb_arg);
485 mb_argc++;
05079acc
OK
486 }
487 mb_argv[mb_argc] = (char *) NULL;
e90c1d2a
VZ
488
489 // this macro will free memory we used above
490 #define ARGS_CLEANUP \
345b0247 491 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
e90c1d2a
VZ
492 free(mb_argv[mb_argc])
493#else // ANSI
494 // no need for cleanup
495 #define ARGS_CLEANUP
496
05079acc 497 wxChar **mb_argv = argv;
e90c1d2a 498#endif // Unicode/ANSI
518b5d2f 499
e2478fde
VZ
500 // we want this function to work even if there is no wxApp so ensure that
501 // we have a valid traits pointer
502 wxConsoleAppTraits traitsConsole;
503 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
504 if ( !traits )
505 traits = &traitsConsole;
506
507 // this struct contains all information which we pass to and from
508 // wxAppTraits methods
509 wxExecuteData execData;
510 execData.flags = flags;
511 execData.process = process;
512
518b5d2f 513 // create pipes
e2478fde 514 if ( !traits->CreateEndProcessPipe(execData) )
518b5d2f 515 {
cd6ce4a9 516 wxLogError( _("Failed to execute '%s'\n"), *argv );
e90c1d2a
VZ
517
518 ARGS_CLEANUP;
519
accb3257 520 return ERROR_RETURN_CODE;
518b5d2f
VZ
521 }
522
f6bcfd97 523 // pipes for inter process communication
b477f956
VZ
524 wxPipe pipeIn, // stdin
525 pipeOut, // stdout
526 pipeErr; // stderr
cd6ce4a9
VZ
527
528 if ( process && process->IsRedirected() )
8b33ae2d 529 {
b477f956 530 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
8b33ae2d 531 {
cd6ce4a9 532 wxLogError( _("Failed to execute '%s'\n"), *argv );
8b33ae2d
GL
533
534 ARGS_CLEANUP;
535
accb3257 536 return ERROR_RETURN_CODE;
8b33ae2d
GL
537 }
538 }
8b33ae2d 539
518b5d2f 540 // fork the process
ef5f8ab6
VZ
541 //
542 // NB: do *not* use vfork() here, it completely breaks this code for some
543 // reason under Solaris (and maybe others, although not under Linux)
b2ddee86
JJ
544 // But on OpenVMS we do not have fork so we have to use vfork and
545 // cross our fingers that it works.
546#ifdef __VMS
547 pid_t pid = vfork();
548#else
549 pid_t pid = fork();
550#endif
551 if ( pid == -1 ) // error?
518b5d2f
VZ
552 {
553 wxLogSysError( _("Fork failed") );
e90c1d2a
VZ
554
555 ARGS_CLEANUP;
556
accb3257 557 return ERROR_RETURN_CODE;
518b5d2f 558 }
cd6ce4a9 559 else if ( pid == 0 ) // we're in child
518b5d2f 560 {
cd6ce4a9 561 // These lines close the open file descriptors to to avoid any
518b5d2f 562 // input/output which might block the process or irritate the user. If
cd6ce4a9
VZ
563 // one wants proper IO for the subprocess, the right thing to do is to
564 // start an xterm executing it.
fbf456aa 565 if ( !(flags & wxEXEC_SYNC) )
518b5d2f 566 {
35ef537b
VZ
567 // FD_SETSIZE is unsigned under BSD, signed under other platforms
568 // so we need a cast to avoid warnings on all platforms
569 for ( int fd = 0; fd < (int)FD_SETSIZE; fd++ )
518b5d2f 570 {
b477f956
VZ
571 if ( fd == pipeIn[wxPipe::Read]
572 || fd == pipeOut[wxPipe::Write]
573 || fd == pipeErr[wxPipe::Write]
e2478fde 574 || traits->IsWriteFDOfEndProcessPipe(execData, fd) )
cd6ce4a9
VZ
575 {
576 // don't close this one, we still need it
577 continue;
578 }
e90c1d2a 579
b477f956 580 // leave stderr opened too, it won't do any harm
e90c1d2a 581 if ( fd != STDERR_FILENO )
518b5d2f
VZ
582 close(fd);
583 }
0c9c4401 584 }
e1082c9f 585
e8e776aa 586#if !defined(__VMS) && !defined(__EMX__)
0c9c4401
VZ
587 if ( flags & wxEXEC_MAKE_GROUP_LEADER )
588 {
589 // Set process group to child process' pid. Then killing -pid
590 // of the parent will kill the process and all of its children.
591 setsid();
518b5d2f 592 }
0c9c4401
VZ
593#endif // !__VMS
594
0c9c4401
VZ
595 // reading side can be safely closed but we should keep the write one
596 // opened
e2478fde 597 traits->DetachWriteFDOfEndProcessPipe(execData);
518b5d2f 598
80d6dc0a 599 // redirect stdin, stdout and stderr
b477f956 600 if ( pipeIn.IsOk() )
cd6ce4a9 601 {
b477f956
VZ
602 if ( dup2(pipeIn[wxPipe::Read], STDIN_FILENO) == -1 ||
603 dup2(pipeOut[wxPipe::Write], STDOUT_FILENO) == -1 ||
604 dup2(pipeErr[wxPipe::Write], STDERR_FILENO) == -1 )
cd6ce4a9 605 {
f6bcfd97 606 wxLogSysError(_("Failed to redirect child process input/output"));
cd6ce4a9 607 }
518b5d2f 608
b477f956
VZ
609 pipeIn.Close();
610 pipeOut.Close();
611 pipeErr.Close();
cd6ce4a9 612 }
518b5d2f 613
05079acc 614 execvp (*mb_argv, mb_argv);
17a1ebd1 615
d264d709 616 fprintf(stderr, "execvp(");
8d4f85ce
SC
617 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
618 for ( char **ppc_ = mb_argv; *ppc_; ppc_++ )
619 fprintf(stderr, "%s%s", ppc_ == mb_argv ? "" : ", ", *ppc_);
d264d709
VZ
620 fprintf(stderr, ") failed with error %d!\n", errno);
621
518b5d2f 622 // there is no return after successful exec()
518b5d2f 623 _exit(-1);
1d8dd65e
VZ
624
625 // some compilers complain about missing return - of course, they
626 // should know that exit() doesn't return but what else can we do if
627 // they don't?
b477f956
VZ
628 //
629 // and, sure enough, other compilers complain about unreachable code
630 // after exit() call, so we can just always have return here...
1d8dd65e
VZ
631#if defined(__VMS) || defined(__INTEL_COMPILER)
632 return 0;
633#endif
518b5d2f 634 }
cd6ce4a9 635 else // we're in parent
518b5d2f 636 {
cd6ce4a9
VZ
637 ARGS_CLEANUP;
638
7764f973
VZ
639 // save it for WaitForChild() use
640 execData.pid = pid;
641
80d6dc0a
VZ
642 // prepare for IO redirection
643
0e300ddd 644#if wxUSE_STREAMS
80d6dc0a
VZ
645 // the input buffer bufOut is connected to stdout, this is why it is
646 // called bufOut and not bufIn
647 wxStreamTempInputBuffer bufOut,
648 bufErr;
0e300ddd
VZ
649#endif // wxUSE_STREAMS
650
cd6ce4a9
VZ
651 if ( process && process->IsRedirected() )
652 {
1e6feb95 653#if wxUSE_STREAMS
80d6dc0a
VZ
654 wxOutputStream *inStream =
655 new wxFileOutputStream(pipeIn.Detach(wxPipe::Write));
b477f956 656
79066131
VZ
657 wxPipeInputStream *outStream =
658 new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
b477f956 659
79066131
VZ
660 wxPipeInputStream *errStream =
661 new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
f6bcfd97 662
80d6dc0a 663 process->SetPipeStreams(outStream, inStream, errStream);
0e300ddd 664
80d6dc0a 665 bufOut.Init(outStream);
b477f956 666 bufErr.Init(errStream);
e2478fde
VZ
667
668 execData.bufOut = &bufOut;
669 execData.bufErr = &bufErr;
1e6feb95 670#endif // wxUSE_STREAMS
b477f956 671 }
1e6feb95 672
b477f956
VZ
673 if ( pipeIn.IsOk() )
674 {
675 pipeIn.Close();
676 pipeOut.Close();
677 pipeErr.Close();
cd6ce4a9
VZ
678 }
679
e2478fde 680 return traits->WaitForChild(execData);
518b5d2f 681 }
79656e30 682
17a1ebd1 683#if !defined(__VMS) && !defined(__INTEL_COMPILER)
79656e30 684 return ERROR_RETURN_CODE;
ef0ed19e 685#endif
17a1ebd1 686}
518b5d2f 687
accb3257 688#undef ERROR_RETURN_CODE
f6bcfd97
BP
689#undef ARGS_CLEANUP
690
518b5d2f
VZ
691// ----------------------------------------------------------------------------
692// file and directory functions
693// ----------------------------------------------------------------------------
694
05079acc 695const wxChar* wxGetHomeDir( wxString *home )
518b5d2f 696{
8ea92b4d 697 *home = wxGetUserHome( wxEmptyString );
79066131 698 wxString tmp;
8ea92b4d 699 if ( home->empty() )
223d09f6 700 *home = wxT("/");
181cbcf4 701#ifdef __VMS
79066131
VZ
702 tmp = *home;
703 if ( tmp.Last() != wxT(']'))
704 if ( tmp.Last() != wxT('/')) *home << wxT('/');
181cbcf4 705#endif
518b5d2f
VZ
706 return home->c_str();
707}
708
05079acc
OK
709#if wxUSE_UNICODE
710const wxMB2WXbuf wxGetUserHome( const wxString &user )
e90c1d2a 711#else // just for binary compatibility -- there is no 'const' here
518b5d2f 712char *wxGetUserHome( const wxString &user )
05079acc 713#endif
518b5d2f
VZ
714{
715 struct passwd *who = (struct passwd *) NULL;
716
0fb67cd1 717 if ( !user )
518b5d2f 718 {
e90c1d2a 719 wxChar *ptr;
518b5d2f 720
223d09f6 721 if ((ptr = wxGetenv(wxT("HOME"))) != NULL)
518b5d2f 722 {
2b5f62a0
VZ
723#if wxUSE_UNICODE
724 wxWCharBuffer buffer( ptr );
725 return buffer;
726#else
518b5d2f 727 return ptr;
2b5f62a0 728#endif
518b5d2f 729 }
223d09f6 730 if ((ptr = wxGetenv(wxT("USER"))) != NULL || (ptr = wxGetenv(wxT("LOGNAME"))) != NULL)
518b5d2f 731 {
e90c1d2a 732 who = getpwnam(wxConvertWX2MB(ptr));
518b5d2f
VZ
733 }
734
735 // We now make sure the the user exists!
736 if (who == NULL)
737 {
738 who = getpwuid(getuid());
739 }
740 }
741 else
742 {
05079acc 743 who = getpwnam (user.mb_str());
518b5d2f
VZ
744 }
745
af111fc3 746 return wxConvertMB2WX(who ? who->pw_dir : 0);
518b5d2f
VZ
747}
748
749// ----------------------------------------------------------------------------
0fb67cd1 750// network and user id routines
518b5d2f
VZ
751// ----------------------------------------------------------------------------
752
0fb67cd1
VZ
753// retrieve either the hostname or FQDN depending on platform (caller must
754// check whether it's one or the other, this is why this function is for
755// private use only)
05079acc 756static bool wxGetHostNameInternal(wxChar *buf, int sz)
518b5d2f 757{
9d8aca48 758 wxCHECK_MSG( buf, false, wxT("NULL pointer in wxGetHostNameInternal") );
518b5d2f 759
223d09f6 760 *buf = wxT('\0');
518b5d2f
VZ
761
762 // we're using uname() which is POSIX instead of less standard sysinfo()
763#if defined(HAVE_UNAME)
cc743a6f 764 struct utsname uts;
518b5d2f
VZ
765 bool ok = uname(&uts) != -1;
766 if ( ok )
767 {
e90c1d2a 768 wxStrncpy(buf, wxConvertMB2WX(uts.nodename), sz - 1);
223d09f6 769 buf[sz] = wxT('\0');
518b5d2f
VZ
770 }
771#elif defined(HAVE_GETHOSTNAME)
772 bool ok = gethostname(buf, sz) != -1;
0fb67cd1 773#else // no uname, no gethostname
223d09f6 774 wxFAIL_MSG(wxT("don't know host name for this machine"));
518b5d2f 775
9d8aca48 776 bool ok = false;
0fb67cd1 777#endif // uname/gethostname
518b5d2f
VZ
778
779 if ( !ok )
780 {
781 wxLogSysError(_("Cannot get the hostname"));
782 }
783
784 return ok;
785}
786
05079acc 787bool wxGetHostName(wxChar *buf, int sz)
0fb67cd1
VZ
788{
789 bool ok = wxGetHostNameInternal(buf, sz);
790
791 if ( ok )
792 {
793 // BSD systems return the FQDN, we only want the hostname, so extract
794 // it (we consider that dots are domain separators)
223d09f6 795 wxChar *dot = wxStrchr(buf, wxT('.'));
0fb67cd1
VZ
796 if ( dot )
797 {
798 // nuke it
223d09f6 799 *dot = wxT('\0');
0fb67cd1
VZ
800 }
801 }
802
803 return ok;
804}
805
05079acc 806bool wxGetFullHostName(wxChar *buf, int sz)
0fb67cd1
VZ
807{
808 bool ok = wxGetHostNameInternal(buf, sz);
809
810 if ( ok )
811 {
223d09f6 812 if ( !wxStrchr(buf, wxT('.')) )
0fb67cd1 813 {
e90c1d2a 814 struct hostent *host = gethostbyname(wxConvertWX2MB(buf));
0fb67cd1
VZ
815 if ( !host )
816 {
817 wxLogSysError(_("Cannot get the official hostname"));
818
9d8aca48 819 ok = false;
0fb67cd1
VZ
820 }
821 else
822 {
823 // the canonical name
e90c1d2a 824 wxStrncpy(buf, wxConvertMB2WX(host->h_name), sz);
0fb67cd1
VZ
825 }
826 }
827 //else: it's already a FQDN (BSD behaves this way)
828 }
829
830 return ok;
831}
832
05079acc 833bool wxGetUserId(wxChar *buf, int sz)
518b5d2f
VZ
834{
835 struct passwd *who;
836
223d09f6 837 *buf = wxT('\0');
518b5d2f
VZ
838 if ((who = getpwuid(getuid ())) != NULL)
839 {
e90c1d2a 840 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
9d8aca48 841 return true;
518b5d2f
VZ
842 }
843
9d8aca48 844 return false;
518b5d2f
VZ
845}
846
05079acc 847bool wxGetUserName(wxChar *buf, int sz)
518b5d2f
VZ
848{
849 struct passwd *who;
518b5d2f 850
223d09f6 851 *buf = wxT('\0');
b12915c1
VZ
852 if ((who = getpwuid (getuid ())) != NULL)
853 {
854 // pw_gecos field in struct passwd is not standard
bd3277fe 855#ifdef HAVE_PW_GECOS
b12915c1 856 char *comma = strchr(who->pw_gecos, ',');
518b5d2f
VZ
857 if (comma)
858 *comma = '\0'; // cut off non-name comment fields
e90c1d2a 859 wxStrncpy (buf, wxConvertMB2WX(who->pw_gecos), sz - 1);
b12915c1 860#else // !HAVE_PW_GECOS
0fcdf6dc 861 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
b12915c1 862#endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
9d8aca48 863 return true;
518b5d2f
VZ
864 }
865
9d8aca48 866 return false;
518b5d2f
VZ
867}
868
e2478fde 869// this function is in mac/utils.cpp for wxMac
6e73695c 870#ifndef __WXMAC__
e2478fde 871
bdc72a22
VZ
872wxString wxGetOsDescription()
873{
db1d0193
VZ
874 FILE *f = popen("uname -s -r -m", "r");
875 if (f)
876 {
877 char buf[256];
878 size_t c = fread(buf, 1, sizeof(buf) - 1, f);
879 pclose(f);
880 // Trim newline from output.
881 if (c && buf[c - 1] == '\n')
882 --c;
883 buf[c] = '\0';
884 return wxString::FromAscii( buf );
885 }
886 wxFAIL_MSG( _T("uname failed") );
887 return _T("");
bdc72a22
VZ
888}
889
e2478fde 890#endif // !__WXMAC__
bd3277fe 891
c1cb4153
VZ
892unsigned long wxGetProcessId()
893{
894 return (unsigned long)getpid();
895}
896
9d8aca48 897wxMemorySize wxGetFreeMemory()
bd3277fe
VZ
898{
899#if defined(__LINUX__)
900 // get it from /proc/meminfo
901 FILE *fp = fopen("/proc/meminfo", "r");
902 if ( fp )
903 {
904 long memFree = -1;
905
906 char buf[1024];
907 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
908 {
909 long memTotal, memUsed;
910 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
911 }
912
913 fclose(fp);
914
9d8aca48 915 return (wxMemorySize)memFree;
bd3277fe
VZ
916 }
917#elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
9d8aca48 918 return (wxMemorySize)(sysconf(_SC_AVPHYS_PAGES)*sysconf(_SC_PAGESIZE));
9ad34f61
VZ
919#elif defined(__SGI__)
920 struct rminfo realmem;
921 if ( sysmp(MP_SAGET, MPSA_RMINFO, &realmem, sizeof realmem) == 0 )
922 return ((wxMemorySize)realmem.physmem * sysconf(_SC_PAGESIZE));
bd3277fe
VZ
923//#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
924#endif
925
926 // can't find it out
927 return -1;
928}
929
eadd7bd2
VZ
930bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
931{
9952adac 932#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
fbfb3fb3 933 // the case to "char *" is needed for AIX 4.3
85da04e9
VZ
934 wxStatfs_t fs;
935 if ( wxStatfs((char *)(const char*)path.fn_str(), &fs) != 0 )
eadd7bd2 936 {
401eb3de 937 wxLogSysError( wxT("Failed to get file system statistics") );
eadd7bd2 938
9d8aca48 939 return false;
eadd7bd2
VZ
940 }
941
125cb99b
VZ
942 // under Solaris we also have to use f_frsize field instead of f_bsize
943 // which is in general a multiple of f_frsize
944#ifdef HAVE_STATVFS
945 wxLongLong blockSize = fs.f_frsize;
946#else // HAVE_STATFS
947 wxLongLong blockSize = fs.f_bsize;
948#endif // HAVE_STATVFS/HAVE_STATFS
9952adac 949
eadd7bd2
VZ
950 if ( pTotal )
951 {
125cb99b 952 *pTotal = wxLongLong(fs.f_blocks) * blockSize;
eadd7bd2
VZ
953 }
954
955 if ( pFree )
956 {
125cb99b 957 *pFree = wxLongLong(fs.f_bavail) * blockSize;
eadd7bd2
VZ
958 }
959
9d8aca48 960 return true;
125cb99b 961#else // !HAVE_STATFS && !HAVE_STATVFS
9d8aca48 962 return false;
125cb99b 963#endif // HAVE_STATFS
eadd7bd2
VZ
964}
965
8fd0d89b
VZ
966// ----------------------------------------------------------------------------
967// env vars
968// ----------------------------------------------------------------------------
969
97b305b7 970bool wxGetEnv(const wxString& var, wxString *value)
308978f6
VZ
971{
972 // wxGetenv is defined as getenv()
973 wxChar *p = wxGetenv(var);
974 if ( !p )
9d8aca48 975 return false;
308978f6
VZ
976
977 if ( value )
978 {
979 *value = p;
980 }
981
9d8aca48 982 return true;
308978f6
VZ
983}
984
8fd0d89b
VZ
985bool wxSetEnv(const wxString& variable, const wxChar *value)
986{
987#if defined(HAVE_SETENV)
d90b2df8
VZ
988 return setenv(variable.mb_str(),
989 value ? (const char *)wxString(value).mb_str()
990 : NULL,
991 1 /* overwrite */) == 0;
8fd0d89b
VZ
992#elif defined(HAVE_PUTENV)
993 wxString s = variable;
994 if ( value )
995 s << _T('=') << value;
996
997 // transform to ANSI
67479dbd 998 const wxWX2MBbuf p = s.mb_str();
8fd0d89b
VZ
999
1000 // the string will be free()d by libc
1001 char *buf = (char *)malloc(strlen(p) + 1);
1002 strcpy(buf, p);
1003
1004 return putenv(buf) == 0;
1005#else // no way to set an env var
67479dbd 1006 return false;
8fd0d89b
VZ
1007#endif
1008}
1009
a37a5a73
VZ
1010// ----------------------------------------------------------------------------
1011// signal handling
1012// ----------------------------------------------------------------------------
1013
1014#if wxUSE_ON_FATAL_EXCEPTION
1015
1016#include <signal.h>
1017
90350682 1018extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
a37a5a73
VZ
1019{
1020 if ( wxTheApp )
1021 {
1022 // give the user a chance to do something special about this
1023 wxTheApp->OnFatalException();
1024 }
1025
1026 abort();
1027}
1028
1029bool wxHandleFatalExceptions(bool doit)
1030{
1031 // old sig handlers
9d8aca48 1032 static bool s_savedHandlers = false;
a37a5a73
VZ
1033 static struct sigaction s_handlerFPE,
1034 s_handlerILL,
1035 s_handlerBUS,
1036 s_handlerSEGV;
1037
9d8aca48 1038 bool ok = true;
a37a5a73
VZ
1039 if ( doit && !s_savedHandlers )
1040 {
1041 // install the signal handler
1042 struct sigaction act;
1043
1044 // some systems extend it with non std fields, so zero everything
1045 memset(&act, 0, sizeof(act));
1046
1047 act.sa_handler = wxFatalSignalHandler;
1048 sigemptyset(&act.sa_mask);
1049 act.sa_flags = 0;
1050
1051 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1052 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1053 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1054 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1055 if ( !ok )
1056 {
1057 wxLogDebug(_T("Failed to install our signal handler."));
1058 }
1059
9d8aca48 1060 s_savedHandlers = true;
a37a5a73
VZ
1061 }
1062 else if ( s_savedHandlers )
1063 {
1064 // uninstall the signal handler
1065 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1066 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1067 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1068 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1069 if ( !ok )
1070 {
1071 wxLogDebug(_T("Failed to uninstall our signal handler."));
1072 }
1073
9d8aca48 1074 s_savedHandlers = false;
a37a5a73
VZ
1075 }
1076 //else: nothing to do
1077
1078 return ok;
1079}
1080
1081#endif // wxUSE_ON_FATAL_EXCEPTION
1082
ec67cff1 1083#endif // wxUSE_BASE
e2478fde
VZ
1084
1085#if wxUSE_GUI
1086
1087// ----------------------------------------------------------------------------
1088// wxExecute support
1089// ----------------------------------------------------------------------------
1090
1091// Darwin doesn't use the same process end detection mechanisms so we don't
1092// need wxExecute-related helpers for it
1093#if !(defined(__DARWIN__) && defined(__WXMAC__))
1094
1095bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData& execData)
1096{
1097 return execData.pipeEndProcDetect.Create();
1098}
1099
1100bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData& execData, int fd)
1101{
46446cc2 1102 return fd == (execData.pipeEndProcDetect)[wxPipe::Write];
e2478fde
VZ
1103}
1104
1105void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData& execData)
1106{
1107 execData.pipeEndProcDetect.Detach(wxPipe::Write);
1108 execData.pipeEndProcDetect.Close();
1109}
1110
1111#else // !Darwin
1112
1113bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData& WXUNUSED(execData))
1114{
1115 return true;
1116}
1117
1118bool
1119wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData& WXUNUSED(execData),
1120 int WXUNUSED(fd))
1121{
1122 return false;
1123}
1124
1125void
1126wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData& WXUNUSED(execData))
1127{
1128 // nothing to do here, we don't use the pipe
1129}
1130
1131#endif // !Darwin/Darwin
1132
1133int wxGUIAppTraits::WaitForChild(wxExecuteData& execData)
1134{
1135 wxEndProcessData *endProcData = new wxEndProcessData;
1136
f38f6899
VZ
1137 const int flags = execData.flags;
1138
e2478fde
VZ
1139 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1140 // callback function directly if the process terminates before
1141 // the callback can be added to the run loop. Set up the endProcData.
f38f6899 1142 if ( flags & wxEXEC_SYNC )
e2478fde
VZ
1143 {
1144 // we may have process for capturing the program output, but it's
1145 // not used in wxEndProcessData in the case of sync execution
1146 endProcData->process = NULL;
1147
1148 // sync execution: indicate it by negating the pid
1149 endProcData->pid = -execData.pid;
1150 }
1151 else
1152 {
1153 // async execution, nothing special to do -- caller will be
1154 // notified about the process termination if process != NULL, endProcData
1155 // will be deleted in GTK_EndProcessDetector
1156 endProcData->process = execData.process;
1157 endProcData->pid = execData.pid;
1158 }
1159
1160
f7ef0602 1161#if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
e2478fde
VZ
1162 endProcData->tag = wxAddProcessCallbackForPid(endProcData, execData.pid);
1163#else
1164 endProcData->tag = wxAddProcessCallback
1165 (
1166 endProcData,
1167 execData.pipeEndProcDetect.Detach(wxPipe::Read)
1168 );
1169
1170 execData.pipeEndProcDetect.Close();
f7ef0602 1171#endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
e2478fde 1172
f38f6899 1173 if ( flags & wxEXEC_SYNC )
e2478fde
VZ
1174 {
1175 wxBusyCursor bc;
f38f6899
VZ
1176 wxWindowDisabler *wd = flags & wxEXEC_NODISABLE ? NULL
1177 : new wxWindowDisabler;
e2478fde
VZ
1178
1179 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1180 // process terminates
1181 while ( endProcData->pid != 0 )
1182 {
05df0f1b
VZ
1183 bool idle = true;
1184
e2478fde
VZ
1185#if wxUSE_STREAMS
1186 if ( execData.bufOut )
05df0f1b 1187 {
e2478fde 1188 execData.bufOut->Update();
05df0f1b
VZ
1189 idle = false;
1190 }
e2478fde
VZ
1191
1192 if ( execData.bufErr )
05df0f1b 1193 {
e2478fde 1194 execData.bufErr->Update();
05df0f1b
VZ
1195 idle = false;
1196 }
e2478fde
VZ
1197#endif // wxUSE_STREAMS
1198
1012c2ce 1199 // don't consume 100% of the CPU while we're sitting in this
05df0f1b
VZ
1200 // loop
1201 if ( idle )
39ef7151 1202 wxMilliSleep(1);
05df0f1b 1203
e2478fde
VZ
1204 // give GTK+ a chance to call GTK_EndProcessDetector here and
1205 // also repaint the GUI
1206 wxYield();
1207 }
1208
1209 int exitcode = endProcData->exitcode;
1210
f38f6899 1211 delete wd;
e2478fde
VZ
1212 delete endProcData;
1213
1214 return exitcode;
1215 }
1216 else // async execution
1217 {
1218 return execData.pid;
1219 }
1220}
1221
2dbc444a
RD
1222#endif // wxUSE_GUI
1223#if wxUSE_BASE
1224
e2478fde
VZ
1225void wxHandleProcessTermination(wxEndProcessData *proc_data)
1226{
1227 // notify user about termination if required
1228 if ( proc_data->process )
1229 {
1230 proc_data->process->OnTerminate(proc_data->pid, proc_data->exitcode);
1231 }
1232
1233 // clean up
1234 if ( proc_data->pid > 0 )
1235 {
1236 delete proc_data;
1237 }
1238 else
1239 {
1240 // let wxExecute() know that the process has terminated
1241 proc_data->pid = 0;
1242 }
1243}
1244
2dbc444a 1245#endif // wxUSE_BASE