]>
git.saurik.com Git - wxWidgets.git/blob - src/unix/utilsunx.cpp
1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: generic Unix implementation of many wx functions
4 // Author: Vadim Zeitlin
6 // Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 // ============================================================================
12 // ============================================================================
14 // ----------------------------------------------------------------------------
16 // ----------------------------------------------------------------------------
19 #include "wx/string.h"
25 #include "wx/process.h"
26 #include "wx/thread.h"
28 #include "wx/unix/execute.h"
34 #include <sys/types.h>
41 #include <fcntl.h> // for O_WRONLY and friends
42 #include <time.h> // nanosleep() and/or usleep()
43 #include <ctype.h> // isspace()
44 #include <sys/time.h> // needed for FD_SETSIZE
47 #include <sys/utsname.h> // for uname()
50 // ----------------------------------------------------------------------------
51 // conditional compilation
52 // ----------------------------------------------------------------------------
54 // many versions of Unices have this function, but it is not defined in system
55 // headers - please add your system here if it is the case for your OS.
56 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
57 #if !defined(HAVE_USLEEP) && \
58 (defined(__SUN__) && !defined(__SunOs_5_6) && \
59 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
60 defined(__osf__) || defined(__EMX__)
64 int usleep(unsigned int usec
);
67 /* I copied this from the XFree86 diffs. AV. */
68 #define INCL_DOSPROCESS
70 inline void usleep(unsigned long delay
)
72 DosSleep(delay
? (delay
/1000l) : 1l);
75 void usleep(unsigned long usec
);
77 #endif // Sun/EMX/Something else
81 #endif // Unices without usleep()
83 // ============================================================================
85 // ============================================================================
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
91 void wxSleep(int nSecs
)
96 void wxUsleep(unsigned long milliseconds
)
98 #if defined(HAVE_NANOSLEEP)
100 tmReq
.tv_sec
= milliseconds
/ 1000;
101 tmReq
.tv_nsec
= (milliseconds
% 1000) * 1000 * 1000;
103 // we're not interested in remaining time nor in return value
104 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
105 #elif defined(HAVE_USLEEP)
106 // uncomment this if you feel brave or if you are sure that your version
107 // of Solaris has a safe usleep() function but please notice that usleep()
108 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
109 // documented as MT-Safe
110 #if defined(__SUN__) && wxUSE_THREADS
111 #error "usleep() cannot be used in MT programs under Solaris."
114 usleep(milliseconds
* 1000); // usleep(3) wants microseconds
115 #elif defined(HAVE_SLEEP)
116 // under BeOS sleep() takes seconds (what about other platforms, if any?)
117 sleep(milliseconds
* 1000);
118 #else // !sleep function
119 #error "usleep() or nanosleep() function required for wxUsleep"
120 #endif // sleep function
123 // ----------------------------------------------------------------------------
124 // process management
125 // ----------------------------------------------------------------------------
127 int wxKill(long pid
, wxSignal sig
)
129 return kill(pid
, (int)sig
);
132 #define WXEXECUTE_NARGS 127
134 long wxExecute( const wxString
& command
, bool sync
, wxProcess
*process
)
136 wxCHECK_MSG( !command
.IsEmpty(), 0, wxT("can't exec empty command") );
139 wxChar
*argv
[WXEXECUTE_NARGS
];
141 const wxChar
*cptr
= command
.c_str();
142 wxChar quotechar
= wxT('\0'); // is arg quoted?
143 bool escaped
= FALSE
;
145 // split the command line in arguments
149 quotechar
= wxT('\0');
151 // eat leading whitespace:
152 while ( wxIsspace(*cptr
) )
155 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
160 if ( *cptr
== wxT('\\') && ! escaped
)
167 // all other characters:
171 // have we reached the end of the argument?
172 if ( (*cptr
== quotechar
&& ! escaped
)
173 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
174 || *cptr
== wxT('\0') )
176 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
177 wxT("too many arguments in wxExecute") );
179 argv
[argc
] = new wxChar
[argument
.length() + 1];
180 wxStrcpy(argv
[argc
], argument
.c_str());
183 // if not at end of buffer, swallow last character:
187 break; // done with this one, start over
193 // do execute the command
194 long lRc
= wxExecute(argv
, sync
, process
);
199 delete [] argv
[argc
++];
204 bool wxShell(const wxString
& command
)
208 cmd
.Printf(wxT("xterm -e %s"), command
.c_str());
212 return wxExecute(cmd
) != 0;
215 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
217 int pid
= (proc_data
->pid
> 0) ? proc_data
->pid
: -(proc_data
->pid
);
219 // waitpid is POSIX so should be available everywhere, however on older
220 // systems wait() might be used instead in a loop (until the right pid
225 // wait for child termination and if waitpid() was interrupted, try again
228 rc
= waitpid(pid
, &status
, 0);
230 while ( rc
== -1 && errno
== EINTR
);
233 if( rc
== -1 || ! (WIFEXITED(status
) || WIFSIGNALED(status
)) )
235 wxLogSysError(_("Waiting for subprocess termination failed"));
236 /* AFAIK, this can only happen if something went wrong within
237 wxGTK, i.e. due to a race condition or some serious bug.
238 After having fixed the order of statements in
239 GTK_EndProcessDetector(). (KB)
244 // notify user about termination if required
245 if (proc_data
->process
)
247 proc_data
->process
->OnTerminate(proc_data
->pid
,
248 WEXITSTATUS(status
));
251 if ( proc_data
->pid
> 0 )
257 // wxExecute() will know about it
258 proc_data
->exitcode
= status
;
265 long wxExecute( wxChar
**argv
, bool sync
, wxProcess
*process
)
267 wxCHECK_MSG( *argv
, 0, wxT("can't exec empty command") );
271 char *mb_argv
[WXEXECUTE_NARGS
];
273 while (argv
[mb_argc
])
275 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
276 mb_argv
[mb_argc
] = strdup(mb_arg
);
279 mb_argv
[mb_argc
] = (char *) NULL
;
281 // this macro will free memory we used above
282 #define ARGS_CLEANUP \
283 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
284 free(mb_argv[mb_argc])
286 // no need for cleanup
289 wxChar
**mb_argv
= argv
;
290 #endif // Unicode/ANSI
294 int end_proc_detect
[2];
295 if (pipe(end_proc_detect
) == -1)
297 wxLogSysError( _("Pipe creation failed") );
313 wxLogSysError( _("Fork failed") );
323 close(end_proc_detect
[0]); // close reading side
326 // These three lines close the open file descriptors to to avoid any
327 // input/output which might block the process or irritate the user. If
328 // one wants proper IO for the subprocess, the right thing to do is
329 // to start an xterm executing it.
332 // leave stderr opened, it won't do any hurm
333 for ( int fd
= 0; fd
< FD_SETSIZE
; fd
++ )
336 if ( fd
== end_proc_detect
[1] )
340 if ( fd
!= STDERR_FILENO
)
346 close(STDERR_FILENO
);
348 // some programs complain about stderr not being open, so redirect
350 open("/dev/null", O_RDONLY
); // stdin
351 open("/dev/null", O_WRONLY
); // stdout
352 open("/dev/null", O_WRONLY
); // stderr
355 execvp (*mb_argv
, mb_argv
);
357 // there is no return after successful exec()
358 wxFprintf(stderr
, _("Can't execute '%s'\n"), *argv
);
365 wxEndProcessData
*data
= new wxEndProcessData
;
372 wxASSERT_MSG( !process
, wxT("wxProcess param ignored for sync exec") );
373 data
->process
= NULL
;
375 // sync execution: indicate it by negating the pid
377 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
379 close(end_proc_detect
[1]); // close writing side
381 // it will be set to 0 from GTK_EndProcessDetector
382 while (data
->pid
!= 0)
385 int exitcode
= data
->exitcode
;
393 // async execution, nothing special to do - caller will be
394 // notified about the process termination if process != NULL, data
395 // will be deleted in GTK_EndProcessDetector
396 data
->process
= process
;
398 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
400 close(end_proc_detect
[1]); // close writing side
405 wxASSERT_MSG( sync
, wxT("async execution not supported yet") );
408 if ( waitpid(pid
, &exitcode
, 0) == -1 || !WIFEXITED(exitcode
) )
410 wxLogSysError(_("Waiting for subprocess termination failed"));
421 // ----------------------------------------------------------------------------
422 // file and directory functions
423 // ----------------------------------------------------------------------------
425 const wxChar
* wxGetHomeDir( wxString
*home
)
427 *home
= wxGetUserHome( wxString() );
428 if ( home
->IsEmpty() )
431 return home
->c_str();
435 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
436 #else // just for binary compatibility -- there is no 'const' here
437 char *wxGetUserHome( const wxString
&user
)
440 struct passwd
*who
= (struct passwd
*) NULL
;
446 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
450 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
452 who
= getpwnam(wxConvertWX2MB(ptr
));
455 // We now make sure the the user exists!
458 who
= getpwuid(getuid());
463 who
= getpwnam (user
.mb_str());
466 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
469 // ----------------------------------------------------------------------------
470 // network and user id routines
471 // ----------------------------------------------------------------------------
473 // retrieve either the hostname or FQDN depending on platform (caller must
474 // check whether it's one or the other, this is why this function is for
476 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
478 wxCHECK_MSG( buf
, FALSE
, wxT("NULL pointer in wxGetHostNameInternal") );
482 // we're using uname() which is POSIX instead of less standard sysinfo()
483 #if defined(HAVE_UNAME)
485 bool ok
= uname(&uts
) != -1;
488 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
491 #elif defined(HAVE_GETHOSTNAME)
492 bool ok
= gethostname(buf
, sz
) != -1;
493 #else // no uname, no gethostname
494 wxFAIL_MSG(wxT("don't know host name for this machine"));
497 #endif // uname/gethostname
501 wxLogSysError(_("Cannot get the hostname"));
507 bool wxGetHostName(wxChar
*buf
, int sz
)
509 bool ok
= wxGetHostNameInternal(buf
, sz
);
513 // BSD systems return the FQDN, we only want the hostname, so extract
514 // it (we consider that dots are domain separators)
515 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
526 bool wxGetFullHostName(wxChar
*buf
, int sz
)
528 bool ok
= wxGetHostNameInternal(buf
, sz
);
532 if ( !wxStrchr(buf
, wxT('.')) )
534 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
537 wxLogSysError(_("Cannot get the official hostname"));
543 // the canonical name
544 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
547 //else: it's already a FQDN (BSD behaves this way)
553 bool wxGetUserId(wxChar
*buf
, int sz
)
558 if ((who
= getpwuid(getuid ())) != NULL
)
560 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
567 bool wxGetUserName(wxChar
*buf
, int sz
)
572 if ((who
= getpwuid (getuid ())) != NULL
)
574 // pw_gecos field in struct passwd is not standard
576 char *comma
= strchr(who
->pw_gecos
, ',');
578 *comma
= '\0'; // cut off non-name comment fields
579 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
580 #else // !HAVE_PW_GECOS
581 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
582 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
589 wxString
wxGetOsDescription()
591 #ifndef WXWIN_OS_DESCRIPTION
592 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
594 return WXWIN_OS_DESCRIPTION
;
598 // ----------------------------------------------------------------------------
599 // error and debug output routines (deprecated, use wxLog)
600 // ----------------------------------------------------------------------------
602 void wxDebugMsg( const char *format
, ... )
605 va_start( ap
, format
);
606 vfprintf( stderr
, format
, ap
);
611 void wxError( const wxString
&msg
, const wxString
&title
)
613 wxFprintf( stderr
, _("Error ") );
614 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
615 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
616 wxFprintf( stderr
, wxT(".\n") );
619 void wxFatalError( const wxString
&msg
, const wxString
&title
)
621 wxFprintf( stderr
, _("Error ") );
622 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
623 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
624 wxFprintf( stderr
, wxT(".\n") );
625 exit(3); // the same exit code as for abort()