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