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