]> git.saurik.com Git - wxWidgets.git/blame - src/unix/utilsunx.cpp
added error message in case older apple header files are used
[wxWidgets.git] / src / unix / utilsunx.cpp
CommitLineData
518b5d2f
VZ
1/////////////////////////////////////////////////////////////////////////////
2// Name: utilsunx.cpp
3// Purpose: generic Unix implementation of many wx functions
4// Author: Vadim Zeitlin
5// Id: $Id$
6// Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
7// Licence: wxWindows licence
8/////////////////////////////////////////////////////////////////////////////
9
10// ============================================================================
11// declarations
12// ============================================================================
13
14// ----------------------------------------------------------------------------
15// headers
16// ----------------------------------------------------------------------------
17
18#include "wx/defs.h"
19#include "wx/string.h"
20
21#include "wx/intl.h"
22#include "wx/log.h"
a37a5a73 23#include "wx/app.h"
518b5d2f
VZ
24
25#include "wx/utils.h"
26#include "wx/process.h"
bdc72a22 27#include "wx/thread.h"
518b5d2f 28
8b33ae2d
GL
29#include "wx/stream.h"
30
eadd7bd2
VZ
31#ifdef HAVE_STATFS
32 #include <sys/vfs.h>
33#endif // HAVE_STATFS
34
6dc6fda6
VZ
35#if wxUSE_GUI
36 #include "wx/unix/execute.h"
37#endif
518b5d2f 38
f6bcfd97
BP
39// SGI signal.h defines signal handler arguments differently depending on
40// whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
41#if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
42 #define _LANGUAGE_C_PLUS_PLUS 1
43#endif // SGI hack
44
518b5d2f
VZ
45#include <stdarg.h>
46#include <dirent.h>
47#include <string.h>
48#include <sys/stat.h>
49#include <sys/types.h>
50#include <unistd.h>
51#include <sys/wait.h>
52#include <pwd.h>
53#include <errno.h>
54#include <netdb.h>
55#include <signal.h>
56#include <fcntl.h> // for O_WRONLY and friends
57#include <time.h> // nanosleep() and/or usleep()
fad866f4 58#include <ctype.h> // isspace()
b12915c1 59#include <sys/time.h> // needed for FD_SETSIZE
7bcb11d3 60
0fcdf6dc 61#ifdef HAVE_UNAME
518b5d2f
VZ
62 #include <sys/utsname.h> // for uname()
63#endif // HAVE_UNAME
64
65// ----------------------------------------------------------------------------
66// conditional compilation
67// ----------------------------------------------------------------------------
68
69// many versions of Unices have this function, but it is not defined in system
70// headers - please add your system here if it is the case for your OS.
71// SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
1363811b
VZ
72#if !defined(HAVE_USLEEP) && \
73 (defined(__SUN__) && !defined(__SunOs_5_6) && \
518b5d2f 74 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
fd9811b1 75 defined(__osf__) || defined(__EMX__)
518b5d2f
VZ
76 extern "C"
77 {
1363811b
VZ
78 #ifdef __SUN__
79 int usleep(unsigned int usec);
80 #else // !Sun
bdc72a22
VZ
81 #ifdef __EMX__
82 /* I copied this from the XFree86 diffs. AV. */
83 #define INCL_DOSPROCESS
84 #include <os2.h>
85 inline void usleep(unsigned long delay)
86 {
87 DosSleep(delay ? (delay/1000l) : 1l);
88 }
89 #else // !Sun && !EMX
90 void usleep(unsigned long usec);
91 #endif
e6daf794 92 #endif // Sun/EMX/Something else
518b5d2f 93 };
bdc72a22
VZ
94
95 #define HAVE_USLEEP 1
518b5d2f
VZ
96#endif // Unices without usleep()
97
518b5d2f
VZ
98// ============================================================================
99// implementation
100// ============================================================================
101
102// ----------------------------------------------------------------------------
103// sleeping
104// ----------------------------------------------------------------------------
105
106void wxSleep(int nSecs)
107{
108 sleep(nSecs);
109}
110
111void wxUsleep(unsigned long milliseconds)
112{
b12915c1 113#if defined(HAVE_NANOSLEEP)
518b5d2f 114 timespec tmReq;
13111b2a 115 tmReq.tv_sec = (time_t)(milliseconds / 1000);
518b5d2f
VZ
116 tmReq.tv_nsec = (milliseconds % 1000) * 1000 * 1000;
117
118 // we're not interested in remaining time nor in return value
119 (void)nanosleep(&tmReq, (timespec *)NULL);
b12915c1 120#elif defined(HAVE_USLEEP)
518b5d2f
VZ
121 // uncomment this if you feel brave or if you are sure that your version
122 // of Solaris has a safe usleep() function but please notice that usleep()
123 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
124 // documented as MT-Safe
ea18eed9 125 #if defined(__SUN__) && wxUSE_THREADS
518b5d2f
VZ
126 #error "usleep() cannot be used in MT programs under Solaris."
127 #endif // Sun
128
129 usleep(milliseconds * 1000); // usleep(3) wants microseconds
b12915c1
VZ
130#elif defined(HAVE_SLEEP)
131 // under BeOS sleep() takes seconds (what about other platforms, if any?)
132 sleep(milliseconds * 1000);
518b5d2f
VZ
133#else // !sleep function
134 #error "usleep() or nanosleep() function required for wxUsleep"
135#endif // sleep function
136}
137
138// ----------------------------------------------------------------------------
139// process management
140// ----------------------------------------------------------------------------
141
50567b69 142int wxKill(long pid, wxSignal sig, wxKillError *rc)
518b5d2f 143{
50567b69
VZ
144 int err = kill((pid_t)pid, (int)sig);
145 if ( rc )
146 {
147 switch ( err )
148 {
149 case 0:
150 *rc = wxKILL_OK;
151 break;
152
153 case EINVAL:
154 *rc = wxKILL_BAD_SIGNAL;
155 break;
156
157 case EPERM:
158 *rc = wxKILL_ACCESS_DENIED;
159 break;
160
161 case ESRCH:
162 *rc = wxKILL_NO_PROCESS;
163 break;
164
165 default:
166 // this goes against Unix98 docs so log it
167 wxLogDebug(_T("unexpected kill(2) return value %d"), err);
168
169 // something else...
170 *rc = wxKILL_ERROR;
171 }
172 }
173
174 return err;
518b5d2f
VZ
175}
176
fad866f4
KB
177#define WXEXECUTE_NARGS 127
178
518b5d2f
VZ
179long wxExecute( const wxString& command, bool sync, wxProcess *process )
180{
223d09f6 181 wxCHECK_MSG( !command.IsEmpty(), 0, wxT("can't exec empty command") );
518b5d2f
VZ
182
183 int argc = 0;
05079acc 184 wxChar *argv[WXEXECUTE_NARGS];
fad866f4 185 wxString argument;
05079acc 186 const wxChar *cptr = command.c_str();
223d09f6 187 wxChar quotechar = wxT('\0'); // is arg quoted?
fad866f4 188 bool escaped = FALSE;
518b5d2f 189
0ed9a934 190 // split the command line in arguments
fad866f4
KB
191 do
192 {
223d09f6
KB
193 argument=wxT("");
194 quotechar = wxT('\0');
0ed9a934 195
fad866f4 196 // eat leading whitespace:
05079acc 197 while ( wxIsspace(*cptr) )
fad866f4 198 cptr++;
0ed9a934 199
223d09f6 200 if ( *cptr == wxT('\'') || *cptr == wxT('"') )
fad866f4 201 quotechar = *cptr++;
0ed9a934 202
fad866f4
KB
203 do
204 {
223d09f6 205 if ( *cptr == wxT('\\') && ! escaped )
fad866f4
KB
206 {
207 escaped = TRUE;
208 cptr++;
209 continue;
210 }
0ed9a934 211
fad866f4 212 // all other characters:
0ed9a934 213 argument += *cptr++;
fad866f4 214 escaped = FALSE;
0ed9a934
VZ
215
216 // have we reached the end of the argument?
217 if ( (*cptr == quotechar && ! escaped)
223d09f6
KB
218 || (quotechar == wxT('\0') && wxIsspace(*cptr))
219 || *cptr == wxT('\0') )
fad866f4 220 {
0ed9a934 221 wxASSERT_MSG( argc < WXEXECUTE_NARGS,
223d09f6 222 wxT("too many arguments in wxExecute") );
0ed9a934 223
05079acc
OK
224 argv[argc] = new wxChar[argument.length() + 1];
225 wxStrcpy(argv[argc], argument.c_str());
fad866f4 226 argc++;
0ed9a934 227
fad866f4 228 // if not at end of buffer, swallow last character:
0ed9a934
VZ
229 if(*cptr)
230 cptr++;
231
fad866f4
KB
232 break; // done with this one, start over
233 }
0ed9a934
VZ
234 } while(*cptr);
235 } while(*cptr);
fad866f4 236 argv[argc] = NULL;
0ed9a934
VZ
237
238 // do execute the command
518b5d2f
VZ
239 long lRc = wxExecute(argv, sync, process);
240
0ed9a934 241 // clean up
fad866f4 242 argc = 0;
0ed9a934 243 while( argv[argc] )
fad866f4 244 delete [] argv[argc++];
518b5d2f
VZ
245
246 return lRc;
247}
248
2c8e4738
VZ
249// ----------------------------------------------------------------------------
250// wxShell
251// ----------------------------------------------------------------------------
252
253static wxString wxMakeShellCommand(const wxString& command)
518b5d2f
VZ
254{
255 wxString cmd;
cd6ce4a9 256 if ( !command )
2c8e4738
VZ
257 {
258 // just an interactive shell
cd6ce4a9 259 cmd = _T("xterm");
2c8e4738 260 }
518b5d2f 261 else
2c8e4738
VZ
262 {
263 // execute command in a shell
264 cmd << _T("/bin/sh -c '") << command << _T('\'');
265 }
266
267 return cmd;
268}
269
270bool wxShell(const wxString& command)
271{
272 return wxExecute(wxMakeShellCommand(command), TRUE /* sync */) == 0;
273}
274
275bool wxShell(const wxString& command, wxArrayString& output)
276{
277 wxCHECK_MSG( !!command, FALSE, _T("can't exec shell non interactively") );
518b5d2f 278
2c8e4738 279 return wxExecute(wxMakeShellCommand(command), output);
518b5d2f
VZ
280}
281
6dc6fda6
VZ
282#if wxUSE_GUI
283
518b5d2f
VZ
284void wxHandleProcessTermination(wxEndProcessData *proc_data)
285{
286 int pid = (proc_data->pid > 0) ? proc_data->pid : -(proc_data->pid);
287
0ed9a934
VZ
288 // waitpid is POSIX so should be available everywhere, however on older
289 // systems wait() might be used instead in a loop (until the right pid
290 // terminates)
518b5d2f 291 int status = 0;
ab857a4e
KB
292 int rc;
293
bdc72a22 294 // wait for child termination and if waitpid() was interrupted, try again
ab857a4e 295 do
bdc72a22 296 {
ab857a4e 297 rc = waitpid(pid, &status, 0);
bdc72a22
VZ
298 }
299 while ( rc == -1 && errno == EINTR );
300
ab857a4e 301
ab857a4e 302 if( rc == -1 || ! (WIFEXITED(status) || WIFSIGNALED(status)) )
0ed9a934 303 {
ab857a4e
KB
304 wxLogSysError(_("Waiting for subprocess termination failed"));
305 /* AFAIK, this can only happen if something went wrong within
bdc72a22 306 wxGTK, i.e. due to a race condition or some serious bug.
ab857a4e
KB
307 After having fixed the order of statements in
308 GTK_EndProcessDetector(). (KB)
309 */
0ed9a934
VZ
310 }
311 else
312 {
313 // notify user about termination if required
314 if (proc_data->process)
315 {
316 proc_data->process->OnTerminate(proc_data->pid,
317 WEXITSTATUS(status));
318 }
ab857a4e
KB
319 // clean up
320 if ( proc_data->pid > 0 )
321 {
322 delete proc_data;
323 }
324 else
325 {
326 // wxExecute() will know about it
327 proc_data->exitcode = status;
bdc72a22 328
ab857a4e
KB
329 proc_data->pid = 0;
330 }
518b5d2f
VZ
331 }
332}
333
6dc6fda6
VZ
334#endif // wxUSE_GUI
335
cd6ce4a9
VZ
336// ----------------------------------------------------------------------------
337// wxStream classes to support IO redirection in wxExecute
338// ----------------------------------------------------------------------------
6dc6fda6 339
1e6feb95
VZ
340#if wxUSE_STREAMS
341
cd6ce4a9
VZ
342class wxProcessFileInputStream : public wxInputStream
343{
344public:
345 wxProcessFileInputStream(int fd) { m_fd = fd; }
346 ~wxProcessFileInputStream() { close(m_fd); }
8b33ae2d 347
cd6ce4a9 348 virtual bool Eof() const;
8b33ae2d 349
cd6ce4a9 350protected:
8b33ae2d
GL
351 size_t OnSysRead(void *buffer, size_t bufsize);
352
cd6ce4a9 353protected:
8b33ae2d
GL
354 int m_fd;
355};
356
cd6ce4a9
VZ
357class wxProcessFileOutputStream : public wxOutputStream
358{
359public:
360 wxProcessFileOutputStream(int fd) { m_fd = fd; }
361 ~wxProcessFileOutputStream() { close(m_fd); }
8b33ae2d 362
cd6ce4a9 363protected:
8b33ae2d
GL
364 size_t OnSysWrite(const void *buffer, size_t bufsize);
365
cd6ce4a9 366protected:
8b33ae2d
GL
367 int m_fd;
368};
369
cd6ce4a9 370bool wxProcessFileInputStream::Eof() const
8b33ae2d 371{
cd6ce4a9
VZ
372 if ( m_lasterror == wxSTREAM_EOF )
373 return TRUE;
374
375 // check if there is any input available
376 struct timeval tv;
377 tv.tv_sec = 0;
378 tv.tv_usec = 0;
379
380 fd_set readfds;
381 FD_ZERO(&readfds);
382 FD_SET(m_fd, &readfds);
383 switch ( select(m_fd + 1, &readfds, NULL, NULL, &tv) )
384 {
385 case -1:
386 wxLogSysError(_("Impossible to get child process input"));
387 // fall through
8b33ae2d 388
cd6ce4a9
VZ
389 case 0:
390 return TRUE;
8b33ae2d 391
cd6ce4a9
VZ
392 default:
393 wxFAIL_MSG(_T("unexpected select() return value"));
394 // still fall through
395
396 case 1:
397 // input available: check if there is any
398 return wxInputStream::Eof();
8b33ae2d 399 }
8b33ae2d
GL
400}
401
cd6ce4a9 402size_t wxProcessFileInputStream::OnSysRead(void *buffer, size_t bufsize)
8b33ae2d 403{
cd6ce4a9
VZ
404 int ret = read(m_fd, buffer, bufsize);
405 if ( ret == 0 )
406 {
407 m_lasterror = wxSTREAM_EOF;
408 }
409 else if ( ret == -1 )
410 {
411 m_lasterror = wxSTREAM_READ_ERROR;
412 ret = 0;
413 }
414 else
415 {
416 m_lasterror = wxSTREAM_NOERROR;
417 }
8b33ae2d 418
cd6ce4a9 419 return ret;
8b33ae2d
GL
420}
421
422size_t wxProcessFileOutputStream::OnSysWrite(const void *buffer, size_t bufsize)
423{
cd6ce4a9
VZ
424 int ret = write(m_fd, buffer, bufsize);
425 if ( ret == -1 )
426 {
427 m_lasterror = wxSTREAM_WRITE_ERROR;
428 ret = 0;
8b33ae2d 429 }
cd6ce4a9
VZ
430 else
431 {
432 m_lasterror = wxSTREAM_NOERROR;
433 }
434
8b33ae2d
GL
435 return ret;
436}
437
1e6feb95
VZ
438#endif // wxUSE_STREAMS
439
6dc6fda6
VZ
440long wxExecute(wxChar **argv,
441 bool sync,
cd6ce4a9 442 wxProcess *process)
518b5d2f 443{
f6bcfd97 444 // for the sync execution, we return -1 to indicate failure, but for async
accb3257
VZ
445 // case we return 0 which is never a valid PID
446 //
447 // we define this as a macro, not a variable, to avoid compiler warnings
448 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
449 #define ERROR_RETURN_CODE ((sync) ? -1 : 0)
f6bcfd97 450
accb3257 451 wxCHECK_MSG( *argv, ERROR_RETURN_CODE, wxT("can't exec empty command") );
518b5d2f 452
05079acc
OK
453#if wxUSE_UNICODE
454 int mb_argc = 0;
455 char *mb_argv[WXEXECUTE_NARGS];
456
e90c1d2a
VZ
457 while (argv[mb_argc])
458 {
cd6ce4a9
VZ
459 wxWX2MBbuf mb_arg = wxConvertWX2MB(argv[mb_argc]);
460 mb_argv[mb_argc] = strdup(mb_arg);
461 mb_argc++;
05079acc
OK
462 }
463 mb_argv[mb_argc] = (char *) NULL;
e90c1d2a
VZ
464
465 // this macro will free memory we used above
466 #define ARGS_CLEANUP \
345b0247 467 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
e90c1d2a
VZ
468 free(mb_argv[mb_argc])
469#else // ANSI
470 // no need for cleanup
471 #define ARGS_CLEANUP
472
05079acc 473 wxChar **mb_argv = argv;
e90c1d2a 474#endif // Unicode/ANSI
518b5d2f 475
e90c1d2a 476#if wxUSE_GUI
518b5d2f 477 // create pipes
e90c1d2a 478 int end_proc_detect[2];
cd6ce4a9 479 if ( pipe(end_proc_detect) == -1 )
518b5d2f
VZ
480 {
481 wxLogSysError( _("Pipe creation failed") );
cd6ce4a9 482 wxLogError( _("Failed to execute '%s'\n"), *argv );
e90c1d2a
VZ
483
484 ARGS_CLEANUP;
485
accb3257 486 return ERROR_RETURN_CODE;
518b5d2f 487 }
e90c1d2a 488#endif // wxUSE_GUI
518b5d2f 489
f6bcfd97
BP
490 // pipes for inter process communication
491 int pipeIn[2], // stdin
492 pipeOut[2], // stdout
493 pipeErr[2]; // stderr
494
cd6ce4a9 495 pipeIn[0] = pipeIn[1] =
f6bcfd97
BP
496 pipeOut[0] = pipeOut[1] =
497 pipeErr[0] = pipeErr[1] = -1;
cd6ce4a9
VZ
498
499 if ( process && process->IsRedirected() )
8b33ae2d 500 {
f6bcfd97 501 if ( pipe(pipeIn) == -1 || pipe(pipeOut) == -1 || pipe(pipeErr) == -1 )
8b33ae2d 502 {
cd6ce4a9
VZ
503#if wxUSE_GUI
504 // free previously allocated resources
8b33ae2d
GL
505 close(end_proc_detect[0]);
506 close(end_proc_detect[1]);
cd6ce4a9
VZ
507#endif // wxUSE_GUI
508
509 wxLogSysError( _("Pipe creation failed") );
510 wxLogError( _("Failed to execute '%s'\n"), *argv );
8b33ae2d
GL
511
512 ARGS_CLEANUP;
513
accb3257 514 return ERROR_RETURN_CODE;
8b33ae2d
GL
515 }
516 }
8b33ae2d 517
518b5d2f 518 // fork the process
0fcdf6dc 519#ifdef HAVE_VFORK
518b5d2f
VZ
520 pid_t pid = vfork();
521#else
522 pid_t pid = fork();
523#endif
cd6ce4a9
VZ
524
525 if ( pid == -1 ) // error?
518b5d2f 526 {
8b33ae2d
GL
527#if wxUSE_GUI
528 close(end_proc_detect[0]);
529 close(end_proc_detect[1]);
cd6ce4a9
VZ
530 close(pipeIn[0]);
531 close(pipeIn[1]);
532 close(pipeOut[0]);
533 close(pipeOut[1]);
f6bcfd97
BP
534 close(pipeErr[0]);
535 close(pipeErr[1]);
cd6ce4a9
VZ
536#endif // wxUSE_GUI
537
518b5d2f 538 wxLogSysError( _("Fork failed") );
e90c1d2a
VZ
539
540 ARGS_CLEANUP;
541
accb3257 542 return ERROR_RETURN_CODE;
518b5d2f 543 }
cd6ce4a9 544 else if ( pid == 0 ) // we're in child
518b5d2f 545 {
e90c1d2a 546#if wxUSE_GUI
518b5d2f 547 close(end_proc_detect[0]); // close reading side
e90c1d2a 548#endif // wxUSE_GUI
518b5d2f 549
cd6ce4a9 550 // These lines close the open file descriptors to to avoid any
518b5d2f 551 // input/output which might block the process or irritate the user. If
cd6ce4a9
VZ
552 // one wants proper IO for the subprocess, the right thing to do is to
553 // start an xterm executing it.
554 if ( !sync )
518b5d2f 555 {
518b5d2f
VZ
556 for ( int fd = 0; fd < FD_SETSIZE; fd++ )
557 {
f6bcfd97 558 if ( fd == pipeIn[0] || fd == pipeOut[1] || fd == pipeErr[1]
e90c1d2a 559#if wxUSE_GUI
cd6ce4a9 560 || fd == end_proc_detect[1]
e90c1d2a 561#endif // wxUSE_GUI
cd6ce4a9
VZ
562 )
563 {
564 // don't close this one, we still need it
565 continue;
566 }
e90c1d2a 567
cd6ce4a9 568 // leave stderr opened too, it won't do any hurm
e90c1d2a 569 if ( fd != STDERR_FILENO )
518b5d2f
VZ
570 close(fd);
571 }
572 }
573
f6bcfd97 574 // redirect stdio, stdout and stderr
cd6ce4a9
VZ
575 if ( pipeIn[0] != -1 )
576 {
577 if ( dup2(pipeIn[0], STDIN_FILENO) == -1 ||
f6bcfd97
BP
578 dup2(pipeOut[1], STDOUT_FILENO) == -1 ||
579 dup2(pipeErr[1], STDERR_FILENO) == -1 )
cd6ce4a9 580 {
f6bcfd97 581 wxLogSysError(_("Failed to redirect child process input/output"));
cd6ce4a9 582 }
518b5d2f 583
cd6ce4a9
VZ
584 close(pipeIn[0]);
585 close(pipeOut[1]);
f6bcfd97 586 close(pipeErr[1]);
cd6ce4a9 587 }
518b5d2f 588
05079acc 589 execvp (*mb_argv, mb_argv);
518b5d2f
VZ
590
591 // there is no return after successful exec()
518b5d2f
VZ
592 _exit(-1);
593 }
cd6ce4a9 594 else // we're in parent
518b5d2f 595 {
cd6ce4a9
VZ
596 ARGS_CLEANUP;
597
598 // pipe initialization: construction of the wxStreams
599 if ( process && process->IsRedirected() )
600 {
1e6feb95 601#if wxUSE_STREAMS
cd6ce4a9
VZ
602 // These two streams are relative to this process.
603 wxOutputStream *outStream = new wxProcessFileOutputStream(pipeIn[1]);
604 wxInputStream *inStream = new wxProcessFileInputStream(pipeOut[0]);
f6bcfd97
BP
605 wxInputStream *errStream = new wxProcessFileInputStream(pipeErr[0]);
606
1e6feb95
VZ
607 process->SetPipeStreams(inStream, outStream, errStream);
608#endif // wxUSE_STREAMS
609
cd6ce4a9
VZ
610 close(pipeIn[0]); // close reading side
611 close(pipeOut[1]); // close writing side
f6bcfd97 612 close(pipeErr[1]); // close writing side
cd6ce4a9
VZ
613 }
614
fac3b423 615#if wxUSE_GUI && !defined(__WXMICROWIN__)
518b5d2f 616 wxEndProcessData *data = new wxEndProcessData;
ab857a4e 617
518b5d2f
VZ
618 if ( sync )
619 {
cd6ce4a9
VZ
620 // we may have process for capturing the program output, but it's
621 // not used in wxEndProcessData in the case of sync execution
518b5d2f
VZ
622 data->process = NULL;
623
624 // sync execution: indicate it by negating the pid
cd6ce4a9
VZ
625 data->pid = -pid;
626 data->tag = wxAddProcessCallback(data, end_proc_detect[0]);
627
ab857a4e 628 close(end_proc_detect[1]); // close writing side
518b5d2f 629
cd6ce4a9
VZ
630 wxBusyCursor bc;
631 wxWindowDisabler wd;
632
518b5d2f
VZ
633 // it will be set to 0 from GTK_EndProcessDetector
634 while (data->pid != 0)
635 wxYield();
636
637 int exitcode = data->exitcode;
638
639 delete data;
640
641 return exitcode;
642 }
cd6ce4a9 643 else // async execution
518b5d2f
VZ
644 {
645 // async execution, nothing special to do - caller will be
ab857a4e 646 // notified about the process termination if process != NULL, data
518b5d2f 647 // will be deleted in GTK_EndProcessDetector
8b33ae2d
GL
648 data->process = process;
649 data->pid = pid;
650 data->tag = wxAddProcessCallback(data, end_proc_detect[0]);
cd6ce4a9 651
ab857a4e 652 close(end_proc_detect[1]); // close writing side
518b5d2f
VZ
653
654 return pid;
655 }
e90c1d2a 656#else // !wxUSE_GUI
223d09f6 657 wxASSERT_MSG( sync, wxT("async execution not supported yet") );
e90c1d2a
VZ
658
659 int exitcode = 0;
660 if ( waitpid(pid, &exitcode, 0) == -1 || !WIFEXITED(exitcode) )
661 {
662 wxLogSysError(_("Waiting for subprocess termination failed"));
663 }
664
665 return exitcode;
666#endif // wxUSE_GUI
518b5d2f 667 }
57681e5b
JJ
668#ifdef __VMS
669 // VMS does not recognise exit as a return and complains about
670 // a missing return
671 // I think VMS is wrong in this
672 // JJ
673 return 0;
674#endif
518b5d2f
VZ
675}
676
accb3257 677#undef ERROR_RETURN_CODE
f6bcfd97
BP
678#undef ARGS_CLEANUP
679
518b5d2f
VZ
680// ----------------------------------------------------------------------------
681// file and directory functions
682// ----------------------------------------------------------------------------
683
05079acc 684const wxChar* wxGetHomeDir( wxString *home )
518b5d2f
VZ
685{
686 *home = wxGetUserHome( wxString() );
181cbcf4 687 wxString tmp;
518b5d2f 688 if ( home->IsEmpty() )
223d09f6 689 *home = wxT("/");
181cbcf4
JJ
690#ifdef __VMS
691 tmp = *home;
692 if ( tmp.Last() != wxT(']'))
693 if ( tmp.Last() != wxT('/')) *home << wxT('/');
694#endif
518b5d2f
VZ
695 return home->c_str();
696}
697
05079acc
OK
698#if wxUSE_UNICODE
699const wxMB2WXbuf wxGetUserHome( const wxString &user )
e90c1d2a 700#else // just for binary compatibility -- there is no 'const' here
518b5d2f 701char *wxGetUserHome( const wxString &user )
05079acc 702#endif
518b5d2f
VZ
703{
704 struct passwd *who = (struct passwd *) NULL;
705
0fb67cd1 706 if ( !user )
518b5d2f 707 {
e90c1d2a 708 wxChar *ptr;
518b5d2f 709
223d09f6 710 if ((ptr = wxGetenv(wxT("HOME"))) != NULL)
518b5d2f
VZ
711 {
712 return ptr;
713 }
223d09f6 714 if ((ptr = wxGetenv(wxT("USER"))) != NULL || (ptr = wxGetenv(wxT("LOGNAME"))) != NULL)
518b5d2f 715 {
e90c1d2a 716 who = getpwnam(wxConvertWX2MB(ptr));
518b5d2f
VZ
717 }
718
719 // We now make sure the the user exists!
720 if (who == NULL)
721 {
722 who = getpwuid(getuid());
723 }
724 }
725 else
726 {
05079acc 727 who = getpwnam (user.mb_str());
518b5d2f
VZ
728 }
729
af111fc3 730 return wxConvertMB2WX(who ? who->pw_dir : 0);
518b5d2f
VZ
731}
732
733// ----------------------------------------------------------------------------
0fb67cd1 734// network and user id routines
518b5d2f
VZ
735// ----------------------------------------------------------------------------
736
0fb67cd1
VZ
737// retrieve either the hostname or FQDN depending on platform (caller must
738// check whether it's one or the other, this is why this function is for
739// private use only)
05079acc 740static bool wxGetHostNameInternal(wxChar *buf, int sz)
518b5d2f 741{
223d09f6 742 wxCHECK_MSG( buf, FALSE, wxT("NULL pointer in wxGetHostNameInternal") );
518b5d2f 743
223d09f6 744 *buf = wxT('\0');
518b5d2f
VZ
745
746 // we're using uname() which is POSIX instead of less standard sysinfo()
747#if defined(HAVE_UNAME)
cc743a6f 748 struct utsname uts;
518b5d2f
VZ
749 bool ok = uname(&uts) != -1;
750 if ( ok )
751 {
e90c1d2a 752 wxStrncpy(buf, wxConvertMB2WX(uts.nodename), sz - 1);
223d09f6 753 buf[sz] = wxT('\0');
518b5d2f
VZ
754 }
755#elif defined(HAVE_GETHOSTNAME)
756 bool ok = gethostname(buf, sz) != -1;
0fb67cd1 757#else // no uname, no gethostname
223d09f6 758 wxFAIL_MSG(wxT("don't know host name for this machine"));
518b5d2f
VZ
759
760 bool ok = FALSE;
0fb67cd1 761#endif // uname/gethostname
518b5d2f
VZ
762
763 if ( !ok )
764 {
765 wxLogSysError(_("Cannot get the hostname"));
766 }
767
768 return ok;
769}
770
05079acc 771bool wxGetHostName(wxChar *buf, int sz)
0fb67cd1
VZ
772{
773 bool ok = wxGetHostNameInternal(buf, sz);
774
775 if ( ok )
776 {
777 // BSD systems return the FQDN, we only want the hostname, so extract
778 // it (we consider that dots are domain separators)
223d09f6 779 wxChar *dot = wxStrchr(buf, wxT('.'));
0fb67cd1
VZ
780 if ( dot )
781 {
782 // nuke it
223d09f6 783 *dot = wxT('\0');
0fb67cd1
VZ
784 }
785 }
786
787 return ok;
788}
789
05079acc 790bool wxGetFullHostName(wxChar *buf, int sz)
0fb67cd1
VZ
791{
792 bool ok = wxGetHostNameInternal(buf, sz);
793
794 if ( ok )
795 {
223d09f6 796 if ( !wxStrchr(buf, wxT('.')) )
0fb67cd1 797 {
e90c1d2a 798 struct hostent *host = gethostbyname(wxConvertWX2MB(buf));
0fb67cd1
VZ
799 if ( !host )
800 {
801 wxLogSysError(_("Cannot get the official hostname"));
802
803 ok = FALSE;
804 }
805 else
806 {
807 // the canonical name
e90c1d2a 808 wxStrncpy(buf, wxConvertMB2WX(host->h_name), sz);
0fb67cd1
VZ
809 }
810 }
811 //else: it's already a FQDN (BSD behaves this way)
812 }
813
814 return ok;
815}
816
05079acc 817bool wxGetUserId(wxChar *buf, int sz)
518b5d2f
VZ
818{
819 struct passwd *who;
820
223d09f6 821 *buf = wxT('\0');
518b5d2f
VZ
822 if ((who = getpwuid(getuid ())) != NULL)
823 {
e90c1d2a 824 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
518b5d2f
VZ
825 return TRUE;
826 }
827
828 return FALSE;
829}
830
05079acc 831bool wxGetUserName(wxChar *buf, int sz)
518b5d2f
VZ
832{
833 struct passwd *who;
518b5d2f 834
223d09f6 835 *buf = wxT('\0');
b12915c1
VZ
836 if ((who = getpwuid (getuid ())) != NULL)
837 {
838 // pw_gecos field in struct passwd is not standard
bd3277fe 839#ifdef HAVE_PW_GECOS
b12915c1 840 char *comma = strchr(who->pw_gecos, ',');
518b5d2f
VZ
841 if (comma)
842 *comma = '\0'; // cut off non-name comment fields
e90c1d2a 843 wxStrncpy (buf, wxConvertMB2WX(who->pw_gecos), sz - 1);
b12915c1 844#else // !HAVE_PW_GECOS
0fcdf6dc 845 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
b12915c1 846#endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
518b5d2f
VZ
847 return TRUE;
848 }
849
850 return FALSE;
851}
852
bdc72a22
VZ
853wxString wxGetOsDescription()
854{
855#ifndef WXWIN_OS_DESCRIPTION
856 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
857#else
858 return WXWIN_OS_DESCRIPTION;
859#endif
860}
861
bd3277fe
VZ
862// this function returns the GUI toolkit version in GUI programs, but OS
863// version in non-GUI ones
864#if !wxUSE_GUI
865
866int wxGetOsVersion(int *majorVsn, int *minorVsn)
867{
868 int major, minor;
869 char name[256];
870
871 if ( sscanf(WXWIN_OS_DESCRIPTION, "%s %d.%d", name, &major, &minor) != 3 )
872 {
873 // unreckognized uname string format
874 major = minor = -1;
875 }
876
877 if ( majorVsn )
878 *majorVsn = major;
879 if ( minorVsn )
880 *minorVsn = minor;
881
882 return wxUNIX;
883}
884
885#endif // !wxUSE_GUI
886
887long wxGetFreeMemory()
888{
889#if defined(__LINUX__)
890 // get it from /proc/meminfo
891 FILE *fp = fopen("/proc/meminfo", "r");
892 if ( fp )
893 {
894 long memFree = -1;
895
896 char buf[1024];
897 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
898 {
899 long memTotal, memUsed;
900 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
901 }
902
903 fclose(fp);
904
905 return memFree;
906 }
907#elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
908 return sysconf(_SC_AVPHYS_PAGES)*sysconf(_SC_PAGESIZE);
909//#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
910#endif
911
912 // can't find it out
913 return -1;
914}
915
eadd7bd2
VZ
916bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
917{
918#ifdef HAVE_STATFS
919
920 struct statfs fs;
921 if ( statfs(path, &fs) != 0 )
922 {
923 wxLogSysError("Failed to get file system statistics");
924
925 return FALSE;
926 }
927
928 if ( pTotal )
929 {
930 *pTotal = wxLongLong(fs.f_blocks) * fs.f_bsize;
931 }
932
933 if ( pFree )
934 {
935 *pFree = wxLongLong(fs.f_bavail) * fs.f_bsize;
936 }
937
938 return TRUE;
939#endif // HAVE_STATFS
940
941 return FALSE;
942}
943
8fd0d89b
VZ
944// ----------------------------------------------------------------------------
945// env vars
946// ----------------------------------------------------------------------------
947
97b305b7 948bool wxGetEnv(const wxString& var, wxString *value)
308978f6
VZ
949{
950 // wxGetenv is defined as getenv()
951 wxChar *p = wxGetenv(var);
952 if ( !p )
953 return FALSE;
954
955 if ( value )
956 {
957 *value = p;
958 }
959
960 return TRUE;
961}
962
8fd0d89b
VZ
963bool wxSetEnv(const wxString& variable, const wxChar *value)
964{
965#if defined(HAVE_SETENV)
966 return setenv(variable.mb_str(), value ? wxString(value).mb_str().data()
967 : NULL, 1 /* overwrite */) == 0;
968#elif defined(HAVE_PUTENV)
969 wxString s = variable;
970 if ( value )
971 s << _T('=') << value;
972
973 // transform to ANSI
974 const char *p = s.mb_str();
975
976 // the string will be free()d by libc
977 char *buf = (char *)malloc(strlen(p) + 1);
978 strcpy(buf, p);
979
980 return putenv(buf) == 0;
981#else // no way to set an env var
982 return FALSE;
983#endif
984}
985
a37a5a73
VZ
986// ----------------------------------------------------------------------------
987// signal handling
988// ----------------------------------------------------------------------------
989
990#if wxUSE_ON_FATAL_EXCEPTION
991
992#include <signal.h>
993
f6bcfd97 994static void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
a37a5a73
VZ
995{
996 if ( wxTheApp )
997 {
998 // give the user a chance to do something special about this
999 wxTheApp->OnFatalException();
1000 }
1001
1002 abort();
1003}
1004
1005bool wxHandleFatalExceptions(bool doit)
1006{
1007 // old sig handlers
1008 static bool s_savedHandlers = FALSE;
1009 static struct sigaction s_handlerFPE,
1010 s_handlerILL,
1011 s_handlerBUS,
1012 s_handlerSEGV;
1013
1014 bool ok = TRUE;
1015 if ( doit && !s_savedHandlers )
1016 {
1017 // install the signal handler
1018 struct sigaction act;
1019
1020 // some systems extend it with non std fields, so zero everything
1021 memset(&act, 0, sizeof(act));
1022
1023 act.sa_handler = wxFatalSignalHandler;
1024 sigemptyset(&act.sa_mask);
1025 act.sa_flags = 0;
1026
1027 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1028 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1029 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1030 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1031 if ( !ok )
1032 {
1033 wxLogDebug(_T("Failed to install our signal handler."));
1034 }
1035
1036 s_savedHandlers = TRUE;
1037 }
1038 else if ( s_savedHandlers )
1039 {
1040 // uninstall the signal handler
1041 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1042 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1043 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1044 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1045 if ( !ok )
1046 {
1047 wxLogDebug(_T("Failed to uninstall our signal handler."));
1048 }
1049
1050 s_savedHandlers = FALSE;
1051 }
1052 //else: nothing to do
1053
1054 return ok;
1055}
1056
1057#endif // wxUSE_ON_FATAL_EXCEPTION
1058
518b5d2f
VZ
1059// ----------------------------------------------------------------------------
1060// error and debug output routines (deprecated, use wxLog)
1061// ----------------------------------------------------------------------------
1062
1063void wxDebugMsg( const char *format, ... )
1064{
1065 va_list ap;
1066 va_start( ap, format );
1067 vfprintf( stderr, format, ap );
1068 fflush( stderr );
1069 va_end(ap);
1070}
1071
1072void wxError( const wxString &msg, const wxString &title )
1073{
05079acc 1074 wxFprintf( stderr, _("Error ") );
223d09f6
KB
1075 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1076 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1077 wxFprintf( stderr, wxT(".\n") );
518b5d2f
VZ
1078}
1079
1080void wxFatalError( const wxString &msg, const wxString &title )
1081{
05079acc 1082 wxFprintf( stderr, _("Error ") );
223d09f6
KB
1083 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1084 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1085 wxFprintf( stderr, wxT(".\n") );
518b5d2f
VZ
1086 exit(3); // the same exit code as for abort()
1087}
93ccaed8 1088