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>
34 #ifdef HAVE_SYS_SELECT_H
35 #include <sys/select.h>
36 #endif /* HAVE_SYS_SELECT_H */
42 /* With solaris threads, fork() duplicates all threads, which
43 * a) could cause unexpected side-effects, and b) is expensive.
44 * Once we remove support for solaris threads, the FORK1 #define
47 #ifdef G_THREADS_IMPL_SOLARIS
48 #define FORK1() fork1()
50 #define FORK1() fork()
53 static gint g_execute (const gchar *file,
56 gboolean search_path);
58 static gboolean make_pipe (gint p[2],
60 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
61 const gchar *working_directory,
64 gboolean close_descriptors,
66 gboolean stdout_to_null,
67 gboolean stderr_to_null,
68 gboolean child_inherits_stdin,
69 gboolean file_and_argv_zero,
70 GSpawnChildSetupFunc child_setup,
74 gint *standard_output,
79 g_spawn_error_quark (void)
81 static GQuark quark = 0;
83 quark = g_quark_from_static_string ("g-exec-error-quark");
89 * @working_directory: child's current working directory, or %NULL to inherit parent's
90 * @argv: child's argument vector
91 * @envp: child's environment, or %NULL to inherit parent's
92 * @flags: flags from #GSpawnFlags
93 * @child_setup: function to run in the child just before exec()
94 * @user_data: user data for @child_setup
95 * @child_pid: return location for child process ID, or %NULL
96 * @error: return location for error
98 * See g_spawn_async_with_pipes() for a full description; this function
99 * simply calls the g_spawn_async_with_pipes() without any pipes.
101 * Return value: %TRUE on success, %FALSE if error is set
104 g_spawn_async (const gchar *working_directory,
108 GSpawnChildSetupFunc child_setup,
113 g_return_val_if_fail (argv != NULL, FALSE);
115 return g_spawn_async_with_pipes (working_directory,
125 /* Avoids a danger in threaded situations (calling close()
126 * on a file descriptor twice, and another thread has
127 * re-opened it since the first close)
130 close_and_invalidate (gint *fd)
147 READ_FAILED = 0, /* FALSE */
153 read_data (GString *str,
162 bytes = read (fd, buf, 4096);
168 g_string_append_len (str, buf, bytes);
171 else if (bytes < 0 && errno == EINTR)
178 _("Failed to read data from child process (%s)"),
189 * @working_directory: child's current working directory, or %NULL to inherit parent's
190 * @argv: child's argument vector
191 * @envp: child's environment, or %NULL to inherit parent's
192 * @flags: flags from #GSpawnFlags
193 * @child_setup: function to run in the child just before exec()
194 * @user_data: user data for @child_setup
195 * @standard_output: return location for child output
196 * @standard_error: return location for child error messages
197 * @exit_status: child exit status, as returned by waitpid()
198 * @error: return location for error
200 * Executes a child synchronously (waits for the child to exit before returning).
201 * All output from the child is stored in @standard_output and @standard_error,
202 * if those parameters are non-%NULL. If @exit_status is non-%NULL, the exit
203 * status of the child is stored there as it would be returned by
204 * waitpid(); standard UNIX macros such as WIFEXITED() and WEXITSTATUS()
205 * must be used to evaluate the exit status. If an error occurs, no data is
206 * returned in @standard_output, @standard_error, or @exit_status.
208 * This function calls g_spawn_async_with_pipes() internally; see that function
209 * for full details on the other parameters.
211 * Return value: %TRUE on success, %FALSE if an error was set.
214 g_spawn_sync (const gchar *working_directory,
218 GSpawnChildSetupFunc child_setup,
220 gchar **standard_output,
221 gchar **standard_error,
230 GString *outstr = NULL;
231 GString *errstr = NULL;
235 g_return_val_if_fail (argv != NULL, FALSE);
236 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
237 g_return_val_if_fail (standard_output == NULL ||
238 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
239 g_return_val_if_fail (standard_error == NULL ||
240 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
242 /* Just to ensure segfaults if callers try to use
243 * these when an error is reported.
246 *standard_output = NULL;
249 *standard_error = NULL;
251 if (!fork_exec_with_pipes (FALSE,
255 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
256 (flags & G_SPAWN_SEARCH_PATH) != 0,
257 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
258 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
259 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
260 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
265 standard_output ? &outpipe : NULL,
266 standard_error ? &errpipe : NULL,
270 /* Read data from child. */
276 outstr = g_string_new (NULL);
281 errstr = g_string_new (NULL);
284 /* Read data until we get EOF on both pipes. */
293 FD_SET (outpipe, &fds);
295 FD_SET (errpipe, &fds);
297 ret = select (MAX (outpipe, errpipe) + 1,
300 NULL /* no timeout */);
302 if (ret < 0 && errno != EINTR)
309 _("Unexpected error in select() reading data from a child process (%s)"),
315 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
317 switch (read_data (outstr, outpipe, error))
323 close_and_invalidate (&outpipe);
334 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
336 switch (read_data (errstr, errpipe, error))
342 close_and_invalidate (&errpipe);
354 /* These should only be open still if we had an error. */
357 close_and_invalidate (&outpipe);
359 close_and_invalidate (&errpipe);
361 /* Wait for child to exit, even if we have
366 ret = waitpid (pid, &status, 0);
372 else if (errno == ECHILD)
376 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.");
380 /* We don't need the exit status. */
385 if (!failed) /* avoid error pileups */
392 _("Unexpected error in waitpid() (%s)"),
401 g_string_free (outstr, TRUE);
403 g_string_free (errstr, TRUE);
410 *exit_status = status;
413 *standard_output = g_string_free (outstr, FALSE);
416 *standard_error = g_string_free (errstr, FALSE);
423 * g_spawn_async_with_pipes:
424 * @working_directory: child's current working directory, or %NULL to inherit parent's
425 * @argv: child's argument vector
426 * @envp: child's environment, or %NULL to inherit parent's
427 * @flags: flags from #GSpawnFlags
428 * @child_setup: function to run in the child just before exec()
429 * @user_data: user data for @child_setup
430 * @child_pid: return location for child process ID, or %NULL
431 * @standard_input: return location for file descriptor to write to child's stdin, or %NULL
432 * @standard_output: return location for file descriptor to read child's stdout, or %NULL
433 * @standard_error: return location for file descriptor to read child's stderr, or %NULL
434 * @error: return location for error
436 * Executes a child program asynchronously (your program will not
437 * block waiting for the child to exit). The child program is
438 * specified by the only argument that must be provided, @argv. @argv
439 * should be a %NULL-terminated array of strings, to be passed as the
440 * argument vector for the child. The first string in @argv is of
441 * course the name of the program to execute. By default, the name of
442 * the program must be a full path; the <envar>PATH</envar> shell variable
443 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
445 * On Windows, the low-level child process creation API
446 * (CreateProcess())doesn't use argument vectors,
447 * but a command line. The C runtime library's
448 * <function>spawn*()</function> family of functions (which
449 * g_spawn_async_with_pipes() eventually calls) paste the argument
450 * vector elements into a command line, and the C runtime startup code
451 * does a corresponding recostruction of an argument vector from the
452 * command line, to be passed to main(). Complications arise when you have
453 * argument vector elements that contain spaces of double quotes. The
454 * <function>spawn*()</function> functions don't do any quoting or
455 * escaping, but on the other hand the startup code does do unquoting
456 * and unescaping in order to enable receiving arguments with embedded
457 * spaces or double quotes. To work around this asymmetry,
458 * g_spawn_async_with_pipes() will do quoting and escaping on argument
459 * vector elements that need it before calling the C runtime
462 * @envp is a %NULL-terminated array of strings, where each string
463 * has the form <literal>KEY=VALUE</literal>. This will become
464 * the child's environment. If @envp is %NULL, the child inherits its
465 * parent's environment.
467 * @flags should be the bitwise OR of any flags you want to affect the
468 * function's behavior. On Unix, the %G_SPAWN_DO_NOT_REAP_CHILD means
469 * that the child will not be automatically reaped; you must call
470 * waitpid() or handle %SIGCHLD yourself, or the
471 * child will become a zombie. On Windows, the flag means that a
472 * handle to the child will be returned @child_pid. You must call
473 * CloseHandle() on it eventually (or exit the
474 * process), or the child processs will continue to take up some table
475 * space even after its death. Quite similar to zombies on Unix,
478 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
479 * descriptors will be inherited by the child; otherwise all
480 * descriptors except stdin/stdout/stderr will be closed before
481 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
482 * means that <literal>argv[0]</literal> need not be an absolute path, it
483 * will be looked for in the user's <envar>PATH</envar>.
484 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
485 * be discarded, instead of going to the same location as the parent's
486 * standard output. If you use this flag, @standard_output must be %NULL.
487 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
488 * will be discarded, instead of going to the same location as the parent's
489 * standard error. If you use this flag, @standard_error must be %NULL.
490 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
491 * standard input (by default, the child's standard input is attached to
492 * /dev/null). If you use this flag, @standard_input must be %NULL.
493 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
494 * the file to execute, while the remaining elements are the
495 * actual argument vector to pass to the file. Normally
496 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
497 * passes all of @argv to the child.
499 * @child_setup and @user_data are a function and user data. On POSIX
500 * platforms, the function is called in the child after GLib has
501 * performed all the setup it plans to perform (including creating
502 * pipes, closing file descriptors, etc.) but before calling
503 * exec(). That is, @child_setup is called just
504 * before calling exec() in the child. Obviously
505 * actions taken in this function will only affect the child, not the
506 * parent. On Windows, there is no separate fork() and exec()
507 * functionality. Child processes are created and run right away with
508 * one API call, CreateProcess(). @child_setup is
509 * called in the parent process just before creating the child
510 * process. You should carefully consider what you do in @child_setup
511 * if you intend your software to be portable to Windows.
513 * If non-%NULL, @child_pid will on Unix be filled with the child's
514 * process ID. You can use the process ID to send signals to the
515 * child, or to waitpid() if you specified the
516 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
517 * filled with a handle to the child process only if you specified the
518 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
519 * process using the Win32 API, for example wait for its termination
520 * with the <function>WaitFor*()</function> functions, or examine its
521 * exit code with GetExitCodeProcess(). You should close the handle
522 * with CloseHandle() when you no longer need it.
524 * If non-%NULL, the @standard_input, @standard_output, @standard_error
525 * locations will be filled with file descriptors for writing to the child's
526 * standard input or reading from its standard output or standard error.
527 * The caller of g_spawn_async_with_pipes() must close these file descriptors
528 * when they are no longer in use. If these parameters are %NULL, the corresponding
529 * pipe won't be created.
531 * If @standard_input is NULL, the child's standard input is attached to /dev/null
532 * unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
534 * If @standard_error is NULL, the child's standard error goes to the same location
535 * as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL is set.
537 * If @standard_output is NULL, the child's standard output goes to the same location
538 * as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL is set.
540 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
541 * If an error is set, the function returns %FALSE. Errors
542 * are reported even if they occur in the child (for example if the
543 * executable in <literal>argv[0]</literal> is not found). Typically
544 * the <literal>message</literal> field of returned errors should be displayed
545 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
547 * If an error occurs, @child_pid, @standard_input, @standard_output,
548 * and @standard_error will not be filled with valid values.
550 * If @child_pid is not %NULL and an error does not occur then the returned
551 * pid must be closed using g_spawn_close_pid().
553 * Return value: %TRUE on success, %FALSE if an error was set
556 g_spawn_async_with_pipes (const gchar *working_directory,
560 GSpawnChildSetupFunc child_setup,
563 gint *standard_input,
564 gint *standard_output,
565 gint *standard_error,
568 g_return_val_if_fail (argv != NULL, FALSE);
569 g_return_val_if_fail (standard_output == NULL ||
570 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
571 g_return_val_if_fail (standard_error == NULL ||
572 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
573 /* can't inherit stdin if we have an input pipe. */
574 g_return_val_if_fail (standard_input == NULL ||
575 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
577 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
581 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
582 (flags & G_SPAWN_SEARCH_PATH) != 0,
583 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
584 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
585 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
586 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
597 * g_spawn_command_line_sync:
598 * @command_line: a command line
599 * @standard_output: return location for child output
600 * @standard_error: return location for child errors
601 * @exit_status: return location for child exit status
602 * @error: return location for errors
604 * A simple version of g_spawn_sync() with little-used parameters
605 * removed, taking a command line instead of an argument vector. See
606 * g_spawn_sync() for full details. @command_line will be parsed by
607 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
608 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
609 * implications, so consider using g_spawn_sync() directly if
610 * appropriate. Possible errors are those from g_spawn_sync() and those
611 * from g_shell_parse_argv().
613 * On Windows, please note the implications of g_shell_parse_argv()
614 * parsing @command_line. Space is a separator, and backslashes are
615 * special. Thus you cannot simply pass a @command_line containing
616 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
617 * the backslashes will be eaten, and the space will act as a
618 * separator. You need to enclose such paths with single quotes, like
619 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
621 * Return value: %TRUE on success, %FALSE if an error was set
624 g_spawn_command_line_sync (const gchar *command_line,
625 gchar **standard_output,
626 gchar **standard_error,
633 g_return_val_if_fail (command_line != NULL, FALSE);
635 if (!g_shell_parse_argv (command_line,
640 retval = g_spawn_sync (NULL,
656 * g_spawn_command_line_async:
657 * @command_line: a command line
658 * @error: return location for errors
660 * A simple version of g_spawn_async() that parses a command line with
661 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
662 * command line in the background. Unlike g_spawn_async(), the
663 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
664 * that %G_SPAWN_SEARCH_PATH can have security implications, so
665 * consider using g_spawn_async() directly if appropriate. Possible
666 * errors are those from g_shell_parse_argv() and g_spawn_async().
668 * The same concerns on Windows apply as for g_spawn_command_line_sync().
670 * Return value: %TRUE on success, %FALSE if error is set.
673 g_spawn_command_line_async (const gchar *command_line,
679 g_return_val_if_fail (command_line != NULL, FALSE);
681 if (!g_shell_parse_argv (command_line,
686 retval = g_spawn_async (NULL,
700 exec_err_to_g_error (gint en)
706 return G_SPAWN_ERROR_ACCES;
712 return G_SPAWN_ERROR_PERM;
718 return G_SPAWN_ERROR_2BIG;
724 return G_SPAWN_ERROR_NOEXEC;
730 return G_SPAWN_ERROR_NAMETOOLONG;
736 return G_SPAWN_ERROR_NOENT;
742 return G_SPAWN_ERROR_NOMEM;
748 return G_SPAWN_ERROR_NOTDIR;
754 return G_SPAWN_ERROR_LOOP;
760 return G_SPAWN_ERROR_TXTBUSY;
766 return G_SPAWN_ERROR_IO;
772 return G_SPAWN_ERROR_NFILE;
778 return G_SPAWN_ERROR_MFILE;
784 return G_SPAWN_ERROR_INVAL;
790 return G_SPAWN_ERROR_ISDIR;
796 return G_SPAWN_ERROR_LIBBAD;
801 return G_SPAWN_ERROR_FAILED;
807 write_all (gint fd, gconstpointer vbuf, gsize to_write)
809 gchar *buf = (gchar *) vbuf;
813 gssize count = write (fd, buf, to_write);
830 write_err_and_exit (gint fd, gint msg)
834 write_all (fd, &msg, sizeof(msg));
835 write_all (fd, &en, sizeof(en));
841 set_cloexec (gint fd)
843 fcntl (fd, F_SETFD, FD_CLOEXEC);
847 sane_dup2 (gint fd1, gint fd2)
852 ret = dup2 (fd1, fd2);
853 if (ret < 0 && errno == EINTR)
868 do_exec (gint child_err_report_fd,
872 const gchar *working_directory,
875 gboolean close_descriptors,
876 gboolean search_path,
877 gboolean stdout_to_null,
878 gboolean stderr_to_null,
879 gboolean child_inherits_stdin,
880 gboolean file_and_argv_zero,
881 GSpawnChildSetupFunc child_setup,
884 if (working_directory && chdir (working_directory) < 0)
885 write_err_and_exit (child_err_report_fd,
888 /* Close all file descriptors but stdin stdout and stderr as
889 * soon as we exec. Note that this includes
890 * child_err_report_fd, which keeps the parent from blocking
891 * forever on the other end of that pipe.
893 if (close_descriptors)
898 open_max = sysconf (_SC_OPEN_MAX);
899 for (i = 3; i < open_max; i++)
904 /* We need to do child_err_report_fd anyway */
905 set_cloexec (child_err_report_fd);
908 /* Redirect pipes as required */
912 /* dup2 can't actually fail here I don't think */
914 if (sane_dup2 (stdin_fd, 0) < 0)
915 write_err_and_exit (child_err_report_fd,
918 /* ignore this if it doesn't work */
919 close_and_invalidate (&stdin_fd);
921 else if (!child_inherits_stdin)
923 /* Keep process from blocking on a read of stdin */
924 gint read_null = open ("/dev/null", O_RDONLY);
925 sane_dup2 (read_null, 0);
926 close_and_invalidate (&read_null);
931 /* dup2 can't actually fail here I don't think */
933 if (sane_dup2 (stdout_fd, 1) < 0)
934 write_err_and_exit (child_err_report_fd,
937 /* ignore this if it doesn't work */
938 close_and_invalidate (&stdout_fd);
940 else if (stdout_to_null)
942 gint write_null = open ("/dev/null", O_WRONLY);
943 sane_dup2 (write_null, 1);
944 close_and_invalidate (&write_null);
949 /* dup2 can't actually fail here I don't think */
951 if (sane_dup2 (stderr_fd, 2) < 0)
952 write_err_and_exit (child_err_report_fd,
955 /* ignore this if it doesn't work */
956 close_and_invalidate (&stderr_fd);
958 else if (stderr_to_null)
960 gint write_null = open ("/dev/null", O_WRONLY);
961 sane_dup2 (write_null, 2);
962 close_and_invalidate (&write_null);
965 /* Call user function just before we exec */
968 (* child_setup) (user_data);
972 file_and_argv_zero ? argv + 1 : argv,
976 write_err_and_exit (child_err_report_fd,
993 if (bytes >= sizeof(gint)*2)
994 break; /* give up, who knows what happened, should not be
1000 ((gchar*)buf) + bytes,
1001 sizeof(gint) * n_ints_in_buf - bytes);
1002 if (chunk < 0 && errno == EINTR)
1007 /* Some weird shit happened, bail out */
1011 G_SPAWN_ERROR_FAILED,
1012 _("Failed to read from child pipe (%s)"),
1013 g_strerror (errno));
1017 else if (chunk == 0)
1019 else /* chunk > 0 */
1023 *n_ints_read = (gint)(bytes / sizeof(gint));
1029 fork_exec_with_pipes (gboolean intermediate_child,
1030 const gchar *working_directory,
1033 gboolean close_descriptors,
1034 gboolean search_path,
1035 gboolean stdout_to_null,
1036 gboolean stderr_to_null,
1037 gboolean child_inherits_stdin,
1038 gboolean file_and_argv_zero,
1039 GSpawnChildSetupFunc child_setup,
1042 gint *standard_input,
1043 gint *standard_output,
1044 gint *standard_error,
1048 gint stdin_pipe[2] = { -1, -1 };
1049 gint stdout_pipe[2] = { -1, -1 };
1050 gint stderr_pipe[2] = { -1, -1 };
1051 gint child_err_report_pipe[2] = { -1, -1 };
1052 gint child_pid_report_pipe[2] = { -1, -1 };
1055 if (!make_pipe (child_err_report_pipe, error))
1058 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1059 goto cleanup_and_fail;
1061 if (standard_input && !make_pipe (stdin_pipe, error))
1062 goto cleanup_and_fail;
1064 if (standard_output && !make_pipe (stdout_pipe, error))
1065 goto cleanup_and_fail;
1067 if (standard_error && !make_pipe (stderr_pipe, error))
1068 goto cleanup_and_fail;
1077 _("Failed to fork (%s)"),
1078 g_strerror (errno));
1080 goto cleanup_and_fail;
1084 /* Immediate child. This may or may not be the child that
1085 * actually execs the new process.
1088 /* Be sure we crash if the parent exits
1089 * and we write to the err_report_pipe
1091 signal (SIGPIPE, SIG_DFL);
1093 /* Close the parent's end of the pipes;
1094 * not needed in the close_descriptors case,
1097 close_and_invalidate (&child_err_report_pipe[0]);
1098 close_and_invalidate (&child_pid_report_pipe[0]);
1099 close_and_invalidate (&stdin_pipe[1]);
1100 close_and_invalidate (&stdout_pipe[0]);
1101 close_and_invalidate (&stderr_pipe[0]);
1103 if (intermediate_child)
1105 /* We need to fork an intermediate child that launches the
1106 * final child. The purpose of the intermediate child
1107 * is to exit, so we can waitpid() it immediately.
1108 * Then the grandchild will not become a zombie.
1110 GPid grandchild_pid;
1112 grandchild_pid = FORK1 ();
1114 if (grandchild_pid < 0)
1116 /* report -1 as child PID */
1117 write_all (child_pid_report_pipe[1], &grandchild_pid,
1118 sizeof(grandchild_pid));
1120 write_err_and_exit (child_err_report_pipe[1],
1123 else if (grandchild_pid == 0)
1125 do_exec (child_err_report_pipe[1],
1136 child_inherits_stdin,
1143 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1144 close_and_invalidate (&child_pid_report_pipe[1]);
1151 /* Just run the child.
1154 do_exec (child_err_report_pipe[1],
1165 child_inherits_stdin,
1178 /* Close the uncared-about ends of the pipes */
1179 close_and_invalidate (&child_err_report_pipe[1]);
1180 close_and_invalidate (&child_pid_report_pipe[1]);
1181 close_and_invalidate (&stdin_pipe[0]);
1182 close_and_invalidate (&stdout_pipe[1]);
1183 close_and_invalidate (&stderr_pipe[1]);
1185 /* If we had an intermediate child, reap it */
1186 if (intermediate_child)
1189 if (waitpid (pid, &status, 0) < 0)
1193 else if (errno == ECHILD)
1194 ; /* do nothing, child already reaped */
1196 g_warning ("waitpid() should not fail in "
1197 "'fork_exec_with_pipes'");
1202 if (!read_ints (child_err_report_pipe[0],
1205 goto cleanup_and_fail;
1209 /* Error from the child. */
1213 case CHILD_CHDIR_FAILED:
1216 G_SPAWN_ERROR_CHDIR,
1217 _("Failed to change to directory '%s' (%s)"),
1219 g_strerror (buf[1]));
1223 case CHILD_EXEC_FAILED:
1226 exec_err_to_g_error (buf[1]),
1227 _("Failed to execute child process \"%s\" (%s)"),
1229 g_strerror (buf[1]));
1233 case CHILD_DUP2_FAILED:
1236 G_SPAWN_ERROR_FAILED,
1237 _("Failed to redirect output or input of child process (%s)"),
1238 g_strerror (buf[1]));
1242 case CHILD_FORK_FAILED:
1246 _("Failed to fork child process (%s)"),
1247 g_strerror (buf[1]));
1253 G_SPAWN_ERROR_FAILED,
1254 _("Unknown error executing child process \"%s\""),
1259 goto cleanup_and_fail;
1262 /* Get child pid from intermediate child pipe. */
1263 if (intermediate_child)
1267 if (!read_ints (child_pid_report_pipe[0],
1268 buf, 1, &n_ints, error))
1269 goto cleanup_and_fail;
1275 G_SPAWN_ERROR_FAILED,
1276 _("Failed to read enough data from child pid pipe (%s)"),
1277 g_strerror (errno));
1278 goto cleanup_and_fail;
1282 /* we have the child pid */
1287 /* Success against all odds! return the information */
1288 close_and_invalidate (&child_err_report_pipe[0]);
1289 close_and_invalidate (&child_pid_report_pipe[0]);
1295 *standard_input = stdin_pipe[1];
1296 if (standard_output)
1297 *standard_output = stdout_pipe[0];
1299 *standard_error = stderr_pipe[0];
1306 /* There was an error from the Child, reap the child to avoid it being
1313 if (waitpid (pid, NULL, 0) < 0)
1317 else if (errno == ECHILD)
1318 ; /* do nothing, child already reaped */
1320 g_warning ("waitpid() should not fail in "
1321 "'fork_exec_with_pipes'");
1325 close_and_invalidate (&child_err_report_pipe[0]);
1326 close_and_invalidate (&child_err_report_pipe[1]);
1327 close_and_invalidate (&child_pid_report_pipe[0]);
1328 close_and_invalidate (&child_pid_report_pipe[1]);
1329 close_and_invalidate (&stdin_pipe[0]);
1330 close_and_invalidate (&stdin_pipe[1]);
1331 close_and_invalidate (&stdout_pipe[0]);
1332 close_and_invalidate (&stdout_pipe[1]);
1333 close_and_invalidate (&stderr_pipe[0]);
1334 close_and_invalidate (&stderr_pipe[1]);
1340 make_pipe (gint p[2],
1347 G_SPAWN_ERROR_FAILED,
1348 _("Failed to create pipe for communicating with child process (%s)"),
1349 g_strerror (errno));
1356 /* Based on execvp from GNU C Library */
1359 script_execute (const gchar *file,
1362 gboolean search_path)
1364 /* Count the arguments. */
1369 /* Construct an argument list for the shell. */
1373 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1375 new_argv[0] = (char *) "/bin/sh";
1376 new_argv[1] = (char *) file;
1379 new_argv[argc + 1] = argv[argc];
1383 /* Execute the shell. */
1385 execve (new_argv[0], new_argv, envp);
1387 execv (new_argv[0], new_argv);
1394 my_strchrnul (const gchar *str, gchar c)
1396 gchar *p = (gchar*) str;
1397 while (*p && (*p != c))
1404 g_execute (const gchar *file,
1407 gboolean search_path)
1411 /* We check the simple case first. */
1416 if (!search_path || strchr (file, '/') != NULL)
1418 /* Don't search when it contains a slash. */
1420 execve (file, argv, envp);
1424 if (errno == ENOEXEC)
1425 script_execute (file, argv, envp, FALSE);
1429 gboolean got_eacces = 0;
1430 const gchar *path, *p;
1431 gchar *name, *freeme;
1435 path = g_getenv ("PATH");
1438 /* There is no `PATH' in the environment. The default
1439 * search path in libc is the current directory followed by
1440 * the path `confstr' returns for `_CS_PATH'.
1443 /* In GLib we put . last, for security, and don't use the
1444 * unportable confstr(); UNIX98 does not actually specify
1445 * what to search if PATH is unset. POSIX may, dunno.
1448 path = "/bin:/usr/bin:.";
1451 len = strlen (file) + 1;
1452 pathlen = strlen (path);
1453 freeme = name = g_malloc (pathlen + len + 1);
1455 /* Copy the file name at the top, including '\0' */
1456 memcpy (name + pathlen + 1, file, len);
1457 name = name + pathlen;
1458 /* And add the slash before the filename */
1467 p = my_strchrnul (path, ':');
1470 /* Two adjacent colons, or a colon at the beginning or the end
1471 * of `PATH' means to search the current directory.
1475 startp = memcpy (name - (p - path), path, p - path);
1477 /* Try to execute this name. If it works, execv will not return. */
1479 execve (startp, argv, envp);
1481 execv (startp, argv);
1483 if (errno == ENOEXEC)
1484 script_execute (startp, argv, envp, search_path);
1489 /* Record the we got a `Permission denied' error. If we end
1490 * up finding no executable we can use, we want to diagnose
1491 * that we did find one but were denied access.
1504 /* Those errors indicate the file is missing or not executable
1505 * by us, in which case we want to just try the next path
1511 /* Some other error means we found an executable file, but
1512 * something went wrong executing it; return the error to our
1519 while (*p++ != '\0');
1521 /* We tried every element and none of them worked. */
1523 /* At least one failure was due to permissions, so report that
1531 /* Return the error from the last attempt (probably ENOENT). */
1536 * g_spawn_close_pid:
1537 * @pid: The process identifier to close
1539 * On some platforms, notably WIN32, the #GPid type represents a resource
1540 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1541 * is provided for this purpose. It should be used on all platforms, even
1542 * though it doesn't do anything under UNIX.
1545 g_spawn_close_pid (GPid pid)