]>
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)) || \
65 int usleep(unsigned int usec
);
67 void usleep(unsigned long usec
);
70 #endif // Unices without usleep()
72 // ============================================================================
74 // ============================================================================
76 // ----------------------------------------------------------------------------
78 // ----------------------------------------------------------------------------
80 void wxSleep(int nSecs
)
85 void wxUsleep(unsigned long milliseconds
)
89 tmReq
.tv_sec
= milliseconds
/ 1000;
90 tmReq
.tv_nsec
= (milliseconds
% 1000) * 1000 * 1000;
92 // we're not interested in remaining time nor in return value
93 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
95 // uncomment this if you feel brave or if you are sure that your version
96 // of Solaris has a safe usleep() function but please notice that usleep()
97 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
98 // documented as MT-Safe
99 #if defined(__SUN__) && wxUSE_THREADS
100 #error "usleep() cannot be used in MT programs under Solaris."
103 usleep(milliseconds
* 1000); // usleep(3) wants microseconds
104 #else // !sleep function
105 #error "usleep() or nanosleep() function required for wxUsleep"
106 #endif // sleep function
109 // ----------------------------------------------------------------------------
110 // process management
111 // ----------------------------------------------------------------------------
113 int wxKill(long pid
, wxSignal sig
)
115 return kill(pid
, (int)sig
);
118 #define WXEXECUTE_NARGS 127
120 long wxExecute( const wxString
& command
, bool sync
, wxProcess
*process
)
122 wxCHECK_MSG( !command
.IsEmpty(), 0, "can't exec empty command" );
125 char *argv
[WXEXECUTE_NARGS
];
127 const char *cptr
= command
.c_str();
128 char quotechar
= '\0'; // is arg quoted?
129 bool escaped
= FALSE
;
131 // split the command line in arguments
137 // eat leading whitespace:
138 while ( isspace(*cptr
) )
141 if ( *cptr
== '\'' || *cptr
== '"' )
146 if ( *cptr
== '\\' && ! escaped
)
153 // all other characters:
157 // have we reached the end of the argument?
158 if ( (*cptr
== quotechar
&& ! escaped
)
159 || (quotechar
== '\0' && isspace(*cptr
))
162 wxASSERT_MSG( argc
< WXEXECUTE_NARGS
,
163 "too many arguments in wxExecute" );
165 argv
[argc
] = new char[argument
.length() + 1];
166 strcpy(argv
[argc
], argument
.c_str());
169 // if not at end of buffer, swallow last character:
173 break; // done with this one, start over
179 // do execute the command
180 long lRc
= wxExecute(argv
, sync
, process
);
185 delete [] argv
[argc
++];
190 bool wxShell(const wxString
& command
)
194 cmd
.Printf("xterm -e %s", command
.c_str());
198 return wxExecute(cmd
) != 0;
201 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
203 int pid
= (proc_data
->pid
> 0) ? proc_data
->pid
: -(proc_data
->pid
);
205 // waitpid is POSIX so should be available everywhere, however on older
206 // systems wait() might be used instead in a loop (until the right pid
209 if ( waitpid(pid
, &status
, 0) == -1 || !WIFEXITED(status
) )
211 wxLogSysError(_("Waiting for subprocess termination failed"));
215 // notify user about termination if required
216 if (proc_data
->process
)
218 proc_data
->process
->OnTerminate(proc_data
->pid
,
219 WEXITSTATUS(status
));
224 if ( proc_data
->pid
> 0 )
230 // wxExecute() will know about it
231 proc_data
->exitcode
= status
;
237 long wxExecute( char **argv
, bool sync
, wxProcess
*process
)
239 wxCHECK_MSG( *argv
, 0, "can't exec empty command" );
241 int end_proc_detect
[2];
244 if (pipe(end_proc_detect
) == -1)
246 wxLogSysError( _("Pipe creation failed") );
258 wxLogSysError( _("Fork failed") );
264 close(end_proc_detect
[0]); // close reading side
266 // These three lines close the open file descriptors to to avoid any
267 // input/output which might block the process or irritate the user. If
268 // one wants proper IO for the subprocess, the right thing to do is
269 // to start an xterm executing it.
272 // leave stderr opened, it won't do any hurm
273 for ( int fd
= 0; fd
< FD_SETSIZE
; fd
++ )
275 if ( fd
!= end_proc_detect
[1] && fd
!= STDERR_FILENO
)
281 close(STDERR_FILENO
);
283 // some programs complain about stderr not being open, so redirect
285 open("/dev/null", O_RDONLY
); // stdin
286 open("/dev/null", O_WRONLY
); // stdout
287 open("/dev/null", O_WRONLY
); // stderr
290 execvp (*argv
, argv
);
292 // there is no return after successful exec()
293 fprintf(stderr
, _("Can't execute '%s'\n"), *argv
);
300 close(end_proc_detect
[1]); // close writing side
302 wxEndProcessData
*data
= new wxEndProcessData
;
303 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
307 wxASSERT_MSG( !process
, "wxProcess param ignored for sync exec" );
308 data
->process
= NULL
;
310 // sync execution: indicate it by negating the pid
313 // it will be set to 0 from GTK_EndProcessDetector
314 while (data
->pid
!= 0)
317 int exitcode
= data
->exitcode
;
325 // async execution, nothing special to do - caller will be
326 // notified about the process terminationif process != NULL, data
327 // will be deleted in GTK_EndProcessDetector
328 data
->process
= process
;
336 // ----------------------------------------------------------------------------
337 // file and directory functions
338 // ----------------------------------------------------------------------------
340 const char* wxGetHomeDir( wxString
*home
)
342 *home
= wxGetUserHome( wxString() );
343 if ( home
->IsEmpty() )
346 return home
->c_str();
349 char *wxGetUserHome( const wxString
&user
)
351 struct passwd
*who
= (struct passwd
*) NULL
;
357 if ((ptr
= getenv("HOME")) != NULL
)
361 if ((ptr
= getenv("USER")) != NULL
|| (ptr
= getenv("LOGNAME")) != NULL
)
366 // We now make sure the the user exists!
369 who
= getpwuid(getuid());
374 who
= getpwnam (user
);
377 return who
? who
->pw_dir
: (char*)NULL
;
380 // ----------------------------------------------------------------------------
381 // network and user id routines
382 // ----------------------------------------------------------------------------
384 // retrieve either the hostname or FQDN depending on platform (caller must
385 // check whether it's one or the other, this is why this function is for
387 static bool wxGetHostNameInternal(char *buf
, int sz
)
389 wxCHECK_MSG( buf
, FALSE
, "NULL pointer in wxGetHostNameInternal" );
393 // we're using uname() which is POSIX instead of less standard sysinfo()
394 #if defined(HAVE_UNAME)
396 bool ok
= uname(&uts
) != -1;
399 strncpy(buf
, uts
.nodename
, sz
- 1);
402 #elif defined(HAVE_GETHOSTNAME)
403 bool ok
= gethostname(buf
, sz
) != -1;
404 #else // no uname, no gethostname
405 wxFAIL_MSG("don't know host name for this machibe");
408 #endif // uname/gethostname
412 wxLogSysError(_("Cannot get the hostname"));
418 bool wxGetHostName(char *buf
, int sz
)
420 bool ok
= wxGetHostNameInternal(buf
, sz
);
424 // BSD systems return the FQDN, we only want the hostname, so extract
425 // it (we consider that dots are domain separators)
426 char *dot
= strchr(buf
, '.');
437 bool wxGetFullHostName(char *buf
, int sz
)
439 bool ok
= wxGetHostNameInternal(buf
, sz
);
443 if ( !strchr(buf
, '.') )
445 struct hostent
*host
= gethostbyname(buf
);
448 wxLogSysError(_("Cannot get the official hostname"));
454 // the canonical name
455 strncpy(buf
, host
->h_name
, sz
);
458 //else: it's already a FQDN (BSD behaves this way)
464 bool wxGetUserId(char *buf
, int sz
)
469 if ((who
= getpwuid(getuid ())) != NULL
)
471 strncpy (buf
, who
->pw_name
, sz
- 1);
478 bool wxGetUserName(char *buf
, int sz
)
484 if ((who
= getpwuid (getuid ())) != NULL
) {
485 comma
= strchr(who
->pw_gecos
, ',');
487 *comma
= '\0'; // cut off non-name comment fields
488 strncpy (buf
, who
->pw_gecos
, sz
- 1);
495 // ----------------------------------------------------------------------------
496 // error and debug output routines (deprecated, use wxLog)
497 // ----------------------------------------------------------------------------
499 void wxDebugMsg( const char *format
, ... )
502 va_start( ap
, format
);
503 vfprintf( stderr
, format
, ap
);
508 void wxError( const wxString
&msg
, const wxString
&title
)
510 fprintf( stderr
, _("Error ") );
511 if (!title
.IsNull()) fprintf( stderr
, "%s ", WXSTRINGCAST(title
) );
512 if (!msg
.IsNull()) fprintf( stderr
, ": %s", WXSTRINGCAST(msg
) );
513 fprintf( stderr
, ".\n" );
516 void wxFatalError( const wxString
&msg
, const wxString
&title
)
518 fprintf( stderr
, _("Error ") );
519 if (!title
.IsNull()) fprintf( stderr
, "%s ", WXSTRINGCAST(title
) );
520 if (!msg
.IsNull()) fprintf( stderr
, ": %s", WXSTRINGCAST(msg
) );
521 fprintf( stderr
, ".\n" );
522 exit(3); // the same exit code as for abort()