]> git.saurik.com Git - wxWidgets.git/blame - src/unix/utilsunx.cpp
Made wxPageSetupDialog a pimpl implementation.
[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{
db1d0193
VZ
840 FILE *f = popen("uname -s -r -m", "r");
841 if (f)
842 {
843 char buf[256];
844 size_t c = fread(buf, 1, sizeof(buf) - 1, f);
845 pclose(f);
846 // Trim newline from output.
847 if (c && buf[c - 1] == '\n')
848 --c;
849 buf[c] = '\0';
850 return wxString::FromAscii( buf );
851 }
852 wxFAIL_MSG( _T("uname failed") );
853 return _T("");
bdc72a22
VZ
854}
855
e2478fde 856#endif // !__WXMAC__
bd3277fe 857
c1cb4153
VZ
858unsigned long wxGetProcessId()
859{
860 return (unsigned long)getpid();
861}
862
bd3277fe
VZ
863long wxGetFreeMemory()
864{
865#if defined(__LINUX__)
866 // get it from /proc/meminfo
867 FILE *fp = fopen("/proc/meminfo", "r");
868 if ( fp )
869 {
870 long memFree = -1;
871
872 char buf[1024];
873 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
874 {
875 long memTotal, memUsed;
876 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
877 }
878
879 fclose(fp);
880
881 return memFree;
882 }
883#elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
884 return sysconf(_SC_AVPHYS_PAGES)*sysconf(_SC_PAGESIZE);
885//#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
886#endif
887
888 // can't find it out
889 return -1;
890}
891
eadd7bd2
VZ
892bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
893{
9952adac 894#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
fbfb3fb3 895 // the case to "char *" is needed for AIX 4.3
85da04e9
VZ
896 wxStatfs_t fs;
897 if ( wxStatfs((char *)(const char*)path.fn_str(), &fs) != 0 )
eadd7bd2 898 {
401eb3de 899 wxLogSysError( wxT("Failed to get file system statistics") );
eadd7bd2
VZ
900
901 return FALSE;
902 }
903
125cb99b
VZ
904 // under Solaris we also have to use f_frsize field instead of f_bsize
905 // which is in general a multiple of f_frsize
906#ifdef HAVE_STATVFS
907 wxLongLong blockSize = fs.f_frsize;
908#else // HAVE_STATFS
909 wxLongLong blockSize = fs.f_bsize;
910#endif // HAVE_STATVFS/HAVE_STATFS
9952adac 911
eadd7bd2
VZ
912 if ( pTotal )
913 {
125cb99b 914 *pTotal = wxLongLong(fs.f_blocks) * blockSize;
eadd7bd2
VZ
915 }
916
917 if ( pFree )
918 {
125cb99b 919 *pFree = wxLongLong(fs.f_bavail) * blockSize;
eadd7bd2
VZ
920 }
921
922 return TRUE;
125cb99b 923#else // !HAVE_STATFS && !HAVE_STATVFS
eadd7bd2 924 return FALSE;
125cb99b 925#endif // HAVE_STATFS
eadd7bd2
VZ
926}
927
8fd0d89b
VZ
928// ----------------------------------------------------------------------------
929// env vars
930// ----------------------------------------------------------------------------
931
97b305b7 932bool wxGetEnv(const wxString& var, wxString *value)
308978f6
VZ
933{
934 // wxGetenv is defined as getenv()
935 wxChar *p = wxGetenv(var);
936 if ( !p )
937 return FALSE;
938
939 if ( value )
940 {
941 *value = p;
942 }
943
944 return TRUE;
945}
946
8fd0d89b
VZ
947bool wxSetEnv(const wxString& variable, const wxChar *value)
948{
949#if defined(HAVE_SETENV)
d90b2df8
VZ
950 return setenv(variable.mb_str(),
951 value ? (const char *)wxString(value).mb_str()
952 : NULL,
953 1 /* overwrite */) == 0;
8fd0d89b
VZ
954#elif defined(HAVE_PUTENV)
955 wxString s = variable;
956 if ( value )
957 s << _T('=') << value;
958
959 // transform to ANSI
67479dbd 960 const wxWX2MBbuf p = s.mb_str();
8fd0d89b
VZ
961
962 // the string will be free()d by libc
963 char *buf = (char *)malloc(strlen(p) + 1);
964 strcpy(buf, p);
965
966 return putenv(buf) == 0;
967#else // no way to set an env var
67479dbd 968 return false;
8fd0d89b
VZ
969#endif
970}
971
a37a5a73
VZ
972// ----------------------------------------------------------------------------
973// signal handling
974// ----------------------------------------------------------------------------
975
976#if wxUSE_ON_FATAL_EXCEPTION
977
978#include <signal.h>
979
90350682 980extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
a37a5a73
VZ
981{
982 if ( wxTheApp )
983 {
984 // give the user a chance to do something special about this
985 wxTheApp->OnFatalException();
986 }
987
988 abort();
989}
990
991bool wxHandleFatalExceptions(bool doit)
992{
993 // old sig handlers
994 static bool s_savedHandlers = FALSE;
995 static struct sigaction s_handlerFPE,
996 s_handlerILL,
997 s_handlerBUS,
998 s_handlerSEGV;
999
1000 bool ok = TRUE;
1001 if ( doit && !s_savedHandlers )
1002 {
1003 // install the signal handler
1004 struct sigaction act;
1005
1006 // some systems extend it with non std fields, so zero everything
1007 memset(&act, 0, sizeof(act));
1008
1009 act.sa_handler = wxFatalSignalHandler;
1010 sigemptyset(&act.sa_mask);
1011 act.sa_flags = 0;
1012
1013 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1014 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1015 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1016 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1017 if ( !ok )
1018 {
1019 wxLogDebug(_T("Failed to install our signal handler."));
1020 }
1021
1022 s_savedHandlers = TRUE;
1023 }
1024 else if ( s_savedHandlers )
1025 {
1026 // uninstall the signal handler
1027 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1028 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1029 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1030 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1031 if ( !ok )
1032 {
1033 wxLogDebug(_T("Failed to uninstall our signal handler."));
1034 }
1035
1036 s_savedHandlers = FALSE;
1037 }
1038 //else: nothing to do
1039
1040 return ok;
1041}
1042
1043#endif // wxUSE_ON_FATAL_EXCEPTION
1044
518b5d2f
VZ
1045// ----------------------------------------------------------------------------
1046// error and debug output routines (deprecated, use wxLog)
1047// ----------------------------------------------------------------------------
1048
73deed44
VZ
1049#if WXWIN_COMPATIBILITY_2_2
1050
518b5d2f
VZ
1051void wxDebugMsg( const char *format, ... )
1052{
1053 va_list ap;
1054 va_start( ap, format );
1055 vfprintf( stderr, format, ap );
1056 fflush( stderr );
1057 va_end(ap);
1058}
1059
1060void wxError( const wxString &msg, const wxString &title )
1061{
05079acc 1062 wxFprintf( stderr, _("Error ") );
223d09f6
KB
1063 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1064 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1065 wxFprintf( stderr, wxT(".\n") );
518b5d2f
VZ
1066}
1067
1068void wxFatalError( const wxString &msg, const wxString &title )
1069{
05079acc 1070 wxFprintf( stderr, _("Error ") );
223d09f6
KB
1071 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1072 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1073 wxFprintf( stderr, wxT(".\n") );
518b5d2f
VZ
1074 exit(3); // the same exit code as for abort()
1075}
93ccaed8 1076
73deed44
VZ
1077#endif // WXWIN_COMPATIBILITY_2_2
1078
ec67cff1 1079#endif // wxUSE_BASE
e2478fde
VZ
1080
1081#if wxUSE_GUI
1082
1083// ----------------------------------------------------------------------------
1084// wxExecute support
1085// ----------------------------------------------------------------------------
1086
1087// Darwin doesn't use the same process end detection mechanisms so we don't
1088// need wxExecute-related helpers for it
1089#if !(defined(__DARWIN__) && defined(__WXMAC__))
1090
1091bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData& execData)
1092{
1093 return execData.pipeEndProcDetect.Create();
1094}
1095
1096bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData& execData, int fd)
1097{
46446cc2 1098 return fd == (execData.pipeEndProcDetect)[wxPipe::Write];
e2478fde
VZ
1099}
1100
1101void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData& execData)
1102{
1103 execData.pipeEndProcDetect.Detach(wxPipe::Write);
1104 execData.pipeEndProcDetect.Close();
1105}
1106
1107#else // !Darwin
1108
1109bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData& WXUNUSED(execData))
1110{
1111 return true;
1112}
1113
1114bool
1115wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData& WXUNUSED(execData),
1116 int WXUNUSED(fd))
1117{
1118 return false;
1119}
1120
1121void
1122wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData& WXUNUSED(execData))
1123{
1124 // nothing to do here, we don't use the pipe
1125}
1126
1127#endif // !Darwin/Darwin
1128
1129int wxGUIAppTraits::WaitForChild(wxExecuteData& execData)
1130{
1131 wxEndProcessData *endProcData = new wxEndProcessData;
1132
1133 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1134 // callback function directly if the process terminates before
1135 // the callback can be added to the run loop. Set up the endProcData.
1136 if ( execData.flags & wxEXEC_SYNC )
1137 {
1138 // we may have process for capturing the program output, but it's
1139 // not used in wxEndProcessData in the case of sync execution
1140 endProcData->process = NULL;
1141
1142 // sync execution: indicate it by negating the pid
1143 endProcData->pid = -execData.pid;
1144 }
1145 else
1146 {
1147 // async execution, nothing special to do -- caller will be
1148 // notified about the process termination if process != NULL, endProcData
1149 // will be deleted in GTK_EndProcessDetector
1150 endProcData->process = execData.process;
1151 endProcData->pid = execData.pid;
1152 }
1153
1154
f7ef0602 1155#if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
e2478fde
VZ
1156 endProcData->tag = wxAddProcessCallbackForPid(endProcData, execData.pid);
1157#else
1158 endProcData->tag = wxAddProcessCallback
1159 (
1160 endProcData,
1161 execData.pipeEndProcDetect.Detach(wxPipe::Read)
1162 );
1163
1164 execData.pipeEndProcDetect.Close();
f7ef0602 1165#endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
e2478fde
VZ
1166
1167 if ( execData.flags & wxEXEC_SYNC )
1168 {
1169 wxBusyCursor bc;
1170 wxWindowDisabler wd;
1171
1172 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1173 // process terminates
1174 while ( endProcData->pid != 0 )
1175 {
05df0f1b
VZ
1176 bool idle = true;
1177
e2478fde
VZ
1178#if wxUSE_STREAMS
1179 if ( execData.bufOut )
05df0f1b 1180 {
e2478fde 1181 execData.bufOut->Update();
05df0f1b
VZ
1182 idle = false;
1183 }
e2478fde
VZ
1184
1185 if ( execData.bufErr )
05df0f1b 1186 {
e2478fde 1187 execData.bufErr->Update();
05df0f1b
VZ
1188 idle = false;
1189 }
e2478fde
VZ
1190#endif // wxUSE_STREAMS
1191
1012c2ce 1192 // don't consume 100% of the CPU while we're sitting in this
05df0f1b
VZ
1193 // loop
1194 if ( idle )
39ef7151 1195 wxMilliSleep(1);
05df0f1b 1196
e2478fde
VZ
1197 // give GTK+ a chance to call GTK_EndProcessDetector here and
1198 // also repaint the GUI
1199 wxYield();
1200 }
1201
1202 int exitcode = endProcData->exitcode;
1203
1204 delete endProcData;
1205
1206 return exitcode;
1207 }
1208 else // async execution
1209 {
1210 return execData.pid;
1211 }
1212}
1213
2dbc444a
RD
1214#endif // wxUSE_GUI
1215#if wxUSE_BASE
1216
e2478fde
VZ
1217void wxHandleProcessTermination(wxEndProcessData *proc_data)
1218{
1219 // notify user about termination if required
1220 if ( proc_data->process )
1221 {
1222 proc_data->process->OnTerminate(proc_data->pid, proc_data->exitcode);
1223 }
1224
1225 // clean up
1226 if ( proc_data->pid > 0 )
1227 {
1228 delete proc_data;
1229 }
1230 else
1231 {
1232 // let wxExecute() know that the process has terminated
1233 proc_data->pid = 0;
1234 }
1235}
1236
2dbc444a 1237#endif // wxUSE_BASE