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