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