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