]>
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 #include <sys/utsname.h> // for uname()
47 // ----------------------------------------------------------------------------
48 // conditional compilation
49 // ----------------------------------------------------------------------------
51 // many versions of Unices have this function, but it is not defined in system
52 // headers - please add your system here if it is the case for your OS.
53 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
54 #if !defined(HAVE_USLEEP) && \
55 (defined(__SUN__) && !defined(__SunOs_5_6) && \
56 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
61 int usleep(unsigned int usec
);
63 void usleep(unsigned long usec
);
66 #endif // Unices without usleep()
68 // many versions of Unices have this function, but it is not defined in system
69 // headers - please add your system here if it is the case for your OS.
70 // SunOS (and Solaris) and DG-UX are like this.
71 #if defined(__SOLARIS__) || defined(__osf__)
74 pid_t
wait4(pid_t pid
, int *statusp
, int options
,
75 struct rusage
*rusage
);
78 #define wxWait4(pid, stat, flags, rusage) wait4(pid, stat, flags, rusage)
79 #elif defined(__sgi) || defined(__HPUX__)
80 // no wait4() at all on these systems
81 // TODO verify whether wait3() really works in this situation
82 #define wxWait4(pid, stat, flags, rusage) wait3(stat, flags, rusage)
84 // other Unices: assume have wait4(), although it's not standard (but
85 // Linux and FreeBSD do have it)
86 #define wxWait4(pid, stat, flags, rusage) wait4(pid, stat, flags, rusage)
89 // ============================================================================
91 // ============================================================================
93 // ----------------------------------------------------------------------------
95 // ----------------------------------------------------------------------------
97 void wxSleep(int nSecs
)
102 void wxUsleep(unsigned long milliseconds
)
104 #if defined(HAVE_NANOSLEEP)
106 tmReq
.tv_sec
= milliseconds
/ 1000;
107 tmReq
.tv_nsec
= (milliseconds
% 1000) * 1000 * 1000;
109 // we're not interested in remaining time nor in return value
110 (void)nanosleep(&tmReq
, (timespec
*)NULL
);
111 #elif defined(HAVE_USLEEP)
112 // uncomment this if you feel brave or if you are sure that your version
113 // of Solaris has a safe usleep() function but please notice that usleep()
114 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
115 // documented as MT-Safe
116 #if defined(__SUN__) && defined(wxUSE_THREADS)
117 #error "usleep() cannot be used in MT programs under Solaris."
120 usleep(milliseconds
* 1000); // usleep(3) wants microseconds
121 #else // !sleep function
122 #error "usleep() or nanosleep() function required for wxUsleep"
123 #endif // sleep function
126 // ----------------------------------------------------------------------------
127 // process management
128 // ----------------------------------------------------------------------------
130 int wxKill(long pid
, int sig
)
132 return kill(pid
, sig
);
135 #define WXEXECUTE_NARGS 127
137 long wxExecute( const wxString
& command
, bool sync
, wxProcess
*process
)
139 wxCHECK_MSG( !command
.IsEmpty(), 0, "can't exec empty command" );
142 char *argv
[WXEXECUTE_NARGS
];
144 const char *cptr
= command
.c_str();
145 char quotechar
= '\0'; // is arg quoted?
146 bool escaped
= FALSE
;
152 // eat leading whitespace:
153 while(*cptr
&& isspace(*cptr
))
155 if(*cptr
== '\'' || *cptr
== '"')
159 if(*cptr
== '\\' && ! escaped
)
165 // all other characters:
166 argument
+= *cptr
++;
168 // Have we reached the end of the argument?
169 if((*cptr
== quotechar
&& ! escaped
)
170 || (quotechar
== '\0' && isspace(*cptr
))
173 wxASSERT(argc
< WXEXECUTE_NARGS
);
174 argv
[argc
] = new char[argument
.Len()+1];
175 strcpy(argv
[argc
], argument
.c_str());
177 // if not at end of buffer, swallow last character:
179 break; // done with this one, start over
185 long lRc
= wxExecute(argv
, sync
, process
);
189 delete [] argv
[argc
++];
194 bool wxShell(const wxString
& command
)
198 cmd
.Printf("xterm -e %s", command
.c_str());
202 return wxExecute(cmd
) != 0;
205 void wxHandleProcessTermination(wxEndProcessData
*proc_data
)
207 int pid
= (proc_data
->pid
> 0) ? proc_data
->pid
: -(proc_data
->pid
);
210 wxWait4(pid
, &status
, 0, (rusage
*) NULL
);
212 if (proc_data
->process
)
213 proc_data
->process
->OnTerminate(proc_data
->pid
, status
);
215 if (proc_data
->pid
> 0)
221 // wxExecute() will know about it
222 proc_data
->exitcode
= status
;
228 long wxExecute( char **argv
, bool sync
, wxProcess
*process
)
230 wxCHECK_MSG( *argv
, 0, "can't exec empty command" );
232 int end_proc_detect
[2];
235 if (pipe(end_proc_detect
) == -1)
237 wxLogSysError( _("Pipe creation failed") );
249 wxLogSysError( _("Fork failed") );
255 close(end_proc_detect
[0]); // close reading side
257 // These three lines close the open file descriptors to to avoid any
258 // input/output which might block the process or irritate the user. If
259 // one wants proper IO for the subprocess, the "right thing to do is
260 // to start an xterm executing it.
263 // leave stderr opened, it won't do any hurm
264 for ( int fd
= 0; fd
< FD_SETSIZE
; fd
++ )
266 if ( fd
!= end_proc_detect
[1] && fd
!= STDERR_FILENO
)
272 close(STDERR_FILENO
);
274 // some programs complain about stderr not being open, so redirect
276 open("/dev/null", O_RDONLY
); // stdin
277 open("/dev/null", O_WRONLY
); // stdout
278 open("/dev/null", O_WRONLY
); // stderr
282 execvp ((const char *)*argv
, (const char **)argv
);
284 execvp (*argv
, argv
);
287 // there is no return after successful exec()
288 fprintf(stderr
, _("Can't execute '%s'\n"), *argv
);
295 close(end_proc_detect
[1]); // close writing side
297 wxEndProcessData
*data
= new wxEndProcessData
;
298 data
->tag
= wxAddProcessCallback(data
, end_proc_detect
[0]);
302 wxASSERT_MSG( !process
, "wxProcess param ignored for sync exec" );
303 data
->process
= NULL
;
305 // sync execution: indicate it by negating the pid
308 // it will be set to 0 from GTK_EndProcessDetector
309 while (data
->pid
!= 0)
312 int exitcode
= data
->exitcode
;
320 // async execution, nothing special to do - caller will be
321 // notified about the process terminationif process != NULL, data
322 // will be deleted in GTK_EndProcessDetector
323 data
->process
= process
;
331 // ----------------------------------------------------------------------------
332 // file and directory functions
333 // ----------------------------------------------------------------------------
335 const char* wxGetHomeDir( wxString
*home
)
337 *home
= wxGetUserHome( wxString() );
338 if ( home
->IsEmpty() )
341 return home
->c_str();
344 char *wxGetUserHome( const wxString
&user
)
346 struct passwd
*who
= (struct passwd
*) NULL
;
348 if (user
.IsNull() || (user
== ""))
352 if ((ptr
= getenv("HOME")) != NULL
)
356 if ((ptr
= getenv("USER")) != NULL
|| (ptr
= getenv("LOGNAME")) != NULL
)
361 // We now make sure the the user exists!
364 who
= getpwuid(getuid());
369 who
= getpwnam (user
);
372 return who
? who
->pw_dir
: (char*)NULL
;
375 // ----------------------------------------------------------------------------
377 // ----------------------------------------------------------------------------
379 bool wxGetHostName(char *buf
, int sz
)
381 wxCHECK_MSG( buf
, FALSE
, "NULL pointer in wxGetHostName" );
385 // we're using uname() which is POSIX instead of less standard sysinfo()
386 #if defined(HAVE_UNAME)
388 bool ok
= uname(&uts
) != -1;
391 strncpy(buf
, uts
.nodename
, sz
- 1);
394 #elif defined(HAVE_GETHOSTNAME)
395 bool ok
= gethostname(buf
, sz
) != -1;
397 wxFAIL_MSG("don't know host name for this machibe");
404 wxLogSysError(_("Cannot get the hostname"));
410 bool wxGetUserId(char *buf
, int sz
)
415 if ((who
= getpwuid(getuid ())) != NULL
)
417 strncpy (buf
, who
->pw_name
, sz
- 1);
424 bool wxGetUserName(char *buf
, int sz
)
430 if ((who
= getpwuid (getuid ())) != NULL
) {
431 comma
= strchr(who
->pw_gecos
, ',');
433 *comma
= '\0'; // cut off non-name comment fields
434 strncpy (buf
, who
->pw_gecos
, sz
- 1);
441 // ----------------------------------------------------------------------------
442 // error and debug output routines (deprecated, use wxLog)
443 // ----------------------------------------------------------------------------
445 void wxDebugMsg( const char *format
, ... )
448 va_start( ap
, format
);
449 vfprintf( stderr
, format
, ap
);
454 void wxError( const wxString
&msg
, const wxString
&title
)
456 fprintf( stderr
, _("Error ") );
457 if (!title
.IsNull()) fprintf( stderr
, "%s ", WXSTRINGCAST(title
) );
458 if (!msg
.IsNull()) fprintf( stderr
, ": %s", WXSTRINGCAST(msg
) );
459 fprintf( stderr
, ".\n" );
462 void wxFatalError( const wxString
&msg
, const wxString
&title
)
464 fprintf( stderr
, _("Error ") );
465 if (!title
.IsNull()) fprintf( stderr
, "%s ", WXSTRINGCAST(title
) );
466 if (!msg
.IsNull()) fprintf( stderr
, ": %s", WXSTRINGCAST(msg
) );
467 fprintf( stderr
, ".\n" );
468 exit(3); // the same exit code as for abort()
471 //------------------------------------------------------------------------
472 // directory routines
473 //------------------------------------------------------------------------
475 bool wxDirExists( const wxString
& dir
)
478 strcpy( buf
, WXSTRINGCAST(dir
) );
480 return ((stat(buf
, &sbuf
) != -1) && S_ISDIR(sbuf
.st_mode
) ? TRUE
: FALSE
);