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