]>
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()
45 // JACS: needed for FD_SETSIZE
49 #include <sys/utsname.h> // for uname()
52 // ----------------------------------------------------------------------------
53 // conditional compilation
54 // ----------------------------------------------------------------------------
56 // many versions of Unices have this function, but it is not defined in system
57 // headers - please add your system here if it is the case for your OS.
58 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
59 #if !defined(HAVE_USLEEP) && \
60 (defined(__SUN__) && !defined(__SunOs_5_6) && \
61 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
62 defined(__osf__) || defined(__EMX__)
66 int usleep(unsigned int usec
);
69 /* I copied this from the XFree86 diffs. AV. */
70 #define INCL_DOSPROCESS
72 inline void usleep(unsigned long delay
)
74 DosSleep(delay
? (delay
/1000l) : 1l);
77 void usleep(unsigned long usec
);
79 #endif // Sun/EMX/Something else
83 #endif // Unices without usleep()
85 // ============================================================================
87 // ============================================================================
89 // ----------------------------------------------------------------------------
91 // ----------------------------------------------------------------------------
93 void wxSleep(int nSecs
)
98 void wxUsleep(unsigned long milliseconds
)
100 #ifdef HAVE_NANOSLEEP
102 tmReq
.tv_sec
= milliseconds
/ 1000;
103 tmReq
.tv_nsec
= (milliseconds
% 1000) * 1000 * 1000;
105 // we're not interested in remaining time nor in return value
106 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
107 #elif defined( HAVE_USLEEP )
108 // uncomment this if you feel brave or if you are sure that your version
109 // of Solaris has a safe usleep() function but please notice that usleep()
110 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
111 // documented as MT-Safe
112 #if defined(__SUN__) && wxUSE_THREADS
113 #error "usleep() cannot be used in MT programs under Solaris."
116 usleep(milliseconds
* 1000); // usleep(3) wants microseconds
117 #else // !sleep function
118 #error "usleep() or nanosleep() function required for wxUsleep"
119 #endif // sleep function
122 // ----------------------------------------------------------------------------
123 // process management
124 // ----------------------------------------------------------------------------
126 int wxKill(long pid
, wxSignal sig
)
128 return kill(pid
, (int)sig
);
131 #define WXEXECUTE_NARGS 127
133 long wxExecute( const wxString
& command
, bool sync
, wxProcess
*process
)
135 wxCHECK_MSG( !command
.IsEmpty(), 0, wxT("can't exec empty command") );
138 wxChar
*argv
[WXEXECUTE_NARGS
];
140 const wxChar
*cptr
= command
.c_str();
141 wxChar quotechar
= wxT('\0'); // is arg quoted?
142 bool escaped
= FALSE
;
144 // split the command line in arguments
148 quotechar
= wxT('\0');
150 // eat leading whitespace:
151 while ( wxIsspace(*cptr
) )
154 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
159 if ( *cptr
== wxT('\\') && ! escaped
)
166 // all other characters:
170 // have we reached the end of the argument?
171 if ( (*cptr
== quotechar
&& ! escaped
)
172 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
173 || *cptr
== wxT('\0') )
175 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
176 wxT("too many arguments in wxExecute") );
178 argv
[argc
] = new wxChar
[argument
.length() + 1];
179 wxStrcpy(argv
[argc
], argument
.c_str());
182 // if not at end of buffer, swallow last character:
186 break; // done with this one, start over
192 // do execute the command
193 long lRc
= wxExecute(argv
, sync
, process
);
198 delete [] argv
[argc
++];
203 bool wxShell(const wxString
& command
)
207 cmd
.Printf(wxT("xterm -e %s"), command
.c_str());
211 return wxExecute(cmd
) != 0;
214 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
216 int pid
= (proc_data
->pid
> 0) ? proc_data
->pid
: -(proc_data
->pid
);
218 // waitpid is POSIX so should be available everywhere, however on older
219 // systems wait() might be used instead in a loop (until the right pid
224 // wait for child termination and if waitpid() was interrupted, try again
227 rc
= waitpid(pid
, &status
, 0);
229 while ( rc
== -1 && errno
== EINTR
);
232 if( rc
== -1 || ! (WIFEXITED(status
) || WIFSIGNALED(status
)) )
234 wxLogSysError(_("Waiting for subprocess termination failed"));
235 /* AFAIK, this can only happen if something went wrong within
236 wxGTK, i.e. due to a race condition or some serious bug.
237 After having fixed the order of statements in
238 GTK_EndProcessDetector(). (KB)
243 // notify user about termination if required
244 if (proc_data
->process
)
246 proc_data
->process
->OnTerminate(proc_data
->pid
,
247 WEXITSTATUS(status
));
250 if ( proc_data
->pid
> 0 )
256 // wxExecute() will know about it
257 proc_data
->exitcode
= status
;
264 long wxExecute( wxChar
**argv
, bool sync
, wxProcess
*process
)
266 wxCHECK_MSG( *argv
, 0, wxT("can't exec empty command") );
270 char *mb_argv
[WXEXECUTE_NARGS
];
272 while (argv
[mb_argc
])
274 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
275 mb_argv
[mb_argc
] = strdup(mb_arg
);
278 mb_argv
[mb_argc
] = (char *) NULL
;
280 // this macro will free memory we used above
281 #define ARGS_CLEANUP \
282 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
283 free(mb_argv[mb_argc])
285 // no need for cleanup
288 wxChar
**mb_argv
= argv
;
289 #endif // Unicode/ANSI
293 int end_proc_detect
[2];
294 if (pipe(end_proc_detect
) == -1)
296 wxLogSysError( _("Pipe creation failed") );
312 wxLogSysError( _("Fork failed") );
322 close(end_proc_detect
[0]); // close reading side
325 // These three lines close the open file descriptors to to avoid any
326 // input/output which might block the process or irritate the user. If
327 // one wants proper IO for the subprocess, the right thing to do is
328 // to start an xterm executing it.
331 // leave stderr opened, it won't do any hurm
332 for ( int fd
= 0; fd
< FD_SETSIZE
; fd
++ )
335 if ( fd
== end_proc_detect
[1] )
339 if ( fd
!= STDERR_FILENO
)
345 close(STDERR_FILENO
);
347 // some programs complain about stderr not being open, so redirect
349 open("/dev/null", O_RDONLY
); // stdin
350 open("/dev/null", O_WRONLY
); // stdout
351 open("/dev/null", O_WRONLY
); // stderr
354 execvp (*mb_argv
, mb_argv
);
356 // there is no return after successful exec()
357 wxFprintf(stderr
, _("Can't execute '%s'\n"), *argv
);
364 wxEndProcessData
*data
= new wxEndProcessData
;
371 wxASSERT_MSG( !process
, wxT("wxProcess param ignored for sync exec") );
372 data
->process
= NULL
;
374 // sync execution: indicate it by negating the pid
376 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
378 close(end_proc_detect
[1]); // close writing side
380 // it will be set to 0 from GTK_EndProcessDetector
381 while (data
->pid
!= 0)
384 int exitcode
= data
->exitcode
;
392 // async execution, nothing special to do - caller will be
393 // notified about the process termination if process != NULL, data
394 // will be deleted in GTK_EndProcessDetector
395 data
->process
= process
;
397 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
399 close(end_proc_detect
[1]); // close writing side
404 wxASSERT_MSG( sync
, wxT("async execution not supported yet") );
407 if ( waitpid(pid
, &exitcode
, 0) == -1 || !WIFEXITED(exitcode
) )
409 wxLogSysError(_("Waiting for subprocess termination failed"));
420 // ----------------------------------------------------------------------------
421 // file and directory functions
422 // ----------------------------------------------------------------------------
424 const wxChar
* wxGetHomeDir( wxString
*home
)
426 *home
= wxGetUserHome( wxString() );
427 if ( home
->IsEmpty() )
430 return home
->c_str();
434 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
435 #else // just for binary compatibility -- there is no 'const' here
436 char *wxGetUserHome( const wxString
&user
)
439 struct passwd
*who
= (struct passwd
*) NULL
;
445 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
449 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
451 who
= getpwnam(wxConvertWX2MB(ptr
));
454 // We now make sure the the user exists!
457 who
= getpwuid(getuid());
462 who
= getpwnam (user
.mb_str());
465 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
468 // ----------------------------------------------------------------------------
469 // network and user id routines
470 // ----------------------------------------------------------------------------
472 // retrieve either the hostname or FQDN depending on platform (caller must
473 // check whether it's one or the other, this is why this function is for
475 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
477 wxCHECK_MSG( buf
, FALSE
, wxT("NULL pointer in wxGetHostNameInternal") );
481 // we're using uname() which is POSIX instead of less standard sysinfo()
482 #if defined(HAVE_UNAME)
484 bool ok
= uname(&uts
) != -1;
487 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
490 #elif defined(HAVE_GETHOSTNAME)
491 bool ok
= gethostname(buf
, sz
) != -1;
492 #else // no uname, no gethostname
493 wxFAIL_MSG(wxT("don't know host name for this machine"));
496 #endif // uname/gethostname
500 wxLogSysError(_("Cannot get the hostname"));
506 bool wxGetHostName(wxChar
*buf
, int sz
)
508 bool ok
= wxGetHostNameInternal(buf
, sz
);
512 // BSD systems return the FQDN, we only want the hostname, so extract
513 // it (we consider that dots are domain separators)
514 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
525 bool wxGetFullHostName(wxChar
*buf
, int sz
)
527 bool ok
= wxGetHostNameInternal(buf
, sz
);
531 if ( !wxStrchr(buf
, wxT('.')) )
533 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
536 wxLogSysError(_("Cannot get the official hostname"));
542 // the canonical name
543 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
546 //else: it's already a FQDN (BSD behaves this way)
552 bool wxGetUserId(wxChar
*buf
, int sz
)
557 if ((who
= getpwuid(getuid ())) != NULL
)
559 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
566 bool wxGetUserName(wxChar
*buf
, int sz
)
572 if ((who
= getpwuid (getuid ())) != NULL
) {
574 comma
= strchr(who
->pw_gecos
, ',');
576 *comma
= '\0'; // cut off non-name comment fields
577 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
579 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
587 wxString
wxGetOsDescription()
589 #ifndef WXWIN_OS_DESCRIPTION
590 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
592 return WXWIN_OS_DESCRIPTION
;
596 // ----------------------------------------------------------------------------
597 // error and debug output routines (deprecated, use wxLog)
598 // ----------------------------------------------------------------------------
600 void wxDebugMsg( const char *format
, ... )
603 va_start( ap
, format
);
604 vfprintf( stderr
, format
, ap
);
609 void wxError( const wxString
&msg
, const wxString
&title
)
611 wxFprintf( stderr
, _("Error ") );
612 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
613 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
614 wxFprintf( stderr
, wxT(".\n") );
617 void wxFatalError( const wxString
&msg
, const wxString
&title
)
619 wxFprintf( stderr
, _("Error ") );
620 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
621 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
622 wxFprintf( stderr
, wxT(".\n") );
623 exit(3); // the same exit code as for abort()