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