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