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