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