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