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