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