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