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