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