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