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