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