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