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