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