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