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