gobject: Clean up logic in property checks
[glib.git] / glib / gspawn.c
blob388b654a6534317a2acbf65f3966b236675184c2
1 /* gspawn.c - Process launching
3 * Copyright 2000 Red Hat, Inc.
4 * g_execvpe implementation based on GNU libc execvp:
5 * Copyright 1991, 92, 95, 96, 97, 98, 99 Free Software Foundation, Inc.
7 * GLib is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2 of the
10 * License, or (at your option) any later version.
12 * GLib is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with GLib; see the file COPYING.LIB. If not, write
19 * to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
23 #include "config.h"
25 #include <sys/time.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <string.h>
33 #include <stdlib.h> /* for fdwalk */
34 #include <dirent.h>
36 #ifdef HAVE_SYS_SELECT_H
37 #include <sys/select.h>
38 #endif /* HAVE_SYS_SELECT_H */
40 #ifdef HAVE_SYS_RESOURCE_H
41 #include <sys/resource.h>
42 #endif /* HAVE_SYS_RESOURCE_H */
44 #include "gspawn.h"
46 #include "genviron.h"
47 #include "gmem.h"
48 #include "gshell.h"
49 #include "gstring.h"
50 #include "gstrfuncs.h"
51 #include "gtestutils.h"
52 #include "gutils.h"
53 #include "glibintl.h"
56 /**
57 * SECTION:spawn
58 * @Short_description: process launching
59 * @Title: Spawning Processes
64 static gint g_execute (const gchar *file,
65 gchar **argv,
66 gchar **envp,
67 gboolean search_path);
69 static gboolean make_pipe (gint p[2],
70 GError **error);
71 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
72 const gchar *working_directory,
73 gchar **argv,
74 gchar **envp,
75 gboolean close_descriptors,
76 gboolean search_path,
77 gboolean stdout_to_null,
78 gboolean stderr_to_null,
79 gboolean child_inherits_stdin,
80 gboolean file_and_argv_zero,
81 GSpawnChildSetupFunc child_setup,
82 gpointer user_data,
83 GPid *child_pid,
84 gint *standard_input,
85 gint *standard_output,
86 gint *standard_error,
87 GError **error);
89 GQuark
90 g_spawn_error_quark (void)
92 return g_quark_from_static_string ("g-exec-error-quark");
95 /**
96 * g_spawn_async:
97 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
98 * @argv: (array zero-terminated=1): child's argument vector
99 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
100 * @flags: flags from #GSpawnFlags
101 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
102 * @user_data: (closure): user data for @child_setup
103 * @child_pid: (out) (allow-none): return location for child process reference, or %NULL
104 * @error: return location for error
106 * See g_spawn_async_with_pipes() for a full description; this function
107 * simply calls the g_spawn_async_with_pipes() without any pipes.
109 * You should call g_spawn_close_pid() on the returned child process
110 * reference when you don't need it any more.
112 * <note><para>
113 * If you are writing a GTK+ application, and the program you
114 * are spawning is a graphical application, too, then you may
115 * want to use gdk_spawn_on_screen() instead to ensure that
116 * the spawned program opens its windows on the right screen.
117 * </para></note>
119 * <note><para> Note that the returned @child_pid on Windows is a
120 * handle to the child process and not its identifier. Process handles
121 * and process identifiers are different concepts on Windows.
122 * </para></note>
124 * Return value: %TRUE on success, %FALSE if error is set
126 gboolean
127 g_spawn_async (const gchar *working_directory,
128 gchar **argv,
129 gchar **envp,
130 GSpawnFlags flags,
131 GSpawnChildSetupFunc child_setup,
132 gpointer user_data,
133 GPid *child_pid,
134 GError **error)
136 g_return_val_if_fail (argv != NULL, FALSE);
138 return g_spawn_async_with_pipes (working_directory,
139 argv, envp,
140 flags,
141 child_setup,
142 user_data,
143 child_pid,
144 NULL, NULL, NULL,
145 error);
148 /* Avoids a danger in threaded situations (calling close()
149 * on a file descriptor twice, and another thread has
150 * re-opened it since the first close)
152 static gint
153 close_and_invalidate (gint *fd)
155 gint ret;
157 if (*fd < 0)
158 return -1;
159 else
161 again:
162 ret = close (*fd);
163 if (ret == -1 && errno == EINTR)
164 goto again;
165 *fd = -1;
168 return ret;
171 /* Some versions of OS X define READ_OK in public headers */
172 #undef READ_OK
174 typedef enum
176 READ_FAILED = 0, /* FALSE */
177 READ_OK,
178 READ_EOF
179 } ReadResult;
181 static ReadResult
182 read_data (GString *str,
183 gint fd,
184 GError **error)
186 gssize bytes;
187 gchar buf[4096];
189 again:
190 bytes = read (fd, buf, 4096);
192 if (bytes == 0)
193 return READ_EOF;
194 else if (bytes > 0)
196 g_string_append_len (str, buf, bytes);
197 return READ_OK;
199 else if (errno == EINTR)
200 goto again;
201 else
203 int errsv = errno;
205 g_set_error (error,
206 G_SPAWN_ERROR,
207 G_SPAWN_ERROR_READ,
208 _("Failed to read data from child process (%s)"),
209 g_strerror (errsv));
211 return READ_FAILED;
216 * g_spawn_sync:
217 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
218 * @argv: (array zero-terminated=1): child's argument vector
219 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
220 * @flags: flags from #GSpawnFlags
221 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
222 * @user_data: (closure): user data for @child_setup
223 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output, or %NULL
224 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child error messages, or %NULL
225 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid(), or %NULL
226 * @error: return location for error, or %NULL
228 * Executes a child synchronously (waits for the child to exit before returning).
229 * All output from the child is stored in @standard_output and @standard_error,
230 * if those parameters are non-%NULL. Note that you must set the
231 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
232 * passing %NULL for @standard_output and @standard_error.
233 * If @exit_status is non-%NULL, the exit status of the child is stored
234 * there as it would be returned by waitpid(); standard UNIX macros such
235 * as WIFEXITED() and WEXITSTATUS() must be used to evaluate the exit status.
236 * Note that this function call waitpid() even if @exit_status is %NULL, and
237 * does not accept the %G_SPAWN_DO_NOT_REAP_CHILD flag.
238 * If an error occurs, no data is returned in @standard_output,
239 * @standard_error, or @exit_status.
241 * This function calls g_spawn_async_with_pipes() internally; see that
242 * function for full details on the other parameters and details on
243 * how these functions work on Windows.
245 * Return value: %TRUE on success, %FALSE if an error was set.
247 gboolean
248 g_spawn_sync (const gchar *working_directory,
249 gchar **argv,
250 gchar **envp,
251 GSpawnFlags flags,
252 GSpawnChildSetupFunc child_setup,
253 gpointer user_data,
254 gchar **standard_output,
255 gchar **standard_error,
256 gint *exit_status,
257 GError **error)
259 gint outpipe = -1;
260 gint errpipe = -1;
261 GPid pid;
262 fd_set fds;
263 gint ret;
264 GString *outstr = NULL;
265 GString *errstr = NULL;
266 gboolean failed;
267 gint status;
269 g_return_val_if_fail (argv != NULL, FALSE);
270 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
271 g_return_val_if_fail (standard_output == NULL ||
272 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
273 g_return_val_if_fail (standard_error == NULL ||
274 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
276 /* Just to ensure segfaults if callers try to use
277 * these when an error is reported.
279 if (standard_output)
280 *standard_output = NULL;
282 if (standard_error)
283 *standard_error = NULL;
285 if (!fork_exec_with_pipes (FALSE,
286 working_directory,
287 argv,
288 envp,
289 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
290 (flags & G_SPAWN_SEARCH_PATH) != 0,
291 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
292 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
293 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
294 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
295 child_setup,
296 user_data,
297 &pid,
298 NULL,
299 standard_output ? &outpipe : NULL,
300 standard_error ? &errpipe : NULL,
301 error))
302 return FALSE;
304 /* Read data from child. */
306 failed = FALSE;
308 if (outpipe >= 0)
310 outstr = g_string_new (NULL);
313 if (errpipe >= 0)
315 errstr = g_string_new (NULL);
318 /* Read data until we get EOF on both pipes. */
319 while (!failed &&
320 (outpipe >= 0 ||
321 errpipe >= 0))
323 ret = 0;
325 FD_ZERO (&fds);
326 if (outpipe >= 0)
327 FD_SET (outpipe, &fds);
328 if (errpipe >= 0)
329 FD_SET (errpipe, &fds);
331 ret = select (MAX (outpipe, errpipe) + 1,
332 &fds,
333 NULL, NULL,
334 NULL /* no timeout */);
336 if (ret < 0)
338 int errsv = errno;
340 if (errno == EINTR)
341 continue;
343 failed = TRUE;
345 g_set_error (error,
346 G_SPAWN_ERROR,
347 G_SPAWN_ERROR_READ,
348 _("Unexpected error in select() reading data from a child process (%s)"),
349 g_strerror (errsv));
351 break;
354 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
356 switch (read_data (outstr, outpipe, error))
358 case READ_FAILED:
359 failed = TRUE;
360 break;
361 case READ_EOF:
362 close_and_invalidate (&outpipe);
363 outpipe = -1;
364 break;
365 default:
366 break;
369 if (failed)
370 break;
373 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
375 switch (read_data (errstr, errpipe, error))
377 case READ_FAILED:
378 failed = TRUE;
379 break;
380 case READ_EOF:
381 close_and_invalidate (&errpipe);
382 errpipe = -1;
383 break;
384 default:
385 break;
388 if (failed)
389 break;
393 /* These should only be open still if we had an error. */
395 if (outpipe >= 0)
396 close_and_invalidate (&outpipe);
397 if (errpipe >= 0)
398 close_and_invalidate (&errpipe);
400 /* Wait for child to exit, even if we have
401 * an error pending.
403 again:
405 ret = waitpid (pid, &status, 0);
407 if (ret < 0)
409 if (errno == EINTR)
410 goto again;
411 else if (errno == ECHILD)
413 if (exit_status)
415 g_warning ("In call to g_spawn_sync(), exit status of a child process was requested but SIGCHLD action was set to SIG_IGN and ECHILD was received by waitpid(), so exit status can't be returned. This is a bug in the program calling g_spawn_sync(); either don't request the exit status, or don't set the SIGCHLD action.");
417 else
419 /* We don't need the exit status. */
422 else
424 if (!failed) /* avoid error pileups */
426 int errsv = errno;
428 failed = TRUE;
430 g_set_error (error,
431 G_SPAWN_ERROR,
432 G_SPAWN_ERROR_READ,
433 _("Unexpected error in waitpid() (%s)"),
434 g_strerror (errsv));
439 if (failed)
441 if (outstr)
442 g_string_free (outstr, TRUE);
443 if (errstr)
444 g_string_free (errstr, TRUE);
446 return FALSE;
448 else
450 if (exit_status)
451 *exit_status = status;
453 if (standard_output)
454 *standard_output = g_string_free (outstr, FALSE);
456 if (standard_error)
457 *standard_error = g_string_free (errstr, FALSE);
459 return TRUE;
464 * g_spawn_async_with_pipes:
465 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
466 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
467 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
468 * @flags: flags from #GSpawnFlags
469 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
470 * @user_data: (closure): user data for @child_setup
471 * @child_pid: (out) (allow-none): return location for child process ID, or %NULL
472 * @standard_input: (out) (allow-none): return location for file descriptor to write to child's stdin, or %NULL
473 * @standard_output: (out) (allow-none): return location for file descriptor to read child's stdout, or %NULL
474 * @standard_error: (out) (allow-none): return location for file descriptor to read child's stderr, or %NULL
475 * @error: return location for error
477 * Executes a child program asynchronously (your program will not
478 * block waiting for the child to exit). The child program is
479 * specified by the only argument that must be provided, @argv. @argv
480 * should be a %NULL-terminated array of strings, to be passed as the
481 * argument vector for the child. The first string in @argv is of
482 * course the name of the program to execute. By default, the name of
483 * the program must be a full path; the <envar>PATH</envar> shell variable
484 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
485 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
486 * used, then the program will be run from the current directory (or
487 * @working_directory, if specified); this might be unexpected or even
488 * dangerous in some cases when the current directory is world-writable.
490 * On Windows, note that all the string or string vector arguments to
491 * this function and the other g_spawn*() functions are in UTF-8, the
492 * GLib file name encoding. Unicode characters that are not part of
493 * the system codepage passed in these arguments will be correctly
494 * available in the spawned program only if it uses wide character API
495 * to retrieve its command line. For C programs built with Microsoft's
496 * tools it is enough to make the program have a wmain() instead of
497 * main(). wmain() has a wide character argument vector as parameter.
499 * At least currently, mingw doesn't support wmain(), so if you use
500 * mingw to develop the spawned program, it will have to call the
501 * undocumented function __wgetmainargs() to get the wide character
502 * argument vector and environment. See gspawn-win32-helper.c in the
503 * GLib sources or init.c in the mingw runtime sources for a prototype
504 * for that function. Alternatively, you can retrieve the Win32 system
505 * level wide character command line passed to the spawned program
506 * using the GetCommandLineW() function.
508 * On Windows the low-level child process creation API
509 * <function>CreateProcess()</function> doesn't use argument vectors,
510 * but a command line. The C runtime library's
511 * <function>spawn*()</function> family of functions (which
512 * g_spawn_async_with_pipes() eventually calls) paste the argument
513 * vector elements together into a command line, and the C runtime startup code
514 * does a corresponding reconstruction of an argument vector from the
515 * command line, to be passed to main(). Complications arise when you have
516 * argument vector elements that contain spaces of double quotes. The
517 * <function>spawn*()</function> functions don't do any quoting or
518 * escaping, but on the other hand the startup code does do unquoting
519 * and unescaping in order to enable receiving arguments with embedded
520 * spaces or double quotes. To work around this asymmetry,
521 * g_spawn_async_with_pipes() will do quoting and escaping on argument
522 * vector elements that need it before calling the C runtime
523 * spawn() function.
525 * The returned @child_pid on Windows is a handle to the child
526 * process, not its identifier. Process handles and process
527 * identifiers are different concepts on Windows.
529 * @envp is a %NULL-terminated array of strings, where each string
530 * has the form <literal>KEY=VALUE</literal>. This will become
531 * the child's environment. If @envp is %NULL, the child inherits its
532 * parent's environment.
534 * @flags should be the bitwise OR of any flags you want to affect the
535 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
536 * child will not automatically be reaped; you must use a child watch to
537 * be notified about the death of the child process. Eventually you must
538 * call g_spawn_close_pid() on the @child_pid, in order to free
539 * resources which may be associated with the child process. (On Unix,
540 * using a child watch is equivalent to calling waitpid() or handling
541 * the <literal>SIGCHLD</literal> signal manually. On Windows, calling g_spawn_close_pid()
542 * is equivalent to calling CloseHandle() on the process handle returned
543 * in @child_pid). See g_child_watch_add().
545 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
546 * descriptors will be inherited by the child; otherwise all
547 * descriptors except stdin/stdout/stderr will be closed before
548 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
549 * means that <literal>argv[0]</literal> need not be an absolute path, it
550 * will be looked for in the user's <envar>PATH</envar>.
551 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
552 * be discarded, instead of going to the same location as the parent's
553 * standard output. If you use this flag, @standard_output must be %NULL.
554 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
555 * will be discarded, instead of going to the same location as the parent's
556 * standard error. If you use this flag, @standard_error must be %NULL.
557 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
558 * standard input (by default, the child's standard input is attached to
559 * /dev/null). If you use this flag, @standard_input must be %NULL.
560 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
561 * the file to execute, while the remaining elements are the
562 * actual argument vector to pass to the file. Normally
563 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
564 * passes all of @argv to the child.
566 * @child_setup and @user_data are a function and user data. On POSIX
567 * platforms, the function is called in the child after GLib has
568 * performed all the setup it plans to perform (including creating
569 * pipes, closing file descriptors, etc.) but before calling
570 * exec(). That is, @child_setup is called just
571 * before calling exec() in the child. Obviously
572 * actions taken in this function will only affect the child, not the
573 * parent.
575 * On Windows, there is no separate fork() and exec()
576 * functionality. Child processes are created and run with a single
577 * API call, CreateProcess(). There is no sensible thing @child_setup
578 * could be used for on Windows so it is ignored and not called.
580 * If non-%NULL, @child_pid will on Unix be filled with the child's
581 * process ID. You can use the process ID to send signals to the
582 * child, or to use g_child_watch_add() (or waitpid()) if you specified the
583 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
584 * filled with a handle to the child process only if you specified the
585 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
586 * process using the Win32 API, for example wait for its termination
587 * with the <function>WaitFor*()</function> functions, or examine its
588 * exit code with GetExitCodeProcess(). You should close the handle
589 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
591 * If non-%NULL, the @standard_input, @standard_output, @standard_error
592 * locations will be filled with file descriptors for writing to the child's
593 * standard input or reading from its standard output or standard error.
594 * The caller of g_spawn_async_with_pipes() must close these file descriptors
595 * when they are no longer in use. If these parameters are %NULL, the corresponding
596 * pipe won't be created.
598 * If @standard_input is NULL, the child's standard input is attached to
599 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
601 * If @standard_error is NULL, the child's standard error goes to the same
602 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
603 * is set.
605 * If @standard_output is NULL, the child's standard output goes to the same
606 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
607 * is set.
609 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
610 * If an error is set, the function returns %FALSE. Errors
611 * are reported even if they occur in the child (for example if the
612 * executable in <literal>argv[0]</literal> is not found). Typically
613 * the <literal>message</literal> field of returned errors should be displayed
614 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
616 * If an error occurs, @child_pid, @standard_input, @standard_output,
617 * and @standard_error will not be filled with valid values.
619 * If @child_pid is not %NULL and an error does not occur then the returned
620 * process reference must be closed using g_spawn_close_pid().
622 * <note><para>
623 * If you are writing a GTK+ application, and the program you
624 * are spawning is a graphical application, too, then you may
625 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
626 * the spawned program opens its windows on the right screen.
627 * </para></note>
629 * Return value: %TRUE on success, %FALSE if an error was set
631 gboolean
632 g_spawn_async_with_pipes (const gchar *working_directory,
633 gchar **argv,
634 gchar **envp,
635 GSpawnFlags flags,
636 GSpawnChildSetupFunc child_setup,
637 gpointer user_data,
638 GPid *child_pid,
639 gint *standard_input,
640 gint *standard_output,
641 gint *standard_error,
642 GError **error)
644 g_return_val_if_fail (argv != NULL, FALSE);
645 g_return_val_if_fail (standard_output == NULL ||
646 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
647 g_return_val_if_fail (standard_error == NULL ||
648 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
649 /* can't inherit stdin if we have an input pipe. */
650 g_return_val_if_fail (standard_input == NULL ||
651 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
653 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
654 working_directory,
655 argv,
656 envp,
657 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
658 (flags & G_SPAWN_SEARCH_PATH) != 0,
659 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
660 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
661 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
662 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
663 child_setup,
664 user_data,
665 child_pid,
666 standard_input,
667 standard_output,
668 standard_error,
669 error);
673 * g_spawn_command_line_sync:
674 * @command_line: a command line
675 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output
676 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child errors
677 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid()
678 * @error: return location for errors
680 * A simple version of g_spawn_sync() with little-used parameters
681 * removed, taking a command line instead of an argument vector. See
682 * g_spawn_sync() for full details. @command_line will be parsed by
683 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
684 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
685 * implications, so consider using g_spawn_sync() directly if
686 * appropriate. Possible errors are those from g_spawn_sync() and those
687 * from g_shell_parse_argv().
689 * If @exit_status is non-%NULL, the exit status of the child is stored there as
690 * it would be returned by waitpid(); standard UNIX macros such as WIFEXITED()
691 * and WEXITSTATUS() must be used to evaluate the exit status.
693 * On Windows, please note the implications of g_shell_parse_argv()
694 * parsing @command_line. Parsing is done according to Unix shell rules, not
695 * Windows command interpreter rules.
696 * Space is a separator, and backslashes are
697 * special. Thus you cannot simply pass a @command_line containing
698 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
699 * the backslashes will be eaten, and the space will act as a
700 * separator. You need to enclose such paths with single quotes, like
701 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
703 * Return value: %TRUE on success, %FALSE if an error was set
705 gboolean
706 g_spawn_command_line_sync (const gchar *command_line,
707 gchar **standard_output,
708 gchar **standard_error,
709 gint *exit_status,
710 GError **error)
712 gboolean retval;
713 gchar **argv = NULL;
715 g_return_val_if_fail (command_line != NULL, FALSE);
717 if (!g_shell_parse_argv (command_line,
718 NULL, &argv,
719 error))
720 return FALSE;
722 retval = g_spawn_sync (NULL,
723 argv,
724 NULL,
725 G_SPAWN_SEARCH_PATH,
726 NULL,
727 NULL,
728 standard_output,
729 standard_error,
730 exit_status,
731 error);
732 g_strfreev (argv);
734 return retval;
738 * g_spawn_command_line_async:
739 * @command_line: a command line
740 * @error: return location for errors
742 * A simple version of g_spawn_async() that parses a command line with
743 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
744 * command line in the background. Unlike g_spawn_async(), the
745 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
746 * that %G_SPAWN_SEARCH_PATH can have security implications, so
747 * consider using g_spawn_async() directly if appropriate. Possible
748 * errors are those from g_shell_parse_argv() and g_spawn_async().
750 * The same concerns on Windows apply as for g_spawn_command_line_sync().
752 * Return value: %TRUE on success, %FALSE if error is set.
754 gboolean
755 g_spawn_command_line_async (const gchar *command_line,
756 GError **error)
758 gboolean retval;
759 gchar **argv = NULL;
761 g_return_val_if_fail (command_line != NULL, FALSE);
763 if (!g_shell_parse_argv (command_line,
764 NULL, &argv,
765 error))
766 return FALSE;
768 retval = g_spawn_async (NULL,
769 argv,
770 NULL,
771 G_SPAWN_SEARCH_PATH,
772 NULL,
773 NULL,
774 NULL,
775 error);
776 g_strfreev (argv);
778 return retval;
781 static gint
782 exec_err_to_g_error (gint en)
784 switch (en)
786 #ifdef EACCES
787 case EACCES:
788 return G_SPAWN_ERROR_ACCES;
789 break;
790 #endif
792 #ifdef EPERM
793 case EPERM:
794 return G_SPAWN_ERROR_PERM;
795 break;
796 #endif
798 #ifdef E2BIG
799 case E2BIG:
800 return G_SPAWN_ERROR_2BIG;
801 break;
802 #endif
804 #ifdef ENOEXEC
805 case ENOEXEC:
806 return G_SPAWN_ERROR_NOEXEC;
807 break;
808 #endif
810 #ifdef ENAMETOOLONG
811 case ENAMETOOLONG:
812 return G_SPAWN_ERROR_NAMETOOLONG;
813 break;
814 #endif
816 #ifdef ENOENT
817 case ENOENT:
818 return G_SPAWN_ERROR_NOENT;
819 break;
820 #endif
822 #ifdef ENOMEM
823 case ENOMEM:
824 return G_SPAWN_ERROR_NOMEM;
825 break;
826 #endif
828 #ifdef ENOTDIR
829 case ENOTDIR:
830 return G_SPAWN_ERROR_NOTDIR;
831 break;
832 #endif
834 #ifdef ELOOP
835 case ELOOP:
836 return G_SPAWN_ERROR_LOOP;
837 break;
838 #endif
840 #ifdef ETXTBUSY
841 case ETXTBUSY:
842 return G_SPAWN_ERROR_TXTBUSY;
843 break;
844 #endif
846 #ifdef EIO
847 case EIO:
848 return G_SPAWN_ERROR_IO;
849 break;
850 #endif
852 #ifdef ENFILE
853 case ENFILE:
854 return G_SPAWN_ERROR_NFILE;
855 break;
856 #endif
858 #ifdef EMFILE
859 case EMFILE:
860 return G_SPAWN_ERROR_MFILE;
861 break;
862 #endif
864 #ifdef EINVAL
865 case EINVAL:
866 return G_SPAWN_ERROR_INVAL;
867 break;
868 #endif
870 #ifdef EISDIR
871 case EISDIR:
872 return G_SPAWN_ERROR_ISDIR;
873 break;
874 #endif
876 #ifdef ELIBBAD
877 case ELIBBAD:
878 return G_SPAWN_ERROR_LIBBAD;
879 break;
880 #endif
882 default:
883 return G_SPAWN_ERROR_FAILED;
884 break;
888 static gssize
889 write_all (gint fd, gconstpointer vbuf, gsize to_write)
891 gchar *buf = (gchar *) vbuf;
893 while (to_write > 0)
895 gssize count = write (fd, buf, to_write);
896 if (count < 0)
898 if (errno != EINTR)
899 return FALSE;
901 else
903 to_write -= count;
904 buf += count;
908 return TRUE;
911 G_GNUC_NORETURN
912 static void
913 write_err_and_exit (gint fd, gint msg)
915 gint en = errno;
917 write_all (fd, &msg, sizeof(msg));
918 write_all (fd, &en, sizeof(en));
920 _exit (1);
923 static int
924 set_cloexec (void *data, gint fd)
926 if (fd >= GPOINTER_TO_INT (data))
927 fcntl (fd, F_SETFD, FD_CLOEXEC);
929 return 0;
932 #ifndef HAVE_FDWALK
933 static int
934 fdwalk (int (*cb)(void *data, int fd), void *data)
936 gint open_max;
937 gint fd;
938 gint res = 0;
940 #ifdef HAVE_SYS_RESOURCE_H
941 struct rlimit rl;
942 #endif
944 #ifdef __linux__
945 DIR *d;
947 if ((d = opendir("/proc/self/fd"))) {
948 struct dirent *de;
950 while ((de = readdir(d))) {
951 glong l;
952 gchar *e = NULL;
954 if (de->d_name[0] == '.')
955 continue;
957 errno = 0;
958 l = strtol(de->d_name, &e, 10);
959 if (errno != 0 || !e || *e)
960 continue;
962 fd = (gint) l;
964 if ((glong) fd != l)
965 continue;
967 if (fd == dirfd(d))
968 continue;
970 if ((res = cb (data, fd)) != 0)
971 break;
974 closedir(d);
975 return res;
978 /* If /proc is not mounted or not accessible we fall back to the old
979 * rlimit trick */
981 #endif
983 #ifdef HAVE_SYS_RESOURCE_H
985 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
986 open_max = rl.rlim_max;
987 else
988 #endif
989 open_max = sysconf (_SC_OPEN_MAX);
991 for (fd = 0; fd < open_max; fd++)
992 if ((res = cb (data, fd)) != 0)
993 break;
995 return res;
997 #endif
999 static gint
1000 sane_dup2 (gint fd1, gint fd2)
1002 gint ret;
1004 retry:
1005 ret = dup2 (fd1, fd2);
1006 if (ret < 0 && errno == EINTR)
1007 goto retry;
1009 return ret;
1012 static gint
1013 sane_open (const char *path, gint mode)
1015 gint ret;
1017 retry:
1018 ret = open (path, mode);
1019 if (ret < 0 && errno == EINTR)
1020 goto retry;
1022 return ret;
1025 enum
1027 CHILD_CHDIR_FAILED,
1028 CHILD_EXEC_FAILED,
1029 CHILD_DUP2_FAILED,
1030 CHILD_FORK_FAILED
1033 static void
1034 do_exec (gint child_err_report_fd,
1035 gint stdin_fd,
1036 gint stdout_fd,
1037 gint stderr_fd,
1038 const gchar *working_directory,
1039 gchar **argv,
1040 gchar **envp,
1041 gboolean close_descriptors,
1042 gboolean search_path,
1043 gboolean stdout_to_null,
1044 gboolean stderr_to_null,
1045 gboolean child_inherits_stdin,
1046 gboolean file_and_argv_zero,
1047 GSpawnChildSetupFunc child_setup,
1048 gpointer user_data)
1050 if (working_directory && chdir (working_directory) < 0)
1051 write_err_and_exit (child_err_report_fd,
1052 CHILD_CHDIR_FAILED);
1054 /* Close all file descriptors but stdin stdout and stderr as
1055 * soon as we exec. Note that this includes
1056 * child_err_report_fd, which keeps the parent from blocking
1057 * forever on the other end of that pipe.
1059 if (close_descriptors)
1061 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1063 else
1065 /* We need to do child_err_report_fd anyway */
1066 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1069 /* Redirect pipes as required */
1071 if (stdin_fd >= 0)
1073 /* dup2 can't actually fail here I don't think */
1075 if (sane_dup2 (stdin_fd, 0) < 0)
1076 write_err_and_exit (child_err_report_fd,
1077 CHILD_DUP2_FAILED);
1079 /* ignore this if it doesn't work */
1080 close_and_invalidate (&stdin_fd);
1082 else if (!child_inherits_stdin)
1084 /* Keep process from blocking on a read of stdin */
1085 gint read_null = open ("/dev/null", O_RDONLY);
1086 sane_dup2 (read_null, 0);
1087 close_and_invalidate (&read_null);
1090 if (stdout_fd >= 0)
1092 /* dup2 can't actually fail here I don't think */
1094 if (sane_dup2 (stdout_fd, 1) < 0)
1095 write_err_and_exit (child_err_report_fd,
1096 CHILD_DUP2_FAILED);
1098 /* ignore this if it doesn't work */
1099 close_and_invalidate (&stdout_fd);
1101 else if (stdout_to_null)
1103 gint write_null = sane_open ("/dev/null", O_WRONLY);
1104 sane_dup2 (write_null, 1);
1105 close_and_invalidate (&write_null);
1108 if (stderr_fd >= 0)
1110 /* dup2 can't actually fail here I don't think */
1112 if (sane_dup2 (stderr_fd, 2) < 0)
1113 write_err_and_exit (child_err_report_fd,
1114 CHILD_DUP2_FAILED);
1116 /* ignore this if it doesn't work */
1117 close_and_invalidate (&stderr_fd);
1119 else if (stderr_to_null)
1121 gint write_null = sane_open ("/dev/null", O_WRONLY);
1122 sane_dup2 (write_null, 2);
1123 close_and_invalidate (&write_null);
1126 /* Call user function just before we exec */
1127 if (child_setup)
1129 (* child_setup) (user_data);
1132 g_execute (argv[0],
1133 file_and_argv_zero ? argv + 1 : argv,
1134 envp, search_path);
1136 /* Exec failed */
1137 write_err_and_exit (child_err_report_fd,
1138 CHILD_EXEC_FAILED);
1141 static gboolean
1142 read_ints (int fd,
1143 gint* buf,
1144 gint n_ints_in_buf,
1145 gint *n_ints_read,
1146 GError **error)
1148 gsize bytes = 0;
1150 while (TRUE)
1152 gssize chunk;
1154 if (bytes >= sizeof(gint)*2)
1155 break; /* give up, who knows what happened, should not be
1156 * possible.
1159 again:
1160 chunk = read (fd,
1161 ((gchar*)buf) + bytes,
1162 sizeof(gint) * n_ints_in_buf - bytes);
1163 if (chunk < 0 && errno == EINTR)
1164 goto again;
1166 if (chunk < 0)
1168 int errsv = errno;
1170 /* Some weird shit happened, bail out */
1171 g_set_error (error,
1172 G_SPAWN_ERROR,
1173 G_SPAWN_ERROR_FAILED,
1174 _("Failed to read from child pipe (%s)"),
1175 g_strerror (errsv));
1177 return FALSE;
1179 else if (chunk == 0)
1180 break; /* EOF */
1181 else /* chunk > 0 */
1182 bytes += chunk;
1185 *n_ints_read = (gint)(bytes / sizeof(gint));
1187 return TRUE;
1190 static gboolean
1191 fork_exec_with_pipes (gboolean intermediate_child,
1192 const gchar *working_directory,
1193 gchar **argv,
1194 gchar **envp,
1195 gboolean close_descriptors,
1196 gboolean search_path,
1197 gboolean stdout_to_null,
1198 gboolean stderr_to_null,
1199 gboolean child_inherits_stdin,
1200 gboolean file_and_argv_zero,
1201 GSpawnChildSetupFunc child_setup,
1202 gpointer user_data,
1203 GPid *child_pid,
1204 gint *standard_input,
1205 gint *standard_output,
1206 gint *standard_error,
1207 GError **error)
1209 GPid pid = -1;
1210 gint stdin_pipe[2] = { -1, -1 };
1211 gint stdout_pipe[2] = { -1, -1 };
1212 gint stderr_pipe[2] = { -1, -1 };
1213 gint child_err_report_pipe[2] = { -1, -1 };
1214 gint child_pid_report_pipe[2] = { -1, -1 };
1215 gint status;
1217 if (!make_pipe (child_err_report_pipe, error))
1218 return FALSE;
1220 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1221 goto cleanup_and_fail;
1223 if (standard_input && !make_pipe (stdin_pipe, error))
1224 goto cleanup_and_fail;
1226 if (standard_output && !make_pipe (stdout_pipe, error))
1227 goto cleanup_and_fail;
1229 if (standard_error && !make_pipe (stderr_pipe, error))
1230 goto cleanup_and_fail;
1232 pid = fork ();
1234 if (pid < 0)
1236 int errsv = errno;
1238 g_set_error (error,
1239 G_SPAWN_ERROR,
1240 G_SPAWN_ERROR_FORK,
1241 _("Failed to fork (%s)"),
1242 g_strerror (errsv));
1244 goto cleanup_and_fail;
1246 else if (pid == 0)
1248 /* Immediate child. This may or may not be the child that
1249 * actually execs the new process.
1252 /* Reset some signal handlers that we may use */
1253 signal (SIGCHLD, SIG_DFL);
1254 signal (SIGINT, SIG_DFL);
1255 signal (SIGTERM, SIG_DFL);
1256 signal (SIGHUP, SIG_DFL);
1258 /* Be sure we crash if the parent exits
1259 * and we write to the err_report_pipe
1261 signal (SIGPIPE, SIG_DFL);
1263 /* Close the parent's end of the pipes;
1264 * not needed in the close_descriptors case,
1265 * though
1267 close_and_invalidate (&child_err_report_pipe[0]);
1268 close_and_invalidate (&child_pid_report_pipe[0]);
1269 close_and_invalidate (&stdin_pipe[1]);
1270 close_and_invalidate (&stdout_pipe[0]);
1271 close_and_invalidate (&stderr_pipe[0]);
1273 if (intermediate_child)
1275 /* We need to fork an intermediate child that launches the
1276 * final child. The purpose of the intermediate child
1277 * is to exit, so we can waitpid() it immediately.
1278 * Then the grandchild will not become a zombie.
1280 GPid grandchild_pid;
1282 grandchild_pid = fork ();
1284 if (grandchild_pid < 0)
1286 /* report -1 as child PID */
1287 write_all (child_pid_report_pipe[1], &grandchild_pid,
1288 sizeof(grandchild_pid));
1290 write_err_and_exit (child_err_report_pipe[1],
1291 CHILD_FORK_FAILED);
1293 else if (grandchild_pid == 0)
1295 do_exec (child_err_report_pipe[1],
1296 stdin_pipe[0],
1297 stdout_pipe[1],
1298 stderr_pipe[1],
1299 working_directory,
1300 argv,
1301 envp,
1302 close_descriptors,
1303 search_path,
1304 stdout_to_null,
1305 stderr_to_null,
1306 child_inherits_stdin,
1307 file_and_argv_zero,
1308 child_setup,
1309 user_data);
1311 else
1313 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1314 close_and_invalidate (&child_pid_report_pipe[1]);
1316 _exit (0);
1319 else
1321 /* Just run the child.
1324 do_exec (child_err_report_pipe[1],
1325 stdin_pipe[0],
1326 stdout_pipe[1],
1327 stderr_pipe[1],
1328 working_directory,
1329 argv,
1330 envp,
1331 close_descriptors,
1332 search_path,
1333 stdout_to_null,
1334 stderr_to_null,
1335 child_inherits_stdin,
1336 file_and_argv_zero,
1337 child_setup,
1338 user_data);
1341 else
1343 /* Parent */
1345 gint buf[2];
1346 gint n_ints = 0;
1348 /* Close the uncared-about ends of the pipes */
1349 close_and_invalidate (&child_err_report_pipe[1]);
1350 close_and_invalidate (&child_pid_report_pipe[1]);
1351 close_and_invalidate (&stdin_pipe[0]);
1352 close_and_invalidate (&stdout_pipe[1]);
1353 close_and_invalidate (&stderr_pipe[1]);
1355 /* If we had an intermediate child, reap it */
1356 if (intermediate_child)
1358 wait_again:
1359 if (waitpid (pid, &status, 0) < 0)
1361 if (errno == EINTR)
1362 goto wait_again;
1363 else if (errno == ECHILD)
1364 ; /* do nothing, child already reaped */
1365 else
1366 g_warning ("waitpid() should not fail in "
1367 "'fork_exec_with_pipes'");
1372 if (!read_ints (child_err_report_pipe[0],
1373 buf, 2, &n_ints,
1374 error))
1375 goto cleanup_and_fail;
1377 if (n_ints >= 2)
1379 /* Error from the child. */
1381 switch (buf[0])
1383 case CHILD_CHDIR_FAILED:
1384 g_set_error (error,
1385 G_SPAWN_ERROR,
1386 G_SPAWN_ERROR_CHDIR,
1387 _("Failed to change to directory '%s' (%s)"),
1388 working_directory,
1389 g_strerror (buf[1]));
1391 break;
1393 case CHILD_EXEC_FAILED:
1394 g_set_error (error,
1395 G_SPAWN_ERROR,
1396 exec_err_to_g_error (buf[1]),
1397 _("Failed to execute child process \"%s\" (%s)"),
1398 argv[0],
1399 g_strerror (buf[1]));
1401 break;
1403 case CHILD_DUP2_FAILED:
1404 g_set_error (error,
1405 G_SPAWN_ERROR,
1406 G_SPAWN_ERROR_FAILED,
1407 _("Failed to redirect output or input of child process (%s)"),
1408 g_strerror (buf[1]));
1410 break;
1412 case CHILD_FORK_FAILED:
1413 g_set_error (error,
1414 G_SPAWN_ERROR,
1415 G_SPAWN_ERROR_FORK,
1416 _("Failed to fork child process (%s)"),
1417 g_strerror (buf[1]));
1418 break;
1420 default:
1421 g_set_error (error,
1422 G_SPAWN_ERROR,
1423 G_SPAWN_ERROR_FAILED,
1424 _("Unknown error executing child process \"%s\""),
1425 argv[0]);
1426 break;
1429 goto cleanup_and_fail;
1432 /* Get child pid from intermediate child pipe. */
1433 if (intermediate_child)
1435 n_ints = 0;
1437 if (!read_ints (child_pid_report_pipe[0],
1438 buf, 1, &n_ints, error))
1439 goto cleanup_and_fail;
1441 if (n_ints < 1)
1443 int errsv = errno;
1445 g_set_error (error,
1446 G_SPAWN_ERROR,
1447 G_SPAWN_ERROR_FAILED,
1448 _("Failed to read enough data from child pid pipe (%s)"),
1449 g_strerror (errsv));
1450 goto cleanup_and_fail;
1452 else
1454 /* we have the child pid */
1455 pid = buf[0];
1459 /* Success against all odds! return the information */
1460 close_and_invalidate (&child_err_report_pipe[0]);
1461 close_and_invalidate (&child_pid_report_pipe[0]);
1463 if (child_pid)
1464 *child_pid = pid;
1466 if (standard_input)
1467 *standard_input = stdin_pipe[1];
1468 if (standard_output)
1469 *standard_output = stdout_pipe[0];
1470 if (standard_error)
1471 *standard_error = stderr_pipe[0];
1473 return TRUE;
1476 cleanup_and_fail:
1478 /* There was an error from the Child, reap the child to avoid it being
1479 a zombie.
1482 if (pid > 0)
1484 wait_failed:
1485 if (waitpid (pid, NULL, 0) < 0)
1487 if (errno == EINTR)
1488 goto wait_failed;
1489 else if (errno == ECHILD)
1490 ; /* do nothing, child already reaped */
1491 else
1492 g_warning ("waitpid() should not fail in "
1493 "'fork_exec_with_pipes'");
1497 close_and_invalidate (&child_err_report_pipe[0]);
1498 close_and_invalidate (&child_err_report_pipe[1]);
1499 close_and_invalidate (&child_pid_report_pipe[0]);
1500 close_and_invalidate (&child_pid_report_pipe[1]);
1501 close_and_invalidate (&stdin_pipe[0]);
1502 close_and_invalidate (&stdin_pipe[1]);
1503 close_and_invalidate (&stdout_pipe[0]);
1504 close_and_invalidate (&stdout_pipe[1]);
1505 close_and_invalidate (&stderr_pipe[0]);
1506 close_and_invalidate (&stderr_pipe[1]);
1508 return FALSE;
1511 static gboolean
1512 make_pipe (gint p[2],
1513 GError **error)
1515 if (pipe (p) < 0)
1517 gint errsv = errno;
1518 g_set_error (error,
1519 G_SPAWN_ERROR,
1520 G_SPAWN_ERROR_FAILED,
1521 _("Failed to create pipe for communicating with child process (%s)"),
1522 g_strerror (errsv));
1523 return FALSE;
1525 else
1526 return TRUE;
1529 /* Based on execvp from GNU C Library */
1531 static void
1532 script_execute (const gchar *file,
1533 gchar **argv,
1534 gchar **envp,
1535 gboolean search_path)
1537 /* Count the arguments. */
1538 int argc = 0;
1539 while (argv[argc])
1540 ++argc;
1542 /* Construct an argument list for the shell. */
1544 gchar **new_argv;
1546 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1548 new_argv[0] = (char *) "/bin/sh";
1549 new_argv[1] = (char *) file;
1550 while (argc > 0)
1552 new_argv[argc + 1] = argv[argc];
1553 --argc;
1556 /* Execute the shell. */
1557 if (envp)
1558 execve (new_argv[0], new_argv, envp);
1559 else
1560 execv (new_argv[0], new_argv);
1562 g_free (new_argv);
1566 static gchar*
1567 my_strchrnul (const gchar *str, gchar c)
1569 gchar *p = (gchar*) str;
1570 while (*p && (*p != c))
1571 ++p;
1573 return p;
1576 static gint
1577 g_execute (const gchar *file,
1578 gchar **argv,
1579 gchar **envp,
1580 gboolean search_path)
1582 if (*file == '\0')
1584 /* We check the simple case first. */
1585 errno = ENOENT;
1586 return -1;
1589 if (!search_path || strchr (file, '/') != NULL)
1591 /* Don't search when it contains a slash. */
1592 if (envp)
1593 execve (file, argv, envp);
1594 else
1595 execv (file, argv);
1597 if (errno == ENOEXEC)
1598 script_execute (file, argv, envp, FALSE);
1600 else
1602 gboolean got_eacces = 0;
1603 const gchar *path, *p;
1604 gchar *name, *freeme;
1605 gsize len;
1606 gsize pathlen;
1608 path = g_getenv ("PATH");
1609 if (path == NULL)
1611 /* There is no `PATH' in the environment. The default
1612 * search path in libc is the current directory followed by
1613 * the path `confstr' returns for `_CS_PATH'.
1616 /* In GLib we put . last, for security, and don't use the
1617 * unportable confstr(); UNIX98 does not actually specify
1618 * what to search if PATH is unset. POSIX may, dunno.
1621 path = "/bin:/usr/bin:.";
1624 len = strlen (file) + 1;
1625 pathlen = strlen (path);
1626 freeme = name = g_malloc (pathlen + len + 1);
1628 /* Copy the file name at the top, including '\0' */
1629 memcpy (name + pathlen + 1, file, len);
1630 name = name + pathlen;
1631 /* And add the slash before the filename */
1632 *name = '/';
1634 p = path;
1637 char *startp;
1639 path = p;
1640 p = my_strchrnul (path, ':');
1642 if (p == path)
1643 /* Two adjacent colons, or a colon at the beginning or the end
1644 * of `PATH' means to search the current directory.
1646 startp = name + 1;
1647 else
1648 startp = memcpy (name - (p - path), path, p - path);
1650 /* Try to execute this name. If it works, execv will not return. */
1651 if (envp)
1652 execve (startp, argv, envp);
1653 else
1654 execv (startp, argv);
1656 if (errno == ENOEXEC)
1657 script_execute (startp, argv, envp, search_path);
1659 switch (errno)
1661 case EACCES:
1662 /* Record the we got a `Permission denied' error. If we end
1663 * up finding no executable we can use, we want to diagnose
1664 * that we did find one but were denied access.
1666 got_eacces = TRUE;
1668 /* FALL THRU */
1670 case ENOENT:
1671 #ifdef ESTALE
1672 case ESTALE:
1673 #endif
1674 #ifdef ENOTDIR
1675 case ENOTDIR:
1676 #endif
1677 /* Those errors indicate the file is missing or not executable
1678 * by us, in which case we want to just try the next path
1679 * directory.
1681 break;
1683 default:
1684 /* Some other error means we found an executable file, but
1685 * something went wrong executing it; return the error to our
1686 * caller.
1688 g_free (freeme);
1689 return -1;
1692 while (*p++ != '\0');
1694 /* We tried every element and none of them worked. */
1695 if (got_eacces)
1696 /* At least one failure was due to permissions, so report that
1697 * error.
1699 errno = EACCES;
1701 g_free (freeme);
1704 /* Return the error from the last attempt (probably ENOENT). */
1705 return -1;
1709 * g_spawn_close_pid:
1710 * @pid: The process reference to close
1712 * On some platforms, notably Windows, the #GPid type represents a resource
1713 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1714 * is provided for this purpose. It should be used on all platforms, even
1715 * though it doesn't do anything under UNIX.
1717 void
1718 g_spawn_close_pid (GPid pid)