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.
26 #include <sys/types.h>
33 #include <stdlib.h> /* for fdwalk */
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 */
49 #include "gstrfuncs.h"
50 #include "gtestutils.h"
54 static gint g_execute (const gchar *file,
57 gboolean search_path);
59 static gboolean make_pipe (gint p[2],
61 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
62 const gchar *working_directory,
65 gboolean close_descriptors,
67 gboolean stdout_to_null,
68 gboolean stderr_to_null,
69 gboolean child_inherits_stdin,
70 gboolean file_and_argv_zero,
71 GSpawnChildSetupFunc child_setup,
75 gint *standard_output,
80 g_spawn_error_quark (void)
82 return g_quark_from_static_string ("g-exec-error-quark");
87 * @working_directory: child's current working directory, or %NULL to inherit parent's
88 * @argv: child's argument vector
89 * @envp: child's environment, or %NULL to inherit parent's
90 * @flags: flags from #GSpawnFlags
91 * @child_setup: function to run in the child just before exec()
92 * @user_data: user data for @child_setup
93 * @child_pid: return location for child process reference, or %NULL
94 * @error: return location for error
96 * See g_spawn_async_with_pipes() for a full description; this function
97 * simply calls the g_spawn_async_with_pipes() without any pipes.
99 * You should call g_spawn_close_pid() on the returned child process
100 * reference when you don't need it any more.
103 * If you are writing a GTK+ application, and the program you
104 * are spawning is a graphical application, too, then you may
105 * want to use gdk_spawn_on_screen() instead to ensure that
106 * the spawned program opens its windows on the right screen.
109 * <note><para> Note that the returned @child_pid on Windows is a
110 * handle to the child process and not its identifier. Process handles
111 * and process identifiers are different concepts on Windows.
114 * Return value: %TRUE on success, %FALSE if error is set
117 g_spawn_async (const gchar *working_directory,
121 GSpawnChildSetupFunc child_setup,
126 g_return_val_if_fail (argv != NULL, FALSE);
128 return g_spawn_async_with_pipes (working_directory,
138 /* Avoids a danger in threaded situations (calling close()
139 * on a file descriptor twice, and another thread has
140 * re-opened it since the first close)
143 close_and_invalidate (gint *fd)
158 /* Some versions of OS X define READ_OK in public headers */
163 READ_FAILED = 0, /* FALSE */
169 read_data (GString *str,
178 bytes = read (fd, buf, 4096);
184 g_string_append_len (str, buf, bytes);
187 else if (bytes < 0 && errno == EINTR)
196 _("Failed to read data from child process (%s)"),
207 * @working_directory: child's current working directory, or %NULL to inherit parent's
208 * @argv: child's argument vector
209 * @envp: child's environment, or %NULL to inherit parent's
210 * @flags: flags from #GSpawnFlags
211 * @child_setup: function to run in the child just before exec()
212 * @user_data: user data for @child_setup
213 * @standard_output: return location for child output, or %NULL
214 * @standard_error: return location for child error messages, or %NULL
215 * @exit_status: return location for child exit status, as returned by waitpid(), or %NULL
216 * @error: return location for error, or %NULL
218 * Executes a child synchronously (waits for the child to exit before returning).
219 * All output from the child is stored in @standard_output and @standard_error,
220 * if those parameters are non-%NULL. Note that you must set the
221 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
222 * passing %NULL for @standard_output and @standard_error.
223 * If @exit_status is non-%NULL, the exit status of the child is stored
224 * there as it would be returned by waitpid(); standard UNIX macros such
225 * as WIFEXITED() and WEXITSTATUS() must be used to evaluate the exit status.
226 * Note that this function call waitpid() even if @exit_status is %NULL, and
227 * does not accept the %G_SPAWN_DO_NOT_REAP_CHILD flag.
228 * If an error occurs, no data is returned in @standard_output,
229 * @standard_error, or @exit_status.
231 * This function calls g_spawn_async_with_pipes() internally; see that
232 * function for full details on the other parameters and details on
233 * how these functions work on Windows.
235 * Return value: %TRUE on success, %FALSE if an error was set.
238 g_spawn_sync (const gchar *working_directory,
242 GSpawnChildSetupFunc child_setup,
244 gchar **standard_output,
245 gchar **standard_error,
254 GString *outstr = NULL;
255 GString *errstr = NULL;
259 g_return_val_if_fail (argv != NULL, FALSE);
260 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
261 g_return_val_if_fail (standard_output == NULL ||
262 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
263 g_return_val_if_fail (standard_error == NULL ||
264 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
266 /* Just to ensure segfaults if callers try to use
267 * these when an error is reported.
270 *standard_output = NULL;
273 *standard_error = NULL;
275 if (!fork_exec_with_pipes (FALSE,
279 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
280 (flags & G_SPAWN_SEARCH_PATH) != 0,
281 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
282 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
283 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
284 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
289 standard_output ? &outpipe : NULL,
290 standard_error ? &errpipe : NULL,
294 /* Read data from child. */
300 outstr = g_string_new (NULL);
305 errstr = g_string_new (NULL);
308 /* Read data until we get EOF on both pipes. */
317 FD_SET (outpipe, &fds);
319 FD_SET (errpipe, &fds);
321 ret = select (MAX (outpipe, errpipe) + 1,
324 NULL /* no timeout */);
326 if (ret < 0 && errno != EINTR)
335 _("Unexpected error in select() reading data from a child process (%s)"),
341 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
343 switch (read_data (outstr, outpipe, error))
349 close_and_invalidate (&outpipe);
360 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
362 switch (read_data (errstr, errpipe, error))
368 close_and_invalidate (&errpipe);
380 /* These should only be open still if we had an error. */
383 close_and_invalidate (&outpipe);
385 close_and_invalidate (&errpipe);
387 /* Wait for child to exit, even if we have
392 ret = waitpid (pid, &status, 0);
398 else if (errno == ECHILD)
402 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.");
406 /* We don't need the exit status. */
411 if (!failed) /* avoid error pileups */
420 _("Unexpected error in waitpid() (%s)"),
429 g_string_free (outstr, TRUE);
431 g_string_free (errstr, TRUE);
438 *exit_status = status;
441 *standard_output = g_string_free (outstr, FALSE);
444 *standard_error = g_string_free (errstr, FALSE);
451 * g_spawn_async_with_pipes:
452 * @working_directory: child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
453 * @argv: child's argument vector, in the GLib file name encoding
454 * @envp: child's environment, or %NULL to inherit parent's, in the GLib file name encoding
455 * @flags: flags from #GSpawnFlags
456 * @child_setup: function to run in the child just before exec()
457 * @user_data: user data for @child_setup
458 * @child_pid: return location for child process ID, or %NULL
459 * @standard_input: return location for file descriptor to write to child's stdin, or %NULL
460 * @standard_output: return location for file descriptor to read child's stdout, or %NULL
461 * @standard_error: return location for file descriptor to read child's stderr, or %NULL
462 * @error: return location for error
464 * Executes a child program asynchronously (your program will not
465 * block waiting for the child to exit). The child program is
466 * specified by the only argument that must be provided, @argv. @argv
467 * should be a %NULL-terminated array of strings, to be passed as the
468 * argument vector for the child. The first string in @argv is of
469 * course the name of the program to execute. By default, the name of
470 * the program must be a full path; the <envar>PATH</envar> shell variable
471 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
473 * On Windows, note that all the string or string vector arguments to
474 * this function and the other g_spawn*() functions are in UTF-8, the
475 * GLib file name encoding. Unicode characters that are not part of
476 * the system codepage passed in these arguments will be correctly
477 * available in the spawned program only if it uses wide character API
478 * to retrieve its command line. For C programs built with Microsoft's
479 * tools it is enough to make the program have a wmain() instead of
480 * main(). wmain() has a wide character argument vector as parameter.
482 * At least currently, mingw doesn't support wmain(), so if you use
483 * mingw to develop the spawned program, it will have to call the
484 * undocumented function __wgetmainargs() to get the wide character
485 * argument vector and environment. See gspawn-win32-helper.c in the
486 * GLib sources or init.c in the mingw runtime sources for a prototype
487 * for that function. Alternatively, you can retrieve the Win32 system
488 * level wide character command line passed to the spawned program
489 * using the GetCommandLineW() function.
491 * On Windows the low-level child process creation API
492 * <function>CreateProcess()</function> doesn't use argument vectors,
493 * but a command line. The C runtime library's
494 * <function>spawn*()</function> family of functions (which
495 * g_spawn_async_with_pipes() eventually calls) paste the argument
496 * vector elements together into a command line, and the C runtime startup code
497 * does a corresponding reconstruction of an argument vector from the
498 * command line, to be passed to main(). Complications arise when you have
499 * argument vector elements that contain spaces of double quotes. The
500 * <function>spawn*()</function> functions don't do any quoting or
501 * escaping, but on the other hand the startup code does do unquoting
502 * and unescaping in order to enable receiving arguments with embedded
503 * spaces or double quotes. To work around this asymmetry,
504 * g_spawn_async_with_pipes() will do quoting and escaping on argument
505 * vector elements that need it before calling the C runtime
508 * The returned @child_pid on Windows is a handle to the child
509 * process, not its identifier. Process handles and process
510 * identifiers are different concepts on Windows.
512 * @envp is a %NULL-terminated array of strings, where each string
513 * has the form <literal>KEY=VALUE</literal>. This will become
514 * the child's environment. If @envp is %NULL, the child inherits its
515 * parent's environment.
517 * @flags should be the bitwise OR of any flags you want to affect the
518 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that
519 * the child will not automatically be reaped; you must use a
520 * #GChildWatch source to be notified about the death of the child
521 * process. Eventually you must call g_spawn_close_pid() on the
522 * @child_pid, in order to free resources which may be associated
523 * with the child process. (On Unix, using a #GChildWatch source is
524 * equivalent to calling waitpid() or handling the %SIGCHLD signal
525 * manually. On Windows, calling g_spawn_close_pid() is equivalent
526 * to calling CloseHandle() on the process handle returned in
529 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
530 * descriptors will be inherited by the child; otherwise all
531 * descriptors except stdin/stdout/stderr will be closed before
532 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
533 * means that <literal>argv[0]</literal> need not be an absolute path, it
534 * will be looked for in the user's <envar>PATH</envar>.
535 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
536 * be discarded, instead of going to the same location as the parent's
537 * standard output. If you use this flag, @standard_output must be %NULL.
538 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
539 * will be discarded, instead of going to the same location as the parent's
540 * standard error. If you use this flag, @standard_error must be %NULL.
541 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
542 * standard input (by default, the child's standard input is attached to
543 * /dev/null). If you use this flag, @standard_input must be %NULL.
544 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
545 * the file to execute, while the remaining elements are the
546 * actual argument vector to pass to the file. Normally
547 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
548 * passes all of @argv to the child.
550 * @child_setup and @user_data are a function and user data. On POSIX
551 * platforms, the function is called in the child after GLib has
552 * performed all the setup it plans to perform (including creating
553 * pipes, closing file descriptors, etc.) but before calling
554 * exec(). That is, @child_setup is called just
555 * before calling exec() in the child. Obviously
556 * actions taken in this function will only affect the child, not the
559 * On Windows, there is no separate fork() and exec()
560 * functionality. Child processes are created and run with a single
561 * API call, CreateProcess(). There is no sensible thing @child_setup
562 * could be used for on Windows so it is ignored and not called.
564 * If non-%NULL, @child_pid will on Unix be filled with the child's
565 * process ID. You can use the process ID to send signals to the
566 * child, or to use g_child_watch_add() (or waitpid()) if you specified the
567 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
568 * filled with a handle to the child process only if you specified the
569 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
570 * process using the Win32 API, for example wait for its termination
571 * with the <function>WaitFor*()</function> functions, or examine its
572 * exit code with GetExitCodeProcess(). You should close the handle
573 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
575 * If non-%NULL, the @standard_input, @standard_output, @standard_error
576 * locations will be filled with file descriptors for writing to the child's
577 * standard input or reading from its standard output or standard error.
578 * The caller of g_spawn_async_with_pipes() must close these file descriptors
579 * when they are no longer in use. If these parameters are %NULL, the corresponding
580 * pipe won't be created.
582 * If @standard_input is NULL, the child's standard input is attached to
583 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
585 * If @standard_error is NULL, the child's standard error goes to the same
586 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
589 * If @standard_output is NULL, the child's standard output goes to the same
590 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
593 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
594 * If an error is set, the function returns %FALSE. Errors
595 * are reported even if they occur in the child (for example if the
596 * executable in <literal>argv[0]</literal> is not found). Typically
597 * the <literal>message</literal> field of returned errors should be displayed
598 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
600 * If an error occurs, @child_pid, @standard_input, @standard_output,
601 * and @standard_error will not be filled with valid values.
603 * If @child_pid is not %NULL and an error does not occur then the returned
604 * process reference must be closed using g_spawn_close_pid().
607 * If you are writing a GTK+ application, and the program you
608 * are spawning is a graphical application, too, then you may
609 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
610 * the spawned program opens its windows on the right screen.
613 * Return value: %TRUE on success, %FALSE if an error was set
616 g_spawn_async_with_pipes (const gchar *working_directory,
620 GSpawnChildSetupFunc child_setup,
623 gint *standard_input,
624 gint *standard_output,
625 gint *standard_error,
628 g_return_val_if_fail (argv != NULL, FALSE);
629 g_return_val_if_fail (standard_output == NULL ||
630 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
631 g_return_val_if_fail (standard_error == NULL ||
632 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
633 /* can't inherit stdin if we have an input pipe. */
634 g_return_val_if_fail (standard_input == NULL ||
635 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
637 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
641 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
642 (flags & G_SPAWN_SEARCH_PATH) != 0,
643 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
644 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
645 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
646 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
657 * g_spawn_command_line_sync:
658 * @command_line: a command line
659 * @standard_output: return location for child output
660 * @standard_error: return location for child errors
661 * @exit_status: return location for child exit status, as returned by waitpid()
662 * @error: return location for errors
664 * A simple version of g_spawn_sync() with little-used parameters
665 * removed, taking a command line instead of an argument vector. See
666 * g_spawn_sync() for full details. @command_line will be parsed by
667 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
668 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
669 * implications, so consider using g_spawn_sync() directly if
670 * appropriate. Possible errors are those from g_spawn_sync() and those
671 * from g_shell_parse_argv().
673 * If @exit_status is non-%NULL, the exit status of the child is stored there as
674 * it would be returned by waitpid(); standard UNIX macros such as WIFEXITED()
675 * and WEXITSTATUS() must be used to evaluate the exit status.
677 * On Windows, please note the implications of g_shell_parse_argv()
678 * parsing @command_line. Parsing is done according to Unix shell rules, not
679 * Windows command interpreter rules.
680 * Space is a separator, and backslashes are
681 * special. Thus you cannot simply pass a @command_line containing
682 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
683 * the backslashes will be eaten, and the space will act as a
684 * separator. You need to enclose such paths with single quotes, like
685 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
687 * Return value: %TRUE on success, %FALSE if an error was set
690 g_spawn_command_line_sync (const gchar *command_line,
691 gchar **standard_output,
692 gchar **standard_error,
699 g_return_val_if_fail (command_line != NULL, FALSE);
701 if (!g_shell_parse_argv (command_line,
706 retval = g_spawn_sync (NULL,
722 * g_spawn_command_line_async:
723 * @command_line: a command line
724 * @error: return location for errors
726 * A simple version of g_spawn_async() that parses a command line with
727 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
728 * command line in the background. Unlike g_spawn_async(), the
729 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
730 * that %G_SPAWN_SEARCH_PATH can have security implications, so
731 * consider using g_spawn_async() directly if appropriate. Possible
732 * errors are those from g_shell_parse_argv() and g_spawn_async().
734 * The same concerns on Windows apply as for g_spawn_command_line_sync().
736 * Return value: %TRUE on success, %FALSE if error is set.
739 g_spawn_command_line_async (const gchar *command_line,
745 g_return_val_if_fail (command_line != NULL, FALSE);
747 if (!g_shell_parse_argv (command_line,
752 retval = g_spawn_async (NULL,
766 exec_err_to_g_error (gint en)
772 return G_SPAWN_ERROR_ACCES;
778 return G_SPAWN_ERROR_PERM;
784 return G_SPAWN_ERROR_2BIG;
790 return G_SPAWN_ERROR_NOEXEC;
796 return G_SPAWN_ERROR_NAMETOOLONG;
802 return G_SPAWN_ERROR_NOENT;
808 return G_SPAWN_ERROR_NOMEM;
814 return G_SPAWN_ERROR_NOTDIR;
820 return G_SPAWN_ERROR_LOOP;
826 return G_SPAWN_ERROR_TXTBUSY;
832 return G_SPAWN_ERROR_IO;
838 return G_SPAWN_ERROR_NFILE;
844 return G_SPAWN_ERROR_MFILE;
850 return G_SPAWN_ERROR_INVAL;
856 return G_SPAWN_ERROR_ISDIR;
862 return G_SPAWN_ERROR_LIBBAD;
867 return G_SPAWN_ERROR_FAILED;
873 write_all (gint fd, gconstpointer vbuf, gsize to_write)
875 gchar *buf = (gchar *) vbuf;
879 gssize count = write (fd, buf, to_write);
897 write_err_and_exit (gint fd, gint msg)
901 write_all (fd, &msg, sizeof(msg));
902 write_all (fd, &en, sizeof(en));
908 set_cloexec (void *data, gint fd)
910 if (fd >= GPOINTER_TO_INT (data))
911 fcntl (fd, F_SETFD, FD_CLOEXEC);
918 fdwalk (int (*cb)(void *data, int fd), void *data)
924 #ifdef HAVE_SYS_RESOURCE_H
931 if ((d = opendir("/proc/self/fd"))) {
934 while ((de = readdir(d))) {
938 if (de->d_name[0] == '.')
942 l = strtol(de->d_name, &e, 10);
943 if (errno != 0 || !e || *e)
954 if ((res = cb (data, fd)) != 0)
962 /* If /proc is not mounted or not accessible we fall back to the old
967 #ifdef HAVE_SYS_RESOURCE_H
969 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
970 open_max = rl.rlim_max;
973 open_max = sysconf (_SC_OPEN_MAX);
975 for (fd = 0; fd < open_max; fd++)
976 if ((res = cb (data, fd)) != 0)
984 sane_dup2 (gint fd1, gint fd2)
989 ret = dup2 (fd1, fd2);
990 if (ret < 0 && errno == EINTR)
1005 do_exec (gint child_err_report_fd,
1009 const gchar *working_directory,
1012 gboolean close_descriptors,
1013 gboolean search_path,
1014 gboolean stdout_to_null,
1015 gboolean stderr_to_null,
1016 gboolean child_inherits_stdin,
1017 gboolean file_and_argv_zero,
1018 GSpawnChildSetupFunc child_setup,
1021 if (working_directory && chdir (working_directory) < 0)
1022 write_err_and_exit (child_err_report_fd,
1023 CHILD_CHDIR_FAILED);
1025 /* Close all file descriptors but stdin stdout and stderr as
1026 * soon as we exec. Note that this includes
1027 * child_err_report_fd, which keeps the parent from blocking
1028 * forever on the other end of that pipe.
1030 if (close_descriptors)
1032 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1036 /* We need to do child_err_report_fd anyway */
1037 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1040 /* Redirect pipes as required */
1044 /* dup2 can't actually fail here I don't think */
1046 if (sane_dup2 (stdin_fd, 0) < 0)
1047 write_err_and_exit (child_err_report_fd,
1050 /* ignore this if it doesn't work */
1051 close_and_invalidate (&stdin_fd);
1053 else if (!child_inherits_stdin)
1055 /* Keep process from blocking on a read of stdin */
1056 gint read_null = open ("/dev/null", O_RDONLY);
1057 sane_dup2 (read_null, 0);
1058 close_and_invalidate (&read_null);
1063 /* dup2 can't actually fail here I don't think */
1065 if (sane_dup2 (stdout_fd, 1) < 0)
1066 write_err_and_exit (child_err_report_fd,
1069 /* ignore this if it doesn't work */
1070 close_and_invalidate (&stdout_fd);
1072 else if (stdout_to_null)
1074 gint write_null = open ("/dev/null", O_WRONLY);
1075 sane_dup2 (write_null, 1);
1076 close_and_invalidate (&write_null);
1081 /* dup2 can't actually fail here I don't think */
1083 if (sane_dup2 (stderr_fd, 2) < 0)
1084 write_err_and_exit (child_err_report_fd,
1087 /* ignore this if it doesn't work */
1088 close_and_invalidate (&stderr_fd);
1090 else if (stderr_to_null)
1092 gint write_null = open ("/dev/null", O_WRONLY);
1093 sane_dup2 (write_null, 2);
1094 close_and_invalidate (&write_null);
1097 /* Call user function just before we exec */
1100 (* child_setup) (user_data);
1104 file_and_argv_zero ? argv + 1 : argv,
1108 write_err_and_exit (child_err_report_fd,
1125 if (bytes >= sizeof(gint)*2)
1126 break; /* give up, who knows what happened, should not be
1132 ((gchar*)buf) + bytes,
1133 sizeof(gint) * n_ints_in_buf - bytes);
1134 if (chunk < 0 && errno == EINTR)
1141 /* Some weird shit happened, bail out */
1144 G_SPAWN_ERROR_FAILED,
1145 _("Failed to read from child pipe (%s)"),
1146 g_strerror (errsv));
1150 else if (chunk == 0)
1152 else /* chunk > 0 */
1156 *n_ints_read = (gint)(bytes / sizeof(gint));
1162 fork_exec_with_pipes (gboolean intermediate_child,
1163 const gchar *working_directory,
1166 gboolean close_descriptors,
1167 gboolean search_path,
1168 gboolean stdout_to_null,
1169 gboolean stderr_to_null,
1170 gboolean child_inherits_stdin,
1171 gboolean file_and_argv_zero,
1172 GSpawnChildSetupFunc child_setup,
1175 gint *standard_input,
1176 gint *standard_output,
1177 gint *standard_error,
1181 gint stdin_pipe[2] = { -1, -1 };
1182 gint stdout_pipe[2] = { -1, -1 };
1183 gint stderr_pipe[2] = { -1, -1 };
1184 gint child_err_report_pipe[2] = { -1, -1 };
1185 gint child_pid_report_pipe[2] = { -1, -1 };
1188 if (!make_pipe (child_err_report_pipe, error))
1191 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1192 goto cleanup_and_fail;
1194 if (standard_input && !make_pipe (stdin_pipe, error))
1195 goto cleanup_and_fail;
1197 if (standard_output && !make_pipe (stdout_pipe, error))
1198 goto cleanup_and_fail;
1200 if (standard_error && !make_pipe (stderr_pipe, error))
1201 goto cleanup_and_fail;
1212 _("Failed to fork (%s)"),
1213 g_strerror (errsv));
1215 goto cleanup_and_fail;
1219 /* Immediate child. This may or may not be the child that
1220 * actually execs the new process.
1223 /* Be sure we crash if the parent exits
1224 * and we write to the err_report_pipe
1226 signal (SIGPIPE, SIG_DFL);
1228 /* Close the parent's end of the pipes;
1229 * not needed in the close_descriptors case,
1232 close_and_invalidate (&child_err_report_pipe[0]);
1233 close_and_invalidate (&child_pid_report_pipe[0]);
1234 close_and_invalidate (&stdin_pipe[1]);
1235 close_and_invalidate (&stdout_pipe[0]);
1236 close_and_invalidate (&stderr_pipe[0]);
1238 if (intermediate_child)
1240 /* We need to fork an intermediate child that launches the
1241 * final child. The purpose of the intermediate child
1242 * is to exit, so we can waitpid() it immediately.
1243 * Then the grandchild will not become a zombie.
1245 GPid grandchild_pid;
1247 grandchild_pid = fork ();
1249 if (grandchild_pid < 0)
1251 /* report -1 as child PID */
1252 write_all (child_pid_report_pipe[1], &grandchild_pid,
1253 sizeof(grandchild_pid));
1255 write_err_and_exit (child_err_report_pipe[1],
1258 else if (grandchild_pid == 0)
1260 do_exec (child_err_report_pipe[1],
1271 child_inherits_stdin,
1278 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1279 close_and_invalidate (&child_pid_report_pipe[1]);
1286 /* Just run the child.
1289 do_exec (child_err_report_pipe[1],
1300 child_inherits_stdin,
1313 /* Close the uncared-about ends of the pipes */
1314 close_and_invalidate (&child_err_report_pipe[1]);
1315 close_and_invalidate (&child_pid_report_pipe[1]);
1316 close_and_invalidate (&stdin_pipe[0]);
1317 close_and_invalidate (&stdout_pipe[1]);
1318 close_and_invalidate (&stderr_pipe[1]);
1320 /* If we had an intermediate child, reap it */
1321 if (intermediate_child)
1324 if (waitpid (pid, &status, 0) < 0)
1328 else if (errno == ECHILD)
1329 ; /* do nothing, child already reaped */
1331 g_warning ("waitpid() should not fail in "
1332 "'fork_exec_with_pipes'");
1337 if (!read_ints (child_err_report_pipe[0],
1340 goto cleanup_and_fail;
1344 /* Error from the child. */
1348 case CHILD_CHDIR_FAILED:
1351 G_SPAWN_ERROR_CHDIR,
1352 _("Failed to change to directory '%s' (%s)"),
1354 g_strerror (buf[1]));
1358 case CHILD_EXEC_FAILED:
1361 exec_err_to_g_error (buf[1]),
1362 _("Failed to execute child process \"%s\" (%s)"),
1364 g_strerror (buf[1]));
1368 case CHILD_DUP2_FAILED:
1371 G_SPAWN_ERROR_FAILED,
1372 _("Failed to redirect output or input of child process (%s)"),
1373 g_strerror (buf[1]));
1377 case CHILD_FORK_FAILED:
1381 _("Failed to fork child process (%s)"),
1382 g_strerror (buf[1]));
1388 G_SPAWN_ERROR_FAILED,
1389 _("Unknown error executing child process \"%s\""),
1394 goto cleanup_and_fail;
1397 /* Get child pid from intermediate child pipe. */
1398 if (intermediate_child)
1402 if (!read_ints (child_pid_report_pipe[0],
1403 buf, 1, &n_ints, error))
1404 goto cleanup_and_fail;
1412 G_SPAWN_ERROR_FAILED,
1413 _("Failed to read enough data from child pid pipe (%s)"),
1414 g_strerror (errsv));
1415 goto cleanup_and_fail;
1419 /* we have the child pid */
1424 /* Success against all odds! return the information */
1425 close_and_invalidate (&child_err_report_pipe[0]);
1426 close_and_invalidate (&child_pid_report_pipe[0]);
1432 *standard_input = stdin_pipe[1];
1433 if (standard_output)
1434 *standard_output = stdout_pipe[0];
1436 *standard_error = stderr_pipe[0];
1443 /* There was an error from the Child, reap the child to avoid it being
1450 if (waitpid (pid, NULL, 0) < 0)
1454 else if (errno == ECHILD)
1455 ; /* do nothing, child already reaped */
1457 g_warning ("waitpid() should not fail in "
1458 "'fork_exec_with_pipes'");
1462 close_and_invalidate (&child_err_report_pipe[0]);
1463 close_and_invalidate (&child_err_report_pipe[1]);
1464 close_and_invalidate (&child_pid_report_pipe[0]);
1465 close_and_invalidate (&child_pid_report_pipe[1]);
1466 close_and_invalidate (&stdin_pipe[0]);
1467 close_and_invalidate (&stdin_pipe[1]);
1468 close_and_invalidate (&stdout_pipe[0]);
1469 close_and_invalidate (&stdout_pipe[1]);
1470 close_and_invalidate (&stderr_pipe[0]);
1471 close_and_invalidate (&stderr_pipe[1]);
1477 make_pipe (gint p[2],
1485 G_SPAWN_ERROR_FAILED,
1486 _("Failed to create pipe for communicating with child process (%s)"),
1487 g_strerror (errsv));
1494 /* Based on execvp from GNU C Library */
1497 script_execute (const gchar *file,
1500 gboolean search_path)
1502 /* Count the arguments. */
1507 /* Construct an argument list for the shell. */
1511 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1513 new_argv[0] = (char *) "/bin/sh";
1514 new_argv[1] = (char *) file;
1517 new_argv[argc + 1] = argv[argc];
1521 /* Execute the shell. */
1523 execve (new_argv[0], new_argv, envp);
1525 execv (new_argv[0], new_argv);
1532 my_strchrnul (const gchar *str, gchar c)
1534 gchar *p = (gchar*) str;
1535 while (*p && (*p != c))
1542 g_execute (const gchar *file,
1545 gboolean search_path)
1549 /* We check the simple case first. */
1554 if (!search_path || strchr (file, '/') != NULL)
1556 /* Don't search when it contains a slash. */
1558 execve (file, argv, envp);
1562 if (errno == ENOEXEC)
1563 script_execute (file, argv, envp, FALSE);
1567 gboolean got_eacces = 0;
1568 const gchar *path, *p;
1569 gchar *name, *freeme;
1573 path = g_getenv ("PATH");
1576 /* There is no `PATH' in the environment. The default
1577 * search path in libc is the current directory followed by
1578 * the path `confstr' returns for `_CS_PATH'.
1581 /* In GLib we put . last, for security, and don't use the
1582 * unportable confstr(); UNIX98 does not actually specify
1583 * what to search if PATH is unset. POSIX may, dunno.
1586 path = "/bin:/usr/bin:.";
1589 len = strlen (file) + 1;
1590 pathlen = strlen (path);
1591 freeme = name = g_malloc (pathlen + len + 1);
1593 /* Copy the file name at the top, including '\0' */
1594 memcpy (name + pathlen + 1, file, len);
1595 name = name + pathlen;
1596 /* And add the slash before the filename */
1605 p = my_strchrnul (path, ':');
1608 /* Two adjacent colons, or a colon at the beginning or the end
1609 * of `PATH' means to search the current directory.
1613 startp = memcpy (name - (p - path), path, p - path);
1615 /* Try to execute this name. If it works, execv will not return. */
1617 execve (startp, argv, envp);
1619 execv (startp, argv);
1621 if (errno == ENOEXEC)
1622 script_execute (startp, argv, envp, search_path);
1627 /* Record the we got a `Permission denied' error. If we end
1628 * up finding no executable we can use, we want to diagnose
1629 * that we did find one but were denied access.
1642 /* Those errors indicate the file is missing or not executable
1643 * by us, in which case we want to just try the next path
1649 /* Some other error means we found an executable file, but
1650 * something went wrong executing it; return the error to our
1657 while (*p++ != '\0');
1659 /* We tried every element and none of them worked. */
1661 /* At least one failure was due to permissions, so report that
1669 /* Return the error from the last attempt (probably ENOENT). */
1674 * g_spawn_close_pid:
1675 * @pid: The process reference to close
1677 * On some platforms, notably Windows, the #GPid type represents a resource
1678 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1679 * is provided for this purpose. It should be used on all platforms, even
1680 * though it doesn't do anything under UNIX.
1683 g_spawn_close_pid (GPid pid)