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