Clarify documentation of GValueTransform
[glib.git] / glib / gspawn.c
blobb1ee3ea022fd2596f0b7786db03905231afc418f
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 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library 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 License
18 * along with this library; if not, see <http://www.gnu.org/licenses/>.
21 #include "config.h"
23 #include <sys/time.h>
24 #include <sys/types.h>
25 #include <sys/wait.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <string.h>
31 #include <stdlib.h> /* for fdwalk */
32 #include <dirent.h>
34 #ifdef HAVE_SYS_SELECT_H
35 #include <sys/select.h>
36 #endif /* HAVE_SYS_SELECT_H */
38 #ifdef HAVE_SYS_RESOURCE_H
39 #include <sys/resource.h>
40 #endif /* HAVE_SYS_RESOURCE_H */
42 #include "gspawn.h"
43 #include "gthread.h"
44 #include "glib/gstdio.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"
54 #include "glib-unix.h"
56 /**
57 * SECTION:spawn
58 * @Short_description: process launching
59 * @Title: Spawning Processes
61 * GLib supports spawning of processes with an API that is more
62 * convenient than the bare UNIX fork() and exec().
64 * The g_spawn family of functions has synchronous (g_spawn_sync())
65 * and asynchronous variants (g_spawn_async(), g_spawn_async_with_pipes()),
66 * as well as convenience variants that take a complete shell-like
67 * commandline (g_spawn_command_line_sync(), g_spawn_command_line_async()).
69 * See #GSubprocess in GIO for a higher-level API that provides
70 * stream interfaces for communication with child processes.
72 * An example of using g_spawn_async_with_pipes():
73 * |[<!-- language="C" -->
74 * const gchar * const argv[] = { "my-favourite-program", "--args", NULL };
75 * gint child_stdout, child_stderr;
76 * GPid child_pid;
77 * g_autoptr(GError) error = NULL;
79 * // Spawn child process.
80 * g_spawn_async_with_pipes (NULL, argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL,
81 * NULL, &child_pid, NULL, &child_stdout,
82 * &child_stderr, &error);
83 * if (error != NULL)
84 * {
85 * g_error ("Spawning child failed: %s", error->message);
86 * return;
87 * }
89 * // Add a child watch function which will be called when the child process
90 * // exits.
91 * g_child_watch_add (child_pid, child_watch_cb, NULL);
93 * // You could watch for output on @child_stdout and @child_stderr using
94 * // #GUnixInputStream or #GIOChannel here.
96 * static void
97 * child_watch_cb (GPid pid,
98 * gint status,
99 * gpointer user_data)
101 * g_message ("Child %" G_PID_FORMAT " exited %s", pid,
102 * g_spawn_check_exit_status (status, NULL) ? "normally" : "abnormally");
104 * // Free any resources associated with the child here, such as I/O channels
105 * // on its stdout and stderr FDs. If you have no code to put in the
106 * // child_watch_cb() callback, you can remove it and the g_child_watch_add()
107 * // call, but you must also remove the G_SPAWN_DO_NOT_REAP_CHILD flag,
108 * // otherwise the child process will stay around as a zombie until this
109 * // process exits.
111 * g_spawn_close_pid (pid);
113 * ]|
118 static gint g_execute (const gchar *file,
119 gchar **argv,
120 gchar **envp,
121 gboolean search_path,
122 gboolean search_path_from_envp);
124 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
125 const gchar *working_directory,
126 gchar **argv,
127 gchar **envp,
128 gboolean close_descriptors,
129 gboolean search_path,
130 gboolean search_path_from_envp,
131 gboolean stdout_to_null,
132 gboolean stderr_to_null,
133 gboolean child_inherits_stdin,
134 gboolean file_and_argv_zero,
135 gboolean cloexec_pipes,
136 GSpawnChildSetupFunc child_setup,
137 gpointer user_data,
138 GPid *child_pid,
139 gint *standard_input,
140 gint *standard_output,
141 gint *standard_error,
142 GError **error);
144 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
145 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
148 * g_spawn_async:
149 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's
150 * @argv: (array zero-terminated=1): child's argument vector
151 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's
152 * @flags: flags from #GSpawnFlags
153 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
154 * @user_data: (closure): user data for @child_setup
155 * @child_pid: (out) (optional): return location for child process reference, or %NULL
156 * @error: return location for error
158 * See g_spawn_async_with_pipes() for a full description; this function
159 * simply calls the g_spawn_async_with_pipes() without any pipes.
161 * You should call g_spawn_close_pid() on the returned child process
162 * reference when you don't need it any more.
164 * If you are writing a GTK+ application, and the program you are spawning is a
165 * graphical application too, then to ensure that the spawned program opens its
166 * windows on the right screen, you may want to use #GdkAppLaunchContext,
167 * #GAppLaunchcontext, or set the %DISPLAY environment variable.
169 * Note that the returned @child_pid on Windows is a handle to the child
170 * process and not its identifier. Process handles and process identifiers
171 * are different concepts on Windows.
173 * Returns: %TRUE on success, %FALSE if error is set
175 gboolean
176 g_spawn_async (const gchar *working_directory,
177 gchar **argv,
178 gchar **envp,
179 GSpawnFlags flags,
180 GSpawnChildSetupFunc child_setup,
181 gpointer user_data,
182 GPid *child_pid,
183 GError **error)
185 g_return_val_if_fail (argv != NULL, FALSE);
187 return g_spawn_async_with_pipes (working_directory,
188 argv, envp,
189 flags,
190 child_setup,
191 user_data,
192 child_pid,
193 NULL, NULL, NULL,
194 error);
197 /* Avoids a danger in threaded situations (calling close()
198 * on a file descriptor twice, and another thread has
199 * re-opened it since the first close)
201 static void
202 close_and_invalidate (gint *fd)
204 if (*fd < 0)
205 return;
206 else
208 (void) g_close (*fd, NULL);
209 *fd = -1;
213 /* Some versions of OS X define READ_OK in public headers */
214 #undef READ_OK
216 typedef enum
218 READ_FAILED = 0, /* FALSE */
219 READ_OK,
220 READ_EOF
221 } ReadResult;
223 static ReadResult
224 read_data (GString *str,
225 gint fd,
226 GError **error)
228 gssize bytes;
229 gchar buf[4096];
231 again:
232 bytes = read (fd, buf, 4096);
234 if (bytes == 0)
235 return READ_EOF;
236 else if (bytes > 0)
238 g_string_append_len (str, buf, bytes);
239 return READ_OK;
241 else if (errno == EINTR)
242 goto again;
243 else
245 int errsv = errno;
247 g_set_error (error,
248 G_SPAWN_ERROR,
249 G_SPAWN_ERROR_READ,
250 _("Failed to read data from child process (%s)"),
251 g_strerror (errsv));
253 return READ_FAILED;
258 * g_spawn_sync:
259 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's
260 * @argv: (array zero-terminated=1): child's argument vector
261 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's
262 * @flags: flags from #GSpawnFlags
263 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
264 * @user_data: (closure): user data for @child_setup
265 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output, or %NULL
266 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child error messages, or %NULL
267 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid(), or %NULL
268 * @error: return location for error, or %NULL
270 * Executes a child synchronously (waits for the child to exit before returning).
271 * All output from the child is stored in @standard_output and @standard_error,
272 * if those parameters are non-%NULL. Note that you must set the
273 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
274 * passing %NULL for @standard_output and @standard_error.
276 * If @exit_status is non-%NULL, the platform-specific exit status of
277 * the child is stored there; see the documentation of
278 * g_spawn_check_exit_status() for how to use and interpret this.
279 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
280 * @flags, and on POSIX platforms, the same restrictions as for
281 * g_child_watch_source_new() apply.
283 * If an error occurs, no data is returned in @standard_output,
284 * @standard_error, or @exit_status.
286 * This function calls g_spawn_async_with_pipes() internally; see that
287 * function for full details on the other parameters and details on
288 * how these functions work on Windows.
290 * Returns: %TRUE on success, %FALSE if an error was set
292 gboolean
293 g_spawn_sync (const gchar *working_directory,
294 gchar **argv,
295 gchar **envp,
296 GSpawnFlags flags,
297 GSpawnChildSetupFunc child_setup,
298 gpointer user_data,
299 gchar **standard_output,
300 gchar **standard_error,
301 gint *exit_status,
302 GError **error)
304 gint outpipe = -1;
305 gint errpipe = -1;
306 GPid pid;
307 fd_set fds;
308 gint ret;
309 GString *outstr = NULL;
310 GString *errstr = NULL;
311 gboolean failed;
312 gint status;
314 g_return_val_if_fail (argv != NULL, FALSE);
315 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
316 g_return_val_if_fail (standard_output == NULL ||
317 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
318 g_return_val_if_fail (standard_error == NULL ||
319 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
321 /* Just to ensure segfaults if callers try to use
322 * these when an error is reported.
324 if (standard_output)
325 *standard_output = NULL;
327 if (standard_error)
328 *standard_error = NULL;
330 if (!fork_exec_with_pipes (FALSE,
331 working_directory,
332 argv,
333 envp,
334 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
335 (flags & G_SPAWN_SEARCH_PATH) != 0,
336 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
337 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
338 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
339 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
340 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
341 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
342 child_setup,
343 user_data,
344 &pid,
345 NULL,
346 standard_output ? &outpipe : NULL,
347 standard_error ? &errpipe : NULL,
348 error))
349 return FALSE;
351 /* Read data from child. */
353 failed = FALSE;
355 if (outpipe >= 0)
357 outstr = g_string_new (NULL);
360 if (errpipe >= 0)
362 errstr = g_string_new (NULL);
365 /* Read data until we get EOF on both pipes. */
366 while (!failed &&
367 (outpipe >= 0 ||
368 errpipe >= 0))
370 ret = 0;
372 FD_ZERO (&fds);
373 if (outpipe >= 0)
374 FD_SET (outpipe, &fds);
375 if (errpipe >= 0)
376 FD_SET (errpipe, &fds);
378 ret = select (MAX (outpipe, errpipe) + 1,
379 &fds,
380 NULL, NULL,
381 NULL /* no timeout */);
383 if (ret < 0)
385 int errsv = errno;
387 if (errno == EINTR)
388 continue;
390 failed = TRUE;
392 g_set_error (error,
393 G_SPAWN_ERROR,
394 G_SPAWN_ERROR_READ,
395 _("Unexpected error in select() reading data from a child process (%s)"),
396 g_strerror (errsv));
398 break;
401 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
403 switch (read_data (outstr, outpipe, error))
405 case READ_FAILED:
406 failed = TRUE;
407 break;
408 case READ_EOF:
409 close_and_invalidate (&outpipe);
410 outpipe = -1;
411 break;
412 default:
413 break;
416 if (failed)
417 break;
420 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
422 switch (read_data (errstr, errpipe, error))
424 case READ_FAILED:
425 failed = TRUE;
426 break;
427 case READ_EOF:
428 close_and_invalidate (&errpipe);
429 errpipe = -1;
430 break;
431 default:
432 break;
435 if (failed)
436 break;
440 /* These should only be open still if we had an error. */
442 if (outpipe >= 0)
443 close_and_invalidate (&outpipe);
444 if (errpipe >= 0)
445 close_and_invalidate (&errpipe);
447 /* Wait for child to exit, even if we have
448 * an error pending.
450 again:
452 ret = waitpid (pid, &status, 0);
454 if (ret < 0)
456 if (errno == EINTR)
457 goto again;
458 else if (errno == ECHILD)
460 if (exit_status)
462 g_warning ("In call to g_spawn_sync(), exit status of a child process was requested but ECHILD was received by waitpid(). See the documentation of g_child_watch_source_new() for possible causes.");
464 else
466 /* We don't need the exit status. */
469 else
471 if (!failed) /* avoid error pileups */
473 int errsv = errno;
475 failed = TRUE;
477 g_set_error (error,
478 G_SPAWN_ERROR,
479 G_SPAWN_ERROR_READ,
480 _("Unexpected error in waitpid() (%s)"),
481 g_strerror (errsv));
486 if (failed)
488 if (outstr)
489 g_string_free (outstr, TRUE);
490 if (errstr)
491 g_string_free (errstr, TRUE);
493 return FALSE;
495 else
497 if (exit_status)
498 *exit_status = status;
500 if (standard_output)
501 *standard_output = g_string_free (outstr, FALSE);
503 if (standard_error)
504 *standard_error = g_string_free (errstr, FALSE);
506 return TRUE;
511 * g_spawn_async_with_pipes:
512 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
513 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
514 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
515 * @flags: flags from #GSpawnFlags
516 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
517 * @user_data: (closure): user data for @child_setup
518 * @child_pid: (out) (optional): return location for child process ID, or %NULL
519 * @standard_input: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
520 * @standard_output: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
521 * @standard_error: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
522 * @error: return location for error
524 * Executes a child program asynchronously (your program will not
525 * block waiting for the child to exit). The child program is
526 * specified by the only argument that must be provided, @argv.
527 * @argv should be a %NULL-terminated array of strings, to be passed
528 * as the argument vector for the child. The first string in @argv
529 * is of course the name of the program to execute. By default, the
530 * name of the program must be a full path. If @flags contains the
531 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is
532 * used to search for the executable. If @flags contains the
533 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from
534 * @envp is used to search for the executable. If both the
535 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags
536 * are set, the `PATH` variable from @envp takes precedence over
537 * the environment variable.
539 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
540 * used, then the program will be run from the current directory (or
541 * @working_directory, if specified); this might be unexpected or even
542 * dangerous in some cases when the current directory is world-writable.
544 * On Windows, note that all the string or string vector arguments to
545 * this function and the other g_spawn*() functions are in UTF-8, the
546 * GLib file name encoding. Unicode characters that are not part of
547 * the system codepage passed in these arguments will be correctly
548 * available in the spawned program only if it uses wide character API
549 * to retrieve its command line. For C programs built with Microsoft's
550 * tools it is enough to make the program have a wmain() instead of
551 * main(). wmain() has a wide character argument vector as parameter.
553 * At least currently, mingw doesn't support wmain(), so if you use
554 * mingw to develop the spawned program, it should call
555 * g_win32_get_command_line() to get arguments in UTF-8.
557 * On Windows the low-level child process creation API CreateProcess()
558 * doesn't use argument vectors, but a command line. The C runtime
559 * library's spawn*() family of functions (which g_spawn_async_with_pipes()
560 * eventually calls) paste the argument vector elements together into
561 * a command line, and the C runtime startup code does a corresponding
562 * reconstruction of an argument vector from the command line, to be
563 * passed to main(). Complications arise when you have argument vector
564 * elements that contain spaces of double quotes. The spawn*() functions
565 * don't do any quoting or escaping, but on the other hand the startup
566 * code does do unquoting and unescaping in order to enable receiving
567 * arguments with embedded spaces or double quotes. To work around this
568 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
569 * argument vector elements that need it before calling the C runtime
570 * spawn() function.
572 * The returned @child_pid on Windows is a handle to the child
573 * process, not its identifier. Process handles and process
574 * identifiers are different concepts on Windows.
576 * @envp is a %NULL-terminated array of strings, where each string
577 * has the form `KEY=VALUE`. This will become the child's environment.
578 * If @envp is %NULL, the child inherits its parent's environment.
580 * @flags should be the bitwise OR of any flags you want to affect the
581 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
582 * child will not automatically be reaped; you must use a child watch
583 * (g_child_watch_add()) to be notified about the death of the child process,
584 * otherwise it will stay around as a zombie process until this process exits.
585 * Eventually you must call g_spawn_close_pid() on the @child_pid, in order to
586 * free resources which may be associated with the child process. (On Unix,
587 * using a child watch is equivalent to calling waitpid() or handling
588 * the %SIGCHLD signal manually. On Windows, calling g_spawn_close_pid()
589 * is equivalent to calling CloseHandle() on the process handle returned
590 * in @child_pid). See g_child_watch_add().
592 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
593 * descriptors will be inherited by the child; otherwise all descriptors
594 * except stdin/stdout/stderr will be closed before calling exec() in
595 * the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
596 * absolute path, it will be looked for in the `PATH` environment
597 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
598 * absolute path, it will be looked for in the `PATH` variable from
599 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
600 * are used, the value from @envp takes precedence over the environment.
601 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
602 * will be discarded, instead of going to the same location as the parent's
603 * standard output. If you use this flag, @standard_output must be %NULL.
604 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
605 * will be discarded, instead of going to the same location as the parent's
606 * standard error. If you use this flag, @standard_error must be %NULL.
607 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
608 * standard input (by default, the child's standard input is attached to
609 * /dev/null). If you use this flag, @standard_input must be %NULL.
610 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
611 * the file to execute, while the remaining elements are the actual
612 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
613 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
615 * @child_setup and @user_data are a function and user data. On POSIX
616 * platforms, the function is called in the child after GLib has
617 * performed all the setup it plans to perform (including creating
618 * pipes, closing file descriptors, etc.) but before calling exec().
619 * That is, @child_setup is called just before calling exec() in the
620 * child. Obviously actions taken in this function will only affect
621 * the child, not the parent.
623 * On Windows, there is no separate fork() and exec() functionality.
624 * Child processes are created and run with a single API call,
625 * CreateProcess(). There is no sensible thing @child_setup
626 * could be used for on Windows so it is ignored and not called.
628 * If non-%NULL, @child_pid will on Unix be filled with the child's
629 * process ID. You can use the process ID to send signals to the child,
630 * or to use g_child_watch_add() (or waitpid()) if you specified the
631 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
632 * filled with a handle to the child process only if you specified the
633 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
634 * process using the Win32 API, for example wait for its termination
635 * with the WaitFor*() functions, or examine its exit code with
636 * GetExitCodeProcess(). You should close the handle with CloseHandle()
637 * or g_spawn_close_pid() when you no longer need it.
639 * If non-%NULL, the @standard_input, @standard_output, @standard_error
640 * locations will be filled with file descriptors for writing to the child's
641 * standard input or reading from its standard output or standard error.
642 * The caller of g_spawn_async_with_pipes() must close these file descriptors
643 * when they are no longer in use. If these parameters are %NULL, the
644 * corresponding pipe won't be created.
646 * If @standard_input is NULL, the child's standard input is attached to
647 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
649 * If @standard_error is NULL, the child's standard error goes to the same
650 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
651 * is set.
653 * If @standard_output is NULL, the child's standard output goes to the same
654 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
655 * is set.
657 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
658 * If an error is set, the function returns %FALSE. Errors are reported
659 * even if they occur in the child (for example if the executable in
660 * @argv[0] is not found). Typically the `message` field of returned
661 * errors should be displayed to users. Possible errors are those from
662 * the #G_SPAWN_ERROR domain.
664 * If an error occurs, @child_pid, @standard_input, @standard_output,
665 * and @standard_error will not be filled with valid values.
667 * If @child_pid is not %NULL and an error does not occur then the returned
668 * process reference must be closed using g_spawn_close_pid().
670 * If you are writing a GTK+ application, and the program you are spawning is a
671 * graphical application too, then to ensure that the spawned program opens its
672 * windows on the right screen, you may want to use #GdkAppLaunchContext,
673 * #GAppLaunchcontext, or set the %DISPLAY environment variable.
675 * Returns: %TRUE on success, %FALSE if an error was set
677 gboolean
678 g_spawn_async_with_pipes (const gchar *working_directory,
679 gchar **argv,
680 gchar **envp,
681 GSpawnFlags flags,
682 GSpawnChildSetupFunc child_setup,
683 gpointer user_data,
684 GPid *child_pid,
685 gint *standard_input,
686 gint *standard_output,
687 gint *standard_error,
688 GError **error)
690 g_return_val_if_fail (argv != NULL, FALSE);
691 g_return_val_if_fail (standard_output == NULL ||
692 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
693 g_return_val_if_fail (standard_error == NULL ||
694 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
695 /* can't inherit stdin if we have an input pipe. */
696 g_return_val_if_fail (standard_input == NULL ||
697 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
699 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
700 working_directory,
701 argv,
702 envp,
703 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
704 (flags & G_SPAWN_SEARCH_PATH) != 0,
705 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
706 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
707 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
708 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
709 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
710 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
711 child_setup,
712 user_data,
713 child_pid,
714 standard_input,
715 standard_output,
716 standard_error,
717 error);
721 * g_spawn_command_line_sync:
722 * @command_line: a command line
723 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output
724 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child errors
725 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid()
726 * @error: return location for errors
728 * A simple version of g_spawn_sync() with little-used parameters
729 * removed, taking a command line instead of an argument vector. See
730 * g_spawn_sync() for full details. @command_line will be parsed by
731 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
732 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
733 * implications, so consider using g_spawn_sync() directly if
734 * appropriate. Possible errors are those from g_spawn_sync() and those
735 * from g_shell_parse_argv().
737 * If @exit_status is non-%NULL, the platform-specific exit status of
738 * the child is stored there; see the documentation of
739 * g_spawn_check_exit_status() for how to use and interpret this.
741 * On Windows, please note the implications of g_shell_parse_argv()
742 * parsing @command_line. Parsing is done according to Unix shell rules, not
743 * Windows command interpreter rules.
744 * Space is a separator, and backslashes are
745 * special. Thus you cannot simply pass a @command_line containing
746 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
747 * the backslashes will be eaten, and the space will act as a
748 * separator. You need to enclose such paths with single quotes, like
749 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
751 * Returns: %TRUE on success, %FALSE if an error was set
753 gboolean
754 g_spawn_command_line_sync (const gchar *command_line,
755 gchar **standard_output,
756 gchar **standard_error,
757 gint *exit_status,
758 GError **error)
760 gboolean retval;
761 gchar **argv = NULL;
763 g_return_val_if_fail (command_line != NULL, FALSE);
765 if (!g_shell_parse_argv (command_line,
766 NULL, &argv,
767 error))
768 return FALSE;
770 retval = g_spawn_sync (NULL,
771 argv,
772 NULL,
773 G_SPAWN_SEARCH_PATH,
774 NULL,
775 NULL,
776 standard_output,
777 standard_error,
778 exit_status,
779 error);
780 g_strfreev (argv);
782 return retval;
786 * g_spawn_command_line_async:
787 * @command_line: a command line
788 * @error: return location for errors
790 * A simple version of g_spawn_async() that parses a command line with
791 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
792 * command line in the background. Unlike g_spawn_async(), the
793 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
794 * that %G_SPAWN_SEARCH_PATH can have security implications, so
795 * consider using g_spawn_async() directly if appropriate. Possible
796 * errors are those from g_shell_parse_argv() and g_spawn_async().
798 * The same concerns on Windows apply as for g_spawn_command_line_sync().
800 * Returns: %TRUE on success, %FALSE if error is set
802 gboolean
803 g_spawn_command_line_async (const gchar *command_line,
804 GError **error)
806 gboolean retval;
807 gchar **argv = NULL;
809 g_return_val_if_fail (command_line != NULL, FALSE);
811 if (!g_shell_parse_argv (command_line,
812 NULL, &argv,
813 error))
814 return FALSE;
816 retval = g_spawn_async (NULL,
817 argv,
818 NULL,
819 G_SPAWN_SEARCH_PATH,
820 NULL,
821 NULL,
822 NULL,
823 error);
824 g_strfreev (argv);
826 return retval;
830 * g_spawn_check_exit_status:
831 * @exit_status: An exit code as returned from g_spawn_sync()
832 * @error: a #GError
834 * Set @error if @exit_status indicates the child exited abnormally
835 * (e.g. with a nonzero exit code, or via a fatal signal).
837 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
838 * exit status for subprocesses encoded in a platform-specific way.
839 * On Unix, this is guaranteed to be in the same format waitpid() returns,
840 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
842 * Prior to the introduction of this function in GLib 2.34, interpreting
843 * @exit_status required use of platform-specific APIs, which is problematic
844 * for software using GLib as a cross-platform layer.
846 * Additionally, many programs simply want to determine whether or not
847 * the child exited successfully, and either propagate a #GError or
848 * print a message to standard error. In that common case, this function
849 * can be used. Note that the error message in @error will contain
850 * human-readable information about the exit status.
852 * The @domain and @code of @error have special semantics in the case
853 * where the process has an "exit code", as opposed to being killed by
854 * a signal. On Unix, this happens if WIFEXITED() would be true of
855 * @exit_status. On Windows, it is always the case.
857 * The special semantics are that the actual exit code will be the
858 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
859 * This allows you to differentiate between different exit codes.
861 * If the process was terminated by some means other than an exit
862 * status, the domain will be %G_SPAWN_ERROR, and the code will be
863 * %G_SPAWN_ERROR_FAILED.
865 * This function just offers convenience; you can of course also check
866 * the available platform via a macro such as %G_OS_UNIX, and use
867 * WIFEXITED() and WEXITSTATUS() on @exit_status directly. Do not attempt
868 * to scan or parse the error message string; it may be translated and/or
869 * change in future versions of GLib.
871 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
872 * @error will be set)
874 * Since: 2.34
876 gboolean
877 g_spawn_check_exit_status (gint exit_status,
878 GError **error)
880 gboolean ret = FALSE;
882 if (WIFEXITED (exit_status))
884 if (WEXITSTATUS (exit_status) != 0)
886 g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (exit_status),
887 _("Child process exited with code %ld"),
888 (long) WEXITSTATUS (exit_status));
889 goto out;
892 else if (WIFSIGNALED (exit_status))
894 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
895 _("Child process killed by signal %ld"),
896 (long) WTERMSIG (exit_status));
897 goto out;
899 else if (WIFSTOPPED (exit_status))
901 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
902 _("Child process stopped by signal %ld"),
903 (long) WSTOPSIG (exit_status));
904 goto out;
906 else
908 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
909 _("Child process exited abnormally"));
910 goto out;
913 ret = TRUE;
914 out:
915 return ret;
918 static gint
919 exec_err_to_g_error (gint en)
921 switch (en)
923 #ifdef EACCES
924 case EACCES:
925 return G_SPAWN_ERROR_ACCES;
926 break;
927 #endif
929 #ifdef EPERM
930 case EPERM:
931 return G_SPAWN_ERROR_PERM;
932 break;
933 #endif
935 #ifdef E2BIG
936 case E2BIG:
937 return G_SPAWN_ERROR_TOO_BIG;
938 break;
939 #endif
941 #ifdef ENOEXEC
942 case ENOEXEC:
943 return G_SPAWN_ERROR_NOEXEC;
944 break;
945 #endif
947 #ifdef ENAMETOOLONG
948 case ENAMETOOLONG:
949 return G_SPAWN_ERROR_NAMETOOLONG;
950 break;
951 #endif
953 #ifdef ENOENT
954 case ENOENT:
955 return G_SPAWN_ERROR_NOENT;
956 break;
957 #endif
959 #ifdef ENOMEM
960 case ENOMEM:
961 return G_SPAWN_ERROR_NOMEM;
962 break;
963 #endif
965 #ifdef ENOTDIR
966 case ENOTDIR:
967 return G_SPAWN_ERROR_NOTDIR;
968 break;
969 #endif
971 #ifdef ELOOP
972 case ELOOP:
973 return G_SPAWN_ERROR_LOOP;
974 break;
975 #endif
977 #ifdef ETXTBUSY
978 case ETXTBUSY:
979 return G_SPAWN_ERROR_TXTBUSY;
980 break;
981 #endif
983 #ifdef EIO
984 case EIO:
985 return G_SPAWN_ERROR_IO;
986 break;
987 #endif
989 #ifdef ENFILE
990 case ENFILE:
991 return G_SPAWN_ERROR_NFILE;
992 break;
993 #endif
995 #ifdef EMFILE
996 case EMFILE:
997 return G_SPAWN_ERROR_MFILE;
998 break;
999 #endif
1001 #ifdef EINVAL
1002 case EINVAL:
1003 return G_SPAWN_ERROR_INVAL;
1004 break;
1005 #endif
1007 #ifdef EISDIR
1008 case EISDIR:
1009 return G_SPAWN_ERROR_ISDIR;
1010 break;
1011 #endif
1013 #ifdef ELIBBAD
1014 case ELIBBAD:
1015 return G_SPAWN_ERROR_LIBBAD;
1016 break;
1017 #endif
1019 default:
1020 return G_SPAWN_ERROR_FAILED;
1021 break;
1025 static gssize
1026 write_all (gint fd, gconstpointer vbuf, gsize to_write)
1028 gchar *buf = (gchar *) vbuf;
1030 while (to_write > 0)
1032 gssize count = write (fd, buf, to_write);
1033 if (count < 0)
1035 if (errno != EINTR)
1036 return FALSE;
1038 else
1040 to_write -= count;
1041 buf += count;
1045 return TRUE;
1048 G_GNUC_NORETURN
1049 static void
1050 write_err_and_exit (gint fd, gint msg)
1052 gint en = errno;
1054 write_all (fd, &msg, sizeof(msg));
1055 write_all (fd, &en, sizeof(en));
1057 _exit (1);
1060 static int
1061 set_cloexec (void *data, gint fd)
1063 if (fd >= GPOINTER_TO_INT (data))
1064 fcntl (fd, F_SETFD, FD_CLOEXEC);
1066 return 0;
1069 #ifndef HAVE_FDWALK
1070 static int
1071 fdwalk (int (*cb)(void *data, int fd), void *data)
1073 gint open_max;
1074 gint fd;
1075 gint res = 0;
1077 #ifdef HAVE_SYS_RESOURCE_H
1078 struct rlimit rl;
1079 #endif
1081 #ifdef __linux__
1082 DIR *d;
1084 if ((d = opendir("/proc/self/fd"))) {
1085 struct dirent *de;
1087 while ((de = readdir(d))) {
1088 glong l;
1089 gchar *e = NULL;
1091 if (de->d_name[0] == '.')
1092 continue;
1094 errno = 0;
1095 l = strtol(de->d_name, &e, 10);
1096 if (errno != 0 || !e || *e)
1097 continue;
1099 fd = (gint) l;
1101 if ((glong) fd != l)
1102 continue;
1104 if (fd == dirfd(d))
1105 continue;
1107 if ((res = cb (data, fd)) != 0)
1108 break;
1111 closedir(d);
1112 return res;
1115 /* If /proc is not mounted or not accessible we fall back to the old
1116 * rlimit trick */
1118 #endif
1120 #ifdef HAVE_SYS_RESOURCE_H
1122 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1123 open_max = rl.rlim_max;
1124 else
1125 #endif
1126 open_max = sysconf (_SC_OPEN_MAX);
1128 for (fd = 0; fd < open_max; fd++)
1129 if ((res = cb (data, fd)) != 0)
1130 break;
1132 return res;
1134 #endif
1136 static gint
1137 sane_dup2 (gint fd1, gint fd2)
1139 gint ret;
1141 retry:
1142 ret = dup2 (fd1, fd2);
1143 if (ret < 0 && errno == EINTR)
1144 goto retry;
1146 return ret;
1149 static gint
1150 sane_open (const char *path, gint mode)
1152 gint ret;
1154 retry:
1155 ret = open (path, mode);
1156 if (ret < 0 && errno == EINTR)
1157 goto retry;
1159 return ret;
1162 enum
1164 CHILD_CHDIR_FAILED,
1165 CHILD_EXEC_FAILED,
1166 CHILD_DUP2_FAILED,
1167 CHILD_FORK_FAILED
1170 static void
1171 do_exec (gint child_err_report_fd,
1172 gint stdin_fd,
1173 gint stdout_fd,
1174 gint stderr_fd,
1175 const gchar *working_directory,
1176 gchar **argv,
1177 gchar **envp,
1178 gboolean close_descriptors,
1179 gboolean search_path,
1180 gboolean search_path_from_envp,
1181 gboolean stdout_to_null,
1182 gboolean stderr_to_null,
1183 gboolean child_inherits_stdin,
1184 gboolean file_and_argv_zero,
1185 GSpawnChildSetupFunc child_setup,
1186 gpointer user_data)
1188 if (working_directory && chdir (working_directory) < 0)
1189 write_err_and_exit (child_err_report_fd,
1190 CHILD_CHDIR_FAILED);
1192 /* Close all file descriptors but stdin stdout and stderr as
1193 * soon as we exec. Note that this includes
1194 * child_err_report_fd, which keeps the parent from blocking
1195 * forever on the other end of that pipe.
1197 if (close_descriptors)
1199 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1201 else
1203 /* We need to do child_err_report_fd anyway */
1204 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1207 /* Redirect pipes as required */
1209 if (stdin_fd >= 0)
1211 /* dup2 can't actually fail here I don't think */
1213 if (sane_dup2 (stdin_fd, 0) < 0)
1214 write_err_and_exit (child_err_report_fd,
1215 CHILD_DUP2_FAILED);
1217 /* ignore this if it doesn't work */
1218 close_and_invalidate (&stdin_fd);
1220 else if (!child_inherits_stdin)
1222 /* Keep process from blocking on a read of stdin */
1223 gint read_null = open ("/dev/null", O_RDONLY);
1224 g_assert (read_null != -1);
1225 sane_dup2 (read_null, 0);
1226 close_and_invalidate (&read_null);
1229 if (stdout_fd >= 0)
1231 /* dup2 can't actually fail here I don't think */
1233 if (sane_dup2 (stdout_fd, 1) < 0)
1234 write_err_and_exit (child_err_report_fd,
1235 CHILD_DUP2_FAILED);
1237 /* ignore this if it doesn't work */
1238 close_and_invalidate (&stdout_fd);
1240 else if (stdout_to_null)
1242 gint write_null = sane_open ("/dev/null", O_WRONLY);
1243 g_assert (write_null != -1);
1244 sane_dup2 (write_null, 1);
1245 close_and_invalidate (&write_null);
1248 if (stderr_fd >= 0)
1250 /* dup2 can't actually fail here I don't think */
1252 if (sane_dup2 (stderr_fd, 2) < 0)
1253 write_err_and_exit (child_err_report_fd,
1254 CHILD_DUP2_FAILED);
1256 /* ignore this if it doesn't work */
1257 close_and_invalidate (&stderr_fd);
1259 else if (stderr_to_null)
1261 gint write_null = sane_open ("/dev/null", O_WRONLY);
1262 sane_dup2 (write_null, 2);
1263 close_and_invalidate (&write_null);
1266 /* Call user function just before we exec */
1267 if (child_setup)
1269 (* child_setup) (user_data);
1272 g_execute (argv[0],
1273 file_and_argv_zero ? argv + 1 : argv,
1274 envp, search_path, search_path_from_envp);
1276 /* Exec failed */
1277 write_err_and_exit (child_err_report_fd,
1278 CHILD_EXEC_FAILED);
1281 static gboolean
1282 read_ints (int fd,
1283 gint* buf,
1284 gint n_ints_in_buf,
1285 gint *n_ints_read,
1286 GError **error)
1288 gsize bytes = 0;
1290 while (TRUE)
1292 gssize chunk;
1294 if (bytes >= sizeof(gint)*2)
1295 break; /* give up, who knows what happened, should not be
1296 * possible.
1299 again:
1300 chunk = read (fd,
1301 ((gchar*)buf) + bytes,
1302 sizeof(gint) * n_ints_in_buf - bytes);
1303 if (chunk < 0 && errno == EINTR)
1304 goto again;
1306 if (chunk < 0)
1308 int errsv = errno;
1310 /* Some weird shit happened, bail out */
1311 g_set_error (error,
1312 G_SPAWN_ERROR,
1313 G_SPAWN_ERROR_FAILED,
1314 _("Failed to read from child pipe (%s)"),
1315 g_strerror (errsv));
1317 return FALSE;
1319 else if (chunk == 0)
1320 break; /* EOF */
1321 else /* chunk > 0 */
1322 bytes += chunk;
1325 *n_ints_read = (gint)(bytes / sizeof(gint));
1327 return TRUE;
1330 static gboolean
1331 fork_exec_with_pipes (gboolean intermediate_child,
1332 const gchar *working_directory,
1333 gchar **argv,
1334 gchar **envp,
1335 gboolean close_descriptors,
1336 gboolean search_path,
1337 gboolean search_path_from_envp,
1338 gboolean stdout_to_null,
1339 gboolean stderr_to_null,
1340 gboolean child_inherits_stdin,
1341 gboolean file_and_argv_zero,
1342 gboolean cloexec_pipes,
1343 GSpawnChildSetupFunc child_setup,
1344 gpointer user_data,
1345 GPid *child_pid,
1346 gint *standard_input,
1347 gint *standard_output,
1348 gint *standard_error,
1349 GError **error)
1351 GPid pid = -1;
1352 gint stdin_pipe[2] = { -1, -1 };
1353 gint stdout_pipe[2] = { -1, -1 };
1354 gint stderr_pipe[2] = { -1, -1 };
1355 gint child_err_report_pipe[2] = { -1, -1 };
1356 gint child_pid_report_pipe[2] = { -1, -1 };
1357 guint pipe_flags = cloexec_pipes ? FD_CLOEXEC : 0;
1358 gint status;
1360 if (!g_unix_open_pipe (child_err_report_pipe, pipe_flags, error))
1361 return FALSE;
1363 if (intermediate_child && !g_unix_open_pipe (child_pid_report_pipe, pipe_flags, error))
1364 goto cleanup_and_fail;
1366 if (standard_input && !g_unix_open_pipe (stdin_pipe, pipe_flags, error))
1367 goto cleanup_and_fail;
1369 if (standard_output && !g_unix_open_pipe (stdout_pipe, pipe_flags, error))
1370 goto cleanup_and_fail;
1372 if (standard_error && !g_unix_open_pipe (stderr_pipe, FD_CLOEXEC, error))
1373 goto cleanup_and_fail;
1375 pid = fork ();
1377 if (pid < 0)
1379 int errsv = errno;
1381 g_set_error (error,
1382 G_SPAWN_ERROR,
1383 G_SPAWN_ERROR_FORK,
1384 _("Failed to fork (%s)"),
1385 g_strerror (errsv));
1387 goto cleanup_and_fail;
1389 else if (pid == 0)
1391 /* Immediate child. This may or may not be the child that
1392 * actually execs the new process.
1395 /* Reset some signal handlers that we may use */
1396 signal (SIGCHLD, SIG_DFL);
1397 signal (SIGINT, SIG_DFL);
1398 signal (SIGTERM, SIG_DFL);
1399 signal (SIGHUP, SIG_DFL);
1401 /* Be sure we crash if the parent exits
1402 * and we write to the err_report_pipe
1404 signal (SIGPIPE, SIG_DFL);
1406 /* Close the parent's end of the pipes;
1407 * not needed in the close_descriptors case,
1408 * though
1410 close_and_invalidate (&child_err_report_pipe[0]);
1411 close_and_invalidate (&child_pid_report_pipe[0]);
1412 close_and_invalidate (&stdin_pipe[1]);
1413 close_and_invalidate (&stdout_pipe[0]);
1414 close_and_invalidate (&stderr_pipe[0]);
1416 if (intermediate_child)
1418 /* We need to fork an intermediate child that launches the
1419 * final child. The purpose of the intermediate child
1420 * is to exit, so we can waitpid() it immediately.
1421 * Then the grandchild will not become a zombie.
1423 GPid grandchild_pid;
1425 grandchild_pid = fork ();
1427 if (grandchild_pid < 0)
1429 /* report -1 as child PID */
1430 write_all (child_pid_report_pipe[1], &grandchild_pid,
1431 sizeof(grandchild_pid));
1433 write_err_and_exit (child_err_report_pipe[1],
1434 CHILD_FORK_FAILED);
1436 else if (grandchild_pid == 0)
1438 close_and_invalidate (&child_pid_report_pipe[1]);
1439 do_exec (child_err_report_pipe[1],
1440 stdin_pipe[0],
1441 stdout_pipe[1],
1442 stderr_pipe[1],
1443 working_directory,
1444 argv,
1445 envp,
1446 close_descriptors,
1447 search_path,
1448 search_path_from_envp,
1449 stdout_to_null,
1450 stderr_to_null,
1451 child_inherits_stdin,
1452 file_and_argv_zero,
1453 child_setup,
1454 user_data);
1456 else
1458 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1459 close_and_invalidate (&child_pid_report_pipe[1]);
1461 _exit (0);
1464 else
1466 /* Just run the child.
1469 do_exec (child_err_report_pipe[1],
1470 stdin_pipe[0],
1471 stdout_pipe[1],
1472 stderr_pipe[1],
1473 working_directory,
1474 argv,
1475 envp,
1476 close_descriptors,
1477 search_path,
1478 search_path_from_envp,
1479 stdout_to_null,
1480 stderr_to_null,
1481 child_inherits_stdin,
1482 file_and_argv_zero,
1483 child_setup,
1484 user_data);
1487 else
1489 /* Parent */
1491 gint buf[2];
1492 gint n_ints = 0;
1494 /* Close the uncared-about ends of the pipes */
1495 close_and_invalidate (&child_err_report_pipe[1]);
1496 close_and_invalidate (&child_pid_report_pipe[1]);
1497 close_and_invalidate (&stdin_pipe[0]);
1498 close_and_invalidate (&stdout_pipe[1]);
1499 close_and_invalidate (&stderr_pipe[1]);
1501 /* If we had an intermediate child, reap it */
1502 if (intermediate_child)
1504 wait_again:
1505 if (waitpid (pid, &status, 0) < 0)
1507 if (errno == EINTR)
1508 goto wait_again;
1509 else if (errno == ECHILD)
1510 ; /* do nothing, child already reaped */
1511 else
1512 g_warning ("waitpid() should not fail in "
1513 "'fork_exec_with_pipes'");
1518 if (!read_ints (child_err_report_pipe[0],
1519 buf, 2, &n_ints,
1520 error))
1521 goto cleanup_and_fail;
1523 if (n_ints >= 2)
1525 /* Error from the child. */
1527 switch (buf[0])
1529 case CHILD_CHDIR_FAILED:
1530 g_set_error (error,
1531 G_SPAWN_ERROR,
1532 G_SPAWN_ERROR_CHDIR,
1533 _("Failed to change to directory “%s” (%s)"),
1534 working_directory,
1535 g_strerror (buf[1]));
1537 break;
1539 case CHILD_EXEC_FAILED:
1540 g_set_error (error,
1541 G_SPAWN_ERROR,
1542 exec_err_to_g_error (buf[1]),
1543 _("Failed to execute child process “%s” (%s)"),
1544 argv[0],
1545 g_strerror (buf[1]));
1547 break;
1549 case CHILD_DUP2_FAILED:
1550 g_set_error (error,
1551 G_SPAWN_ERROR,
1552 G_SPAWN_ERROR_FAILED,
1553 _("Failed to redirect output or input of child process (%s)"),
1554 g_strerror (buf[1]));
1556 break;
1558 case CHILD_FORK_FAILED:
1559 g_set_error (error,
1560 G_SPAWN_ERROR,
1561 G_SPAWN_ERROR_FORK,
1562 _("Failed to fork child process (%s)"),
1563 g_strerror (buf[1]));
1564 break;
1566 default:
1567 g_set_error (error,
1568 G_SPAWN_ERROR,
1569 G_SPAWN_ERROR_FAILED,
1570 _("Unknown error executing child process “%s”"),
1571 argv[0]);
1572 break;
1575 goto cleanup_and_fail;
1578 /* Get child pid from intermediate child pipe. */
1579 if (intermediate_child)
1581 n_ints = 0;
1583 if (!read_ints (child_pid_report_pipe[0],
1584 buf, 1, &n_ints, error))
1585 goto cleanup_and_fail;
1587 if (n_ints < 1)
1589 int errsv = errno;
1591 g_set_error (error,
1592 G_SPAWN_ERROR,
1593 G_SPAWN_ERROR_FAILED,
1594 _("Failed to read enough data from child pid pipe (%s)"),
1595 g_strerror (errsv));
1596 goto cleanup_and_fail;
1598 else
1600 /* we have the child pid */
1601 pid = buf[0];
1605 /* Success against all odds! return the information */
1606 close_and_invalidate (&child_err_report_pipe[0]);
1607 close_and_invalidate (&child_pid_report_pipe[0]);
1609 if (child_pid)
1610 *child_pid = pid;
1612 if (standard_input)
1613 *standard_input = stdin_pipe[1];
1614 if (standard_output)
1615 *standard_output = stdout_pipe[0];
1616 if (standard_error)
1617 *standard_error = stderr_pipe[0];
1619 return TRUE;
1622 cleanup_and_fail:
1624 /* There was an error from the Child, reap the child to avoid it being
1625 a zombie.
1628 if (pid > 0)
1630 wait_failed:
1631 if (waitpid (pid, NULL, 0) < 0)
1633 if (errno == EINTR)
1634 goto wait_failed;
1635 else if (errno == ECHILD)
1636 ; /* do nothing, child already reaped */
1637 else
1638 g_warning ("waitpid() should not fail in "
1639 "'fork_exec_with_pipes'");
1643 close_and_invalidate (&child_err_report_pipe[0]);
1644 close_and_invalidate (&child_err_report_pipe[1]);
1645 close_and_invalidate (&child_pid_report_pipe[0]);
1646 close_and_invalidate (&child_pid_report_pipe[1]);
1647 close_and_invalidate (&stdin_pipe[0]);
1648 close_and_invalidate (&stdin_pipe[1]);
1649 close_and_invalidate (&stdout_pipe[0]);
1650 close_and_invalidate (&stdout_pipe[1]);
1651 close_and_invalidate (&stderr_pipe[0]);
1652 close_and_invalidate (&stderr_pipe[1]);
1654 return FALSE;
1657 /* Based on execvp from GNU C Library */
1659 static void
1660 script_execute (const gchar *file,
1661 gchar **argv,
1662 gchar **envp)
1664 /* Count the arguments. */
1665 int argc = 0;
1666 while (argv[argc])
1667 ++argc;
1669 /* Construct an argument list for the shell. */
1671 gchar **new_argv;
1673 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1675 new_argv[0] = (char *) "/bin/sh";
1676 new_argv[1] = (char *) file;
1677 while (argc > 0)
1679 new_argv[argc + 1] = argv[argc];
1680 --argc;
1683 /* Execute the shell. */
1684 if (envp)
1685 execve (new_argv[0], new_argv, envp);
1686 else
1687 execv (new_argv[0], new_argv);
1689 g_free (new_argv);
1693 static gchar*
1694 my_strchrnul (const gchar *str, gchar c)
1696 gchar *p = (gchar*) str;
1697 while (*p && (*p != c))
1698 ++p;
1700 return p;
1703 static gint
1704 g_execute (const gchar *file,
1705 gchar **argv,
1706 gchar **envp,
1707 gboolean search_path,
1708 gboolean search_path_from_envp)
1710 if (*file == '\0')
1712 /* We check the simple case first. */
1713 errno = ENOENT;
1714 return -1;
1717 if (!(search_path || search_path_from_envp) || strchr (file, '/') != NULL)
1719 /* Don't search when it contains a slash. */
1720 if (envp)
1721 execve (file, argv, envp);
1722 else
1723 execv (file, argv);
1725 if (errno == ENOEXEC)
1726 script_execute (file, argv, envp);
1728 else
1730 gboolean got_eacces = 0;
1731 const gchar *path, *p;
1732 gchar *name, *freeme;
1733 gsize len;
1734 gsize pathlen;
1736 path = NULL;
1737 if (search_path_from_envp)
1738 path = g_environ_getenv (envp, "PATH");
1739 if (search_path && path == NULL)
1740 path = g_getenv ("PATH");
1742 if (path == NULL)
1744 /* There is no 'PATH' in the environment. The default
1745 * search path in libc is the current directory followed by
1746 * the path 'confstr' returns for '_CS_PATH'.
1749 /* In GLib we put . last, for security, and don't use the
1750 * unportable confstr(); UNIX98 does not actually specify
1751 * what to search if PATH is unset. POSIX may, dunno.
1754 path = "/bin:/usr/bin:.";
1757 len = strlen (file) + 1;
1758 pathlen = strlen (path);
1759 freeme = name = g_malloc (pathlen + len + 1);
1761 /* Copy the file name at the top, including '\0' */
1762 memcpy (name + pathlen + 1, file, len);
1763 name = name + pathlen;
1764 /* And add the slash before the filename */
1765 *name = '/';
1767 p = path;
1770 char *startp;
1772 path = p;
1773 p = my_strchrnul (path, ':');
1775 if (p == path)
1776 /* Two adjacent colons, or a colon at the beginning or the end
1777 * of 'PATH' means to search the current directory.
1779 startp = name + 1;
1780 else
1781 startp = memcpy (name - (p - path), path, p - path);
1783 /* Try to execute this name. If it works, execv will not return. */
1784 if (envp)
1785 execve (startp, argv, envp);
1786 else
1787 execv (startp, argv);
1789 if (errno == ENOEXEC)
1790 script_execute (startp, argv, envp);
1792 switch (errno)
1794 case EACCES:
1795 /* Record the we got a 'Permission denied' error. If we end
1796 * up finding no executable we can use, we want to diagnose
1797 * that we did find one but were denied access.
1799 got_eacces = TRUE;
1801 /* FALL THRU */
1803 case ENOENT:
1804 #ifdef ESTALE
1805 case ESTALE:
1806 #endif
1807 #ifdef ENOTDIR
1808 case ENOTDIR:
1809 #endif
1810 /* Those errors indicate the file is missing or not executable
1811 * by us, in which case we want to just try the next path
1812 * directory.
1814 break;
1816 case ENODEV:
1817 case ETIMEDOUT:
1818 /* Some strange filesystems like AFS return even
1819 * stranger error numbers. They cannot reasonably mean anything
1820 * else so ignore those, too.
1822 break;
1824 default:
1825 /* Some other error means we found an executable file, but
1826 * something went wrong executing it; return the error to our
1827 * caller.
1829 g_free (freeme);
1830 return -1;
1833 while (*p++ != '\0');
1835 /* We tried every element and none of them worked. */
1836 if (got_eacces)
1837 /* At least one failure was due to permissions, so report that
1838 * error.
1840 errno = EACCES;
1842 g_free (freeme);
1845 /* Return the error from the last attempt (probably ENOENT). */
1846 return -1;
1850 * g_spawn_close_pid:
1851 * @pid: The process reference to close
1853 * On some platforms, notably Windows, the #GPid type represents a resource
1854 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1855 * is provided for this purpose. It should be used on all platforms, even
1856 * though it doesn't do anything under UNIX.
1858 void
1859 g_spawn_close_pid (GPid pid)