]> git.saurik.com Git - wxWidgets.git/blob - src/unix/utilsunx.cpp
Committing in .
[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 #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 #if wxUSE_UNICODE
257 long lRc = -1;
258 #else
259 long lRc = wxExecute(argv, flags, process);
260 #endif
261
262 // clean up
263 argc = 0;
264 while( argv[argc] )
265 delete [] argv[argc++];
266
267 return lRc;
268 }
269
270 // ----------------------------------------------------------------------------
271 // wxShell
272 // ----------------------------------------------------------------------------
273
274 static wxString wxMakeShellCommand(const wxString& command)
275 {
276 wxString cmd;
277 if ( !command )
278 {
279 // just an interactive shell
280 cmd = _T("xterm");
281 }
282 else
283 {
284 // execute command in a shell
285 cmd << _T("/bin/sh -c '") << command << _T('\'');
286 }
287
288 return cmd;
289 }
290
291 bool wxShell(const wxString& command)
292 {
293 return wxExecute(wxMakeShellCommand(command), wxEXEC_SYNC) == 0;
294 }
295
296 bool wxShell(const wxString& command, wxArrayString& output)
297 {
298 wxCHECK_MSG( !!command, FALSE, _T("can't exec shell non interactively") );
299
300 return wxExecute(wxMakeShellCommand(command), output);
301 }
302
303 // Shutdown or reboot the PC
304 bool wxShutdown(wxShutdownFlags wFlags)
305 {
306 wxChar level;
307 switch ( wFlags )
308 {
309 case wxSHUTDOWN_POWEROFF:
310 level = _T('0');
311 break;
312
313 case wxSHUTDOWN_REBOOT:
314 level = _T('6');
315 break;
316
317 default:
318 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
319 return FALSE;
320 }
321
322 return system(wxString::Format(_T("init %c"), level).mb_str()) == 0;
323 }
324
325
326 #if wxUSE_GUI
327
328 void wxHandleProcessTermination(wxEndProcessData *proc_data)
329 {
330 // notify user about termination if required
331 if ( proc_data->process )
332 {
333 proc_data->process->OnTerminate(proc_data->pid, proc_data->exitcode);
334 }
335
336 // clean up
337 if ( proc_data->pid > 0 )
338 {
339 delete proc_data;
340 }
341 else
342 {
343 // let wxExecute() know that the process has terminated
344 proc_data->pid = 0;
345 }
346 }
347
348 #endif // wxUSE_GUI
349
350 // ----------------------------------------------------------------------------
351 // wxStream classes to support IO redirection in wxExecute
352 // ----------------------------------------------------------------------------
353
354 #if wxUSE_STREAMS
355
356 // ----------------------------------------------------------------------------
357 // wxPipeInputStream: stream for reading from a pipe
358 // ----------------------------------------------------------------------------
359
360 class wxPipeInputStream : public wxFileInputStream
361 {
362 public:
363 wxPipeInputStream(int fd) : wxFileInputStream(fd) { }
364
365 // return TRUE if the pipe is still opened
366 bool IsOpened() const { return !Eof(); }
367
368 // return TRUE if we have anything to read, don't block
369 bool IsAvailable() const;
370 };
371
372 bool wxPipeInputStream::IsAvailable() const
373 {
374 if ( m_lasterror == wxSTREAM_EOF )
375 return FALSE;
376
377 // check if there is any input available
378 struct timeval tv;
379 tv.tv_sec = 0;
380 tv.tv_usec = 0;
381
382 const int fd = m_file->fd();
383
384 fd_set readfds;
385 FD_ZERO(&readfds);
386 FD_SET(fd, &readfds);
387 switch ( select(fd + 1, &readfds, NULL, NULL, &tv) )
388 {
389 case -1:
390 wxLogSysError(_("Impossible to get child process input"));
391 // fall through
392
393 case 0:
394 return FALSE;
395
396 default:
397 wxFAIL_MSG(_T("unexpected select() return value"));
398 // still fall through
399
400 case 1:
401 // input available -- or maybe not, as select() returns 1 when a
402 // read() will complete without delay, but it could still not read
403 // anything
404 return !Eof();
405 }
406 }
407
408 // define this to let wxexec.cpp know that we know what we're doing
409 #define _WX_USED_BY_WXEXECUTE_
410 #include "../common/execcmn.cpp"
411
412 #endif // wxUSE_STREAMS
413
414 // ----------------------------------------------------------------------------
415 // wxPipe: this encapsulates pipe() system call
416 // ----------------------------------------------------------------------------
417
418 class wxPipe
419 {
420 public:
421 // the symbolic names for the pipe ends
422 enum Direction
423 {
424 Read,
425 Write
426 };
427
428 enum
429 {
430 INVALID_FD = -1
431 };
432
433 // default ctor doesn't do anything
434 wxPipe() { m_fds[Read] = m_fds[Write] = INVALID_FD; }
435
436 // create the pipe, return TRUE if ok, FALSE on error
437 bool Create()
438 {
439 if ( pipe(m_fds) == -1 )
440 {
441 wxLogSysError(_("Pipe creation failed"));
442
443 return FALSE;
444 }
445
446 return TRUE;
447 }
448
449 // return TRUE if we were created successfully
450 bool IsOk() const { return m_fds[Read] != INVALID_FD; }
451
452 // return the descriptor for one of the pipe ends
453 int operator[](Direction which) const
454 {
455 wxASSERT_MSG( which >= 0 && (size_t)which < WXSIZEOF(m_fds),
456 _T("invalid pipe index") );
457
458 return m_fds[which];
459 }
460
461 // detach a descriptor, meaning that the pipe dtor won't close it, and
462 // return it
463 int Detach(Direction which)
464 {
465 wxASSERT_MSG( which >= 0 && (size_t)which < WXSIZEOF(m_fds),
466 _T("invalid pipe index") );
467
468 int fd = m_fds[which];
469 m_fds[which] = INVALID_FD;
470
471 return fd;
472 }
473
474 // close the pipe descriptors
475 void Close()
476 {
477 for ( size_t n = 0; n < WXSIZEOF(m_fds); n++ )
478 {
479 if ( m_fds[n] != INVALID_FD )
480 close(m_fds[n]);
481 }
482 }
483
484 // dtor closes the pipe descriptors
485 ~wxPipe() { Close(); }
486
487 private:
488 int m_fds[2];
489 };
490
491 // ----------------------------------------------------------------------------
492 // wxExecute: the real worker function
493 // ----------------------------------------------------------------------------
494
495 #ifdef __VMS
496 #pragma message disable codeunreachable
497 #endif
498
499 long wxExecute(wxChar **argv,
500 int flags,
501 wxProcess *process)
502 {
503 // for the sync execution, we return -1 to indicate failure, but for async
504 // case we return 0 which is never a valid PID
505 //
506 // we define this as a macro, not a variable, to avoid compiler warnings
507 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
508 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
509
510 wxCHECK_MSG( *argv, ERROR_RETURN_CODE, wxT("can't exec empty command") );
511
512 #if wxUSE_UNICODE
513 int mb_argc = 0;
514 char *mb_argv[WXEXECUTE_NARGS];
515
516 while (argv[mb_argc])
517 {
518 wxWX2MBbuf mb_arg = wxConvertWX2MB(argv[mb_argc]);
519 mb_argv[mb_argc] = strdup(mb_arg);
520 mb_argc++;
521 }
522 mb_argv[mb_argc] = (char *) NULL;
523
524 // this macro will free memory we used above
525 #define ARGS_CLEANUP \
526 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
527 free(mb_argv[mb_argc])
528 #else // ANSI
529 // no need for cleanup
530 #define ARGS_CLEANUP
531
532 wxChar **mb_argv = argv;
533 #endif // Unicode/ANSI
534
535 #if wxUSE_GUI
536 // create pipes
537 wxPipe pipeEndProcDetect;
538 if ( !pipeEndProcDetect.Create() )
539 {
540 wxLogError( _("Failed to execute '%s'\n"), *argv );
541
542 ARGS_CLEANUP;
543
544 return ERROR_RETURN_CODE;
545 }
546 #endif // wxUSE_GUI
547
548 // pipes for inter process communication
549 wxPipe pipeIn, // stdin
550 pipeOut, // stdout
551 pipeErr; // stderr
552
553 if ( process && process->IsRedirected() )
554 {
555 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
556 {
557 wxLogError( _("Failed to execute '%s'\n"), *argv );
558
559 ARGS_CLEANUP;
560
561 return ERROR_RETURN_CODE;
562 }
563 }
564
565 // fork the process
566 //
567 // NB: do *not* use vfork() here, it completely breaks this code for some
568 // reason under Solaris (and maybe others, although not under Linux)
569 // But on OpenVMS we do not have fork so we have to use vfork and
570 // cross our fingers that it works.
571 #ifdef __VMS
572 pid_t pid = vfork();
573 #else
574 pid_t pid = fork();
575 #endif
576 if ( pid == -1 ) // error?
577 {
578 wxLogSysError( _("Fork failed") );
579
580 ARGS_CLEANUP;
581
582 return ERROR_RETURN_CODE;
583 }
584 else if ( pid == 0 ) // we're in child
585 {
586 // These lines close the open file descriptors to to avoid any
587 // input/output which might block the process or irritate the user. If
588 // one wants proper IO for the subprocess, the right thing to do is to
589 // start an xterm executing it.
590 if ( !(flags & wxEXEC_SYNC) )
591 {
592 for ( int fd = 0; fd < FD_SETSIZE; fd++ )
593 {
594 if ( fd == pipeIn[wxPipe::Read]
595 || fd == pipeOut[wxPipe::Write]
596 || fd == pipeErr[wxPipe::Write]
597 #if wxUSE_GUI
598 || fd == pipeEndProcDetect[wxPipe::Write]
599 #endif // wxUSE_GUI
600 )
601 {
602 // don't close this one, we still need it
603 continue;
604 }
605
606 // leave stderr opened too, it won't do any harm
607 if ( fd != STDERR_FILENO )
608 close(fd);
609 }
610 }
611
612 #if !defined(__VMS) && !defined(__EMX__)
613 if ( flags & wxEXEC_MAKE_GROUP_LEADER )
614 {
615 // Set process group to child process' pid. Then killing -pid
616 // of the parent will kill the process and all of its children.
617 setsid();
618 }
619 #endif // !__VMS
620
621 #if wxUSE_GUI
622 // reading side can be safely closed but we should keep the write one
623 // opened
624 pipeEndProcDetect.Detach(wxPipe::Write);
625 pipeEndProcDetect.Close();
626 #endif // wxUSE_GUI
627
628 // redirect stdin, stdout and stderr
629 if ( pipeIn.IsOk() )
630 {
631 if ( dup2(pipeIn[wxPipe::Read], STDIN_FILENO) == -1 ||
632 dup2(pipeOut[wxPipe::Write], STDOUT_FILENO) == -1 ||
633 dup2(pipeErr[wxPipe::Write], STDERR_FILENO) == -1 )
634 {
635 wxLogSysError(_("Failed to redirect child process input/output"));
636 }
637
638 pipeIn.Close();
639 pipeOut.Close();
640 pipeErr.Close();
641 }
642
643 execvp (*mb_argv, mb_argv);
644
645 // there is no return after successful exec()
646 _exit(-1);
647
648 // some compilers complain about missing return - of course, they
649 // should know that exit() doesn't return but what else can we do if
650 // they don't?
651 //
652 // and, sure enough, other compilers complain about unreachable code
653 // after exit() call, so we can just always have return here...
654 #if defined(__VMS) || defined(__INTEL_COMPILER)
655 return 0;
656 #endif
657 }
658 else // we're in parent
659 {
660 ARGS_CLEANUP;
661
662 // prepare for IO redirection
663
664 #if wxUSE_STREAMS
665 // the input buffer bufOut is connected to stdout, this is why it is
666 // called bufOut and not bufIn
667 wxStreamTempInputBuffer bufOut,
668 bufErr;
669 #endif // wxUSE_STREAMS
670
671 if ( process && process->IsRedirected() )
672 {
673 #if wxUSE_STREAMS
674 wxOutputStream *inStream =
675 new wxFileOutputStream(pipeIn.Detach(wxPipe::Write));
676
677 wxPipeInputStream *outStream =
678 new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
679
680 wxPipeInputStream *errStream =
681 new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
682
683 process->SetPipeStreams(outStream, inStream, errStream);
684
685 bufOut.Init(outStream);
686 bufErr.Init(errStream);
687 #endif // wxUSE_STREAMS
688 }
689
690 if ( pipeIn.IsOk() )
691 {
692 pipeIn.Close();
693 pipeOut.Close();
694 pipeErr.Close();
695 }
696
697 #if wxUSE_GUI && !defined(__WXMICROWIN__)
698 wxEndProcessData *data = new wxEndProcessData;
699
700 data->tag = wxAddProcessCallback
701 (
702 data,
703 pipeEndProcDetect.Detach(wxPipe::Read)
704 );
705
706 pipeEndProcDetect.Close();
707
708 if ( flags & wxEXEC_SYNC )
709 {
710 // we may have process for capturing the program output, but it's
711 // not used in wxEndProcessData in the case of sync execution
712 data->process = NULL;
713
714 // sync execution: indicate it by negating the pid
715 data->pid = -pid;
716
717 wxBusyCursor bc;
718 wxWindowDisabler wd;
719
720 // data->pid will be set to 0 from GTK_EndProcessDetector when the
721 // process terminates
722 while ( data->pid != 0 )
723 {
724 #if wxUSE_STREAMS
725 bufOut.Update();
726 bufErr.Update();
727 #endif // wxUSE_STREAMS
728
729 // give GTK+ a chance to call GTK_EndProcessDetector here and
730 // also repaint the GUI
731 wxYield();
732 }
733
734 int exitcode = data->exitcode;
735
736 delete data;
737
738 return exitcode;
739 }
740 else // async execution
741 {
742 // async execution, nothing special to do - caller will be
743 // notified about the process termination if process != NULL, data
744 // will be deleted in GTK_EndProcessDetector
745 data->process = process;
746 data->pid = pid;
747
748 return pid;
749 }
750 #else // !wxUSE_GUI
751
752 wxASSERT_MSG( flags & wxEXEC_SYNC,
753 wxT("async execution not supported yet") );
754
755 int exitcode = 0;
756 if ( waitpid(pid, &exitcode, 0) == -1 || !WIFEXITED(exitcode) )
757 {
758 wxLogSysError(_("Waiting for subprocess termination failed"));
759 }
760
761 return exitcode;
762 #endif // wxUSE_GUI
763 }
764
765 return ERROR_RETURN_CODE;
766 }
767
768 #ifdef __VMS
769 #pragma message enable codeunreachable
770 #endif
771
772 #undef ERROR_RETURN_CODE
773 #undef ARGS_CLEANUP
774
775 // ----------------------------------------------------------------------------
776 // file and directory functions
777 // ----------------------------------------------------------------------------
778
779 const wxChar* wxGetHomeDir( wxString *home )
780 {
781 *home = wxGetUserHome( wxString() );
782 wxString tmp;
783 if ( home->IsEmpty() )
784 *home = wxT("/");
785 #ifdef __VMS
786 tmp = *home;
787 if ( tmp.Last() != wxT(']'))
788 if ( tmp.Last() != wxT('/')) *home << wxT('/');
789 #endif
790 return home->c_str();
791 }
792
793 #if wxUSE_UNICODE
794 const wxMB2WXbuf wxGetUserHome( const wxString &user )
795 #else // just for binary compatibility -- there is no 'const' here
796 char *wxGetUserHome( const wxString &user )
797 #endif
798 {
799 struct passwd *who = (struct passwd *) NULL;
800
801 if ( !user )
802 {
803 wxChar *ptr;
804
805 if ((ptr = wxGetenv(wxT("HOME"))) != NULL)
806 {
807 return ptr;
808 }
809 if ((ptr = wxGetenv(wxT("USER"))) != NULL || (ptr = wxGetenv(wxT("LOGNAME"))) != NULL)
810 {
811 who = getpwnam(wxConvertWX2MB(ptr));
812 }
813
814 // We now make sure the the user exists!
815 if (who == NULL)
816 {
817 who = getpwuid(getuid());
818 }
819 }
820 else
821 {
822 who = getpwnam (user.mb_str());
823 }
824
825 return wxConvertMB2WX(who ? who->pw_dir : 0);
826 }
827
828 // ----------------------------------------------------------------------------
829 // network and user id routines
830 // ----------------------------------------------------------------------------
831
832 // retrieve either the hostname or FQDN depending on platform (caller must
833 // check whether it's one or the other, this is why this function is for
834 // private use only)
835 static bool wxGetHostNameInternal(wxChar *buf, int sz)
836 {
837 wxCHECK_MSG( buf, FALSE, wxT("NULL pointer in wxGetHostNameInternal") );
838
839 *buf = wxT('\0');
840
841 // we're using uname() which is POSIX instead of less standard sysinfo()
842 #if defined(HAVE_UNAME)
843 struct utsname uts;
844 bool ok = uname(&uts) != -1;
845 if ( ok )
846 {
847 wxStrncpy(buf, wxConvertMB2WX(uts.nodename), sz - 1);
848 buf[sz] = wxT('\0');
849 }
850 #elif defined(HAVE_GETHOSTNAME)
851 bool ok = gethostname(buf, sz) != -1;
852 #else // no uname, no gethostname
853 wxFAIL_MSG(wxT("don't know host name for this machine"));
854
855 bool ok = FALSE;
856 #endif // uname/gethostname
857
858 if ( !ok )
859 {
860 wxLogSysError(_("Cannot get the hostname"));
861 }
862
863 return ok;
864 }
865
866 bool wxGetHostName(wxChar *buf, int sz)
867 {
868 bool ok = wxGetHostNameInternal(buf, sz);
869
870 if ( ok )
871 {
872 // BSD systems return the FQDN, we only want the hostname, so extract
873 // it (we consider that dots are domain separators)
874 wxChar *dot = wxStrchr(buf, wxT('.'));
875 if ( dot )
876 {
877 // nuke it
878 *dot = wxT('\0');
879 }
880 }
881
882 return ok;
883 }
884
885 bool wxGetFullHostName(wxChar *buf, int sz)
886 {
887 bool ok = wxGetHostNameInternal(buf, sz);
888
889 if ( ok )
890 {
891 if ( !wxStrchr(buf, wxT('.')) )
892 {
893 struct hostent *host = gethostbyname(wxConvertWX2MB(buf));
894 if ( !host )
895 {
896 wxLogSysError(_("Cannot get the official hostname"));
897
898 ok = FALSE;
899 }
900 else
901 {
902 // the canonical name
903 wxStrncpy(buf, wxConvertMB2WX(host->h_name), sz);
904 }
905 }
906 //else: it's already a FQDN (BSD behaves this way)
907 }
908
909 return ok;
910 }
911
912 bool wxGetUserId(wxChar *buf, int sz)
913 {
914 struct passwd *who;
915
916 *buf = wxT('\0');
917 if ((who = getpwuid(getuid ())) != NULL)
918 {
919 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
920 return TRUE;
921 }
922
923 return FALSE;
924 }
925
926 bool wxGetUserName(wxChar *buf, int sz)
927 {
928 struct passwd *who;
929
930 *buf = wxT('\0');
931 if ((who = getpwuid (getuid ())) != NULL)
932 {
933 // pw_gecos field in struct passwd is not standard
934 #ifdef HAVE_PW_GECOS
935 char *comma = strchr(who->pw_gecos, ',');
936 if (comma)
937 *comma = '\0'; // cut off non-name comment fields
938 wxStrncpy (buf, wxConvertMB2WX(who->pw_gecos), sz - 1);
939 #else // !HAVE_PW_GECOS
940 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
941 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
942 return TRUE;
943 }
944
945 return FALSE;
946 }
947
948 #ifndef __WXMAC__
949 wxString wxGetOsDescription()
950 {
951 #ifndef WXWIN_OS_DESCRIPTION
952 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
953 #else
954 return WXWIN_OS_DESCRIPTION;
955 #endif
956 }
957 #endif
958
959 // this function returns the GUI toolkit version in GUI programs, but OS
960 // version in non-GUI ones
961 #if !wxUSE_GUI
962
963 int wxGetOsVersion(int *majorVsn, int *minorVsn)
964 {
965 int major, minor;
966 char name[256];
967
968 if ( sscanf(WXWIN_OS_DESCRIPTION, "%s %d.%d", name, &major, &minor) != 3 )
969 {
970 // unreckognized uname string format
971 major = minor = -1;
972 }
973
974 if ( majorVsn )
975 *majorVsn = major;
976 if ( minorVsn )
977 *minorVsn = minor;
978
979 return wxUNIX;
980 }
981
982 #endif // !wxUSE_GUI
983
984 unsigned long wxGetProcessId()
985 {
986 return (unsigned long)getpid();
987 }
988
989 long wxGetFreeMemory()
990 {
991 #if defined(__LINUX__)
992 // get it from /proc/meminfo
993 FILE *fp = fopen("/proc/meminfo", "r");
994 if ( fp )
995 {
996 long memFree = -1;
997
998 char buf[1024];
999 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
1000 {
1001 long memTotal, memUsed;
1002 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
1003 }
1004
1005 fclose(fp);
1006
1007 return memFree;
1008 }
1009 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
1010 return sysconf(_SC_AVPHYS_PAGES)*sysconf(_SC_PAGESIZE);
1011 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1012 #endif
1013
1014 // can't find it out
1015 return -1;
1016 }
1017
1018 bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
1019 {
1020 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1021 // the case to "char *" is needed for AIX 4.3
1022 wxStatFs fs;
1023 if ( statfs((char *)(const char*)path.fn_str(), &fs) != 0 )
1024 {
1025 wxLogSysError( wxT("Failed to get file system statistics") );
1026
1027 return FALSE;
1028 }
1029
1030 // under Solaris we also have to use f_frsize field instead of f_bsize
1031 // which is in general a multiple of f_frsize
1032 #ifdef HAVE_STATVFS
1033 wxLongLong blockSize = fs.f_frsize;
1034 #else // HAVE_STATFS
1035 wxLongLong blockSize = fs.f_bsize;
1036 #endif // HAVE_STATVFS/HAVE_STATFS
1037
1038 if ( pTotal )
1039 {
1040 *pTotal = wxLongLong(fs.f_blocks) * blockSize;
1041 }
1042
1043 if ( pFree )
1044 {
1045 *pFree = wxLongLong(fs.f_bavail) * blockSize;
1046 }
1047
1048 return TRUE;
1049 #else // !HAVE_STATFS && !HAVE_STATVFS
1050 return FALSE;
1051 #endif // HAVE_STATFS
1052 }
1053
1054 // ----------------------------------------------------------------------------
1055 // env vars
1056 // ----------------------------------------------------------------------------
1057
1058 bool wxGetEnv(const wxString& var, wxString *value)
1059 {
1060 // wxGetenv is defined as getenv()
1061 wxChar *p = wxGetenv(var);
1062 if ( !p )
1063 return FALSE;
1064
1065 if ( value )
1066 {
1067 *value = p;
1068 }
1069
1070 return TRUE;
1071 }
1072
1073 bool wxSetEnv(const wxString& variable, const wxChar *value)
1074 {
1075 #if defined(HAVE_SETENV)
1076 return setenv(variable.mb_str(),
1077 value ? (const char *)wxString(value).mb_str()
1078 : NULL,
1079 1 /* overwrite */) == 0;
1080 #elif defined(HAVE_PUTENV)
1081 wxString s = variable;
1082 if ( value )
1083 s << _T('=') << value;
1084
1085 // transform to ANSI
1086 const char *p = s.mb_str();
1087
1088 // the string will be free()d by libc
1089 char *buf = (char *)malloc(strlen(p) + 1);
1090 strcpy(buf, p);
1091
1092 return putenv(buf) == 0;
1093 #else // no way to set an env var
1094 return FALSE;
1095 #endif
1096 }
1097
1098 // ----------------------------------------------------------------------------
1099 // signal handling
1100 // ----------------------------------------------------------------------------
1101
1102 #if wxUSE_ON_FATAL_EXCEPTION
1103
1104 #include <signal.h>
1105
1106 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
1107 {
1108 if ( wxTheApp )
1109 {
1110 // give the user a chance to do something special about this
1111 wxTheApp->OnFatalException();
1112 }
1113
1114 abort();
1115 }
1116
1117 bool wxHandleFatalExceptions(bool doit)
1118 {
1119 // old sig handlers
1120 static bool s_savedHandlers = FALSE;
1121 static struct sigaction s_handlerFPE,
1122 s_handlerILL,
1123 s_handlerBUS,
1124 s_handlerSEGV;
1125
1126 bool ok = TRUE;
1127 if ( doit && !s_savedHandlers )
1128 {
1129 // install the signal handler
1130 struct sigaction act;
1131
1132 // some systems extend it with non std fields, so zero everything
1133 memset(&act, 0, sizeof(act));
1134
1135 act.sa_handler = wxFatalSignalHandler;
1136 sigemptyset(&act.sa_mask);
1137 act.sa_flags = 0;
1138
1139 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1140 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1141 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1142 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1143 if ( !ok )
1144 {
1145 wxLogDebug(_T("Failed to install our signal handler."));
1146 }
1147
1148 s_savedHandlers = TRUE;
1149 }
1150 else if ( s_savedHandlers )
1151 {
1152 // uninstall the signal handler
1153 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1154 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1155 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1156 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1157 if ( !ok )
1158 {
1159 wxLogDebug(_T("Failed to uninstall our signal handler."));
1160 }
1161
1162 s_savedHandlers = FALSE;
1163 }
1164 //else: nothing to do
1165
1166 return ok;
1167 }
1168
1169 #endif // wxUSE_ON_FATAL_EXCEPTION
1170
1171 // ----------------------------------------------------------------------------
1172 // error and debug output routines (deprecated, use wxLog)
1173 // ----------------------------------------------------------------------------
1174
1175 #if WXWIN_COMPATIBILITY_2_2
1176
1177 void wxDebugMsg( const char *format, ... )
1178 {
1179 va_list ap;
1180 va_start( ap, format );
1181 vfprintf( stderr, format, ap );
1182 fflush( stderr );
1183 va_end(ap);
1184 }
1185
1186 void wxError( const wxString &msg, const wxString &title )
1187 {
1188 wxFprintf( stderr, _("Error ") );
1189 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1190 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1191 wxFprintf( stderr, wxT(".\n") );
1192 }
1193
1194 void wxFatalError( const wxString &msg, const wxString &title )
1195 {
1196 wxFprintf( stderr, _("Error ") );
1197 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1198 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1199 wxFprintf( stderr, wxT(".\n") );
1200 exit(3); // the same exit code as for abort()
1201 }
1202
1203 #endif // WXWIN_COMPATIBILITY_2_2
1204