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