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