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