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