]>
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"
27 #include "wx/unix/execute.h"
33 #include <sys/types.h>
40 #include <fcntl.h> // for O_WRONLY and friends
41 #include <time.h> // nanosleep() and/or usleep()
42 #include <ctype.h> // isspace()
44 // JACS: needed for FD_SETSIZE
48 #include <sys/utsname.h> // for uname()
51 // ----------------------------------------------------------------------------
52 // conditional compilation
53 // ----------------------------------------------------------------------------
55 // many versions of Unices have this function, but it is not defined in system
56 // headers - please add your system here if it is the case for your OS.
57 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
58 #if !defined(HAVE_USLEEP) && \
59 (defined(__SUN__) && !defined(__SunOs_5_6) && \
60 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
61 defined(__osf__) || defined(__EMX__)
65 int usleep(unsigned int usec
);
68 /* I copied this from the XFree86 diffs. AV. */
69 #define INCL_DOSPROCESS
71 void usleep(unsigned long delay
)
73 DosSleep(delay
? (delay
/1000l) : 1l);
76 void usleep(unsigned long usec
);
78 #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
)
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 #else // !sleep function
116 #error "usleep() or nanosleep() function required for wxUsleep"
117 #endif // sleep function
120 // ----------------------------------------------------------------------------
121 // process management
122 // ----------------------------------------------------------------------------
124 int wxKill(long pid
, wxSignal sig
)
126 return kill(pid
, (int)sig
);
129 #define WXEXECUTE_NARGS 127
131 long wxExecute( const wxString
& command
, bool sync
, wxProcess
*process
)
133 wxCHECK_MSG( !command
.IsEmpty(), 0, wxT("can't exec empty command") );
136 wxChar
*argv
[WXEXECUTE_NARGS
];
138 const wxChar
*cptr
= command
.c_str();
139 wxChar quotechar
= wxT('\0'); // is arg quoted?
140 bool escaped
= FALSE
;
142 // split the command line in arguments
146 quotechar
= wxT('\0');
148 // eat leading whitespace:
149 while ( wxIsspace(*cptr
) )
152 if ( *cptr
== wxT('\'') || *cptr
== wxT('"') )
157 if ( *cptr
== wxT('\\') && ! escaped
)
164 // all other characters:
168 // have we reached the end of the argument?
169 if ( (*cptr
== quotechar
&& ! escaped
)
170 || (quotechar
== wxT('\0') && wxIsspace(*cptr
))
171 || *cptr
== wxT('\0') )
173 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
174 wxT("too many arguments in wxExecute") );
176 argv
[argc
] = new wxChar
[argument
.length() + 1];
177 wxStrcpy(argv
[argc
], argument
.c_str());
180 // if not at end of buffer, swallow last character:
184 break; // done with this one, start over
190 // do execute the command
191 long lRc
= wxExecute(argv
, sync
, process
);
196 delete [] argv
[argc
++];
201 bool wxShell(const wxString
& command
)
205 cmd
.Printf(wxT("xterm -e %s"), command
.c_str());
209 return wxExecute(cmd
) != 0;
212 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
214 int pid
= (proc_data
->pid
> 0) ? proc_data
->pid
: -(proc_data
->pid
);
216 // waitpid is POSIX so should be available everywhere, however on older
217 // systems wait() might be used instead in a loop (until the right pid
223 rc
= waitpid(pid
, &status
, 0);
224 while(rc
== -1 && ( /* errno == ERESTARTSYS || */ errno
== EINTR
) );
225 // waitpid() was interrupted, try again
228 if( rc
== -1 || ! (WIFEXITED(status
) || WIFSIGNALED(status
)) )
230 wxLogSysError(_("Waiting for subprocess termination failed"));
231 /* AFAIK, this can only happen if something went wrong within
232 wxGTK, i.e. due to a racecondition or some serious bug.
233 After having fixed the order of statements in
234 GTK_EndProcessDetector(). (KB)
239 // notify user about termination if required
240 if (proc_data
->process
)
242 proc_data
->process
->OnTerminate(proc_data
->pid
,
243 WEXITSTATUS(status
));
246 if ( proc_data
->pid
> 0 )
252 // wxExecute() will know about it
253 proc_data
->exitcode
= status
;
260 long wxExecute( wxChar
**argv
, bool sync
, wxProcess
*process
)
262 wxCHECK_MSG( *argv
, 0, wxT("can't exec empty command") );
266 char *mb_argv
[WXEXECUTE_NARGS
];
268 while (argv
[mb_argc
])
270 wxWX2MBbuf mb_arg
= wxConvertWX2MB(argv
[mb_argc
]);
271 mb_argv
[mb_argc
] = strdup(mb_arg
);
274 mb_argv
[mb_argc
] = (char *) NULL
;
276 // this macro will free memory we used above
277 #define ARGS_CLEANUP \
278 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
279 free(mb_argv[mb_argc])
281 // no need for cleanup
284 wxChar
**mb_argv
= argv
;
285 #endif // Unicode/ANSI
289 int end_proc_detect
[2];
290 if (pipe(end_proc_detect
) == -1)
292 wxLogSysError( _("Pipe creation failed") );
308 wxLogSysError( _("Fork failed") );
318 close(end_proc_detect
[0]); // close reading side
321 // These three lines close the open file descriptors to to avoid any
322 // input/output which might block the process or irritate the user. If
323 // one wants proper IO for the subprocess, the right thing to do is
324 // to start an xterm executing it.
327 // leave stderr opened, it won't do any hurm
328 for ( int fd
= 0; fd
< FD_SETSIZE
; fd
++ )
331 if ( fd
== end_proc_detect
[1] )
335 if ( fd
!= STDERR_FILENO
)
341 close(STDERR_FILENO
);
343 // some programs complain about stderr not being open, so redirect
345 open("/dev/null", O_RDONLY
); // stdin
346 open("/dev/null", O_WRONLY
); // stdout
347 open("/dev/null", O_WRONLY
); // stderr
350 execvp (*mb_argv
, mb_argv
);
352 // there is no return after successful exec()
353 wxFprintf(stderr
, _("Can't execute '%s'\n"), *argv
);
360 wxEndProcessData
*data
= new wxEndProcessData
;
367 wxASSERT_MSG( !process
, wxT("wxProcess param ignored for sync exec") );
368 data
->process
= NULL
;
370 // sync execution: indicate it by negating the pid
372 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
374 close(end_proc_detect
[1]); // close writing side
376 // it will be set to 0 from GTK_EndProcessDetector
377 while (data
->pid
!= 0)
380 int exitcode
= data
->exitcode
;
388 // async execution, nothing special to do - caller will be
389 // notified about the process termination if process != NULL, data
390 // will be deleted in GTK_EndProcessDetector
391 data
->process
= process
;
393 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
395 close(end_proc_detect
[1]); // close writing side
400 wxASSERT_MSG( sync
, wxT("async execution not supported yet") );
403 if ( waitpid(pid
, &exitcode
, 0) == -1 || !WIFEXITED(exitcode
) )
405 wxLogSysError(_("Waiting for subprocess termination failed"));
416 // ----------------------------------------------------------------------------
417 // file and directory functions
418 // ----------------------------------------------------------------------------
420 const wxChar
* wxGetHomeDir( wxString
*home
)
422 *home
= wxGetUserHome( wxString() );
423 if ( home
->IsEmpty() )
426 return home
->c_str();
430 const wxMB2WXbuf
wxGetUserHome( const wxString
&user
)
431 #else // just for binary compatibility -- there is no 'const' here
432 char *wxGetUserHome( const wxString
&user
)
435 struct passwd
*who
= (struct passwd
*) NULL
;
441 if ((ptr
= wxGetenv(wxT("HOME"))) != NULL
)
445 if ((ptr
= wxGetenv(wxT("USER"))) != NULL
|| (ptr
= wxGetenv(wxT("LOGNAME"))) != NULL
)
447 who
= getpwnam(wxConvertWX2MB(ptr
));
450 // We now make sure the the user exists!
453 who
= getpwuid(getuid());
458 who
= getpwnam (user
.mb_str());
461 return wxConvertMB2WX(who
? who
->pw_dir
: 0);
464 // ----------------------------------------------------------------------------
465 // network and user id routines
466 // ----------------------------------------------------------------------------
468 // retrieve either the hostname or FQDN depending on platform (caller must
469 // check whether it's one or the other, this is why this function is for
471 static bool wxGetHostNameInternal(wxChar
*buf
, int sz
)
473 wxCHECK_MSG( buf
, FALSE
, wxT("NULL pointer in wxGetHostNameInternal") );
477 // we're using uname() which is POSIX instead of less standard sysinfo()
478 #if defined(HAVE_UNAME)
480 bool ok
= uname(&uts
) != -1;
483 wxStrncpy(buf
, wxConvertMB2WX(uts
.nodename
), sz
- 1);
486 #elif defined(HAVE_GETHOSTNAME)
487 bool ok
= gethostname(buf
, sz
) != -1;
488 #else // no uname, no gethostname
489 wxFAIL_MSG(wxT("don't know host name for this machine"));
492 #endif // uname/gethostname
496 wxLogSysError(_("Cannot get the hostname"));
502 bool wxGetHostName(wxChar
*buf
, int sz
)
504 bool ok
= wxGetHostNameInternal(buf
, sz
);
508 // BSD systems return the FQDN, we only want the hostname, so extract
509 // it (we consider that dots are domain separators)
510 wxChar
*dot
= wxStrchr(buf
, wxT('.'));
521 bool wxGetFullHostName(wxChar
*buf
, int sz
)
523 bool ok
= wxGetHostNameInternal(buf
, sz
);
527 if ( !wxStrchr(buf
, wxT('.')) )
529 struct hostent
*host
= gethostbyname(wxConvertWX2MB(buf
));
532 wxLogSysError(_("Cannot get the official hostname"));
538 // the canonical name
539 wxStrncpy(buf
, wxConvertMB2WX(host
->h_name
), sz
);
542 //else: it's already a FQDN (BSD behaves this way)
548 bool wxGetUserId(wxChar
*buf
, int sz
)
553 if ((who
= getpwuid(getuid ())) != NULL
)
555 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
562 bool wxGetUserName(wxChar
*buf
, int sz
)
568 if ((who
= getpwuid (getuid ())) != NULL
) {
570 comma
= strchr(who
->pw_gecos
, ',');
572 *comma
= '\0'; // cut off non-name comment fields
573 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_gecos
), sz
- 1);
575 wxStrncpy (buf
, wxConvertMB2WX(who
->pw_name
), sz
- 1);
583 // ----------------------------------------------------------------------------
584 // error and debug output routines (deprecated, use wxLog)
585 // ----------------------------------------------------------------------------
587 void wxDebugMsg( const char *format
, ... )
590 va_start( ap
, format
);
591 vfprintf( stderr
, format
, ap
);
596 void wxError( const wxString
&msg
, const wxString
&title
)
598 wxFprintf( stderr
, _("Error ") );
599 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
600 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
601 wxFprintf( stderr
, wxT(".\n") );
604 void wxFatalError( const wxString
&msg
, const wxString
&title
)
606 wxFprintf( stderr
, _("Error ") );
607 if (!title
.IsNull()) wxFprintf( stderr
, wxT("%s "), WXSTRINGCAST(title
) );
608 if (!msg
.IsNull()) wxFprintf( stderr
, wxT(": %s"), WXSTRINGCAST(msg
) );
609 wxFprintf( stderr
, wxT(".\n") );
610 exit(3); // the same exit code as for abort()