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