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 static gint g_execute (const gchar *file,
45 gboolean search_path);
47 static gboolean make_pipe (gint p[2],
49 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
50 const gchar *working_directory,
53 gboolean close_descriptors,
55 gboolean stdout_to_null,
56 gboolean stderr_to_null,
57 gboolean child_inherits_stdin,
58 gboolean file_and_argv_zero,
59 GSpawnChildSetupFunc child_setup,
63 gint *standard_output,
68 g_spawn_error_quark (void)
70 static GQuark quark = 0;
72 quark = g_quark_from_static_string ("g-exec-error-quark");
78 * @working_directory: child's current working directory, or %NULL to inherit parent's
79 * @argv: child's argument vector
80 * @envp: child's environment, or %NULL to inherit parent's
81 * @flags: flags from #GSpawnFlags
82 * @child_setup: function to run in the child just before <function>exec()</function>
83 * @user_data: user data for @child_setup
84 * @child_pid: return location for child process ID, or %NULL
85 * @error: return location for error
87 * See g_spawn_async_with_pipes() for a full description; this function
88 * simply calls the g_spawn_async_with_pipes() without any pipes.
90 * Return value: %TRUE on success, %FALSE if error is set
93 g_spawn_async (const gchar *working_directory,
97 GSpawnChildSetupFunc child_setup,
102 g_return_val_if_fail (argv != NULL, FALSE);
104 return g_spawn_async_with_pipes (working_directory,
114 /* Avoids a danger in threaded situations (calling close()
115 * on a file descriptor twice, and another thread has
116 * re-opened it since the first close)
119 close_and_invalidate (gint *fd)
136 READ_FAILED = 0, /* FALSE */
142 read_data (GString *str,
151 bytes = read (fd, &buf, 4096);
157 g_string_append_len (str, buf, bytes);
160 else if (bytes < 0 && errno == EINTR)
167 _("Failed to read data from child process (%s)"),
178 * @working_directory: child's current working directory, or %NULL to inherit parent's
179 * @argv: child's argument vector
180 * @envp: child's environment, or %NULL to inherit parent's
181 * @flags: flags from #GSpawnFlags
182 * @child_setup: function to run in the child just before <function>exec()</function>
183 * @user_data: user data for @child_setup
184 * @standard_output: return location for child output
185 * @standard_error: return location for child error messages
186 * @exit_status: child exit status, as returned by <function>waitpid()</function>
187 * @error: return location for error
189 * Executes a child synchronously (waits for the child to exit before returning).
190 * All output from the child is stored in @standard_output and @standard_error,
191 * if those parameters are non-%NULL. If @exit_status is non-%NULL, the exit
192 * status of the child is stored there as it would be returned by
193 * <function>waitpid()</function>; standard UNIX macros such as
194 * <function>WIFEXITED()</function> and <function>WEXITSTATUS()</function>
195 * must be used to evaluate the exit status. If an error occurs, no data is
196 * returned in @standard_output, @standard_error, or @exit_status.
198 * This function calls g_spawn_async_with_pipes() internally; see that function
199 * for full details on the other parameters.
201 * Return value: %TRUE on success, %FALSE if an error was set.
204 g_spawn_sync (const gchar *working_directory,
208 GSpawnChildSetupFunc child_setup,
210 gchar **standard_output,
211 gchar **standard_error,
220 GString *outstr = NULL;
221 GString *errstr = NULL;
225 g_return_val_if_fail (argv != NULL, FALSE);
226 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
227 g_return_val_if_fail (standard_output == NULL ||
228 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
229 g_return_val_if_fail (standard_error == NULL ||
230 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
232 /* Just to ensure segfaults if callers try to use
233 * these when an error is reported.
236 *standard_output = NULL;
239 *standard_error = NULL;
241 if (!fork_exec_with_pipes (FALSE,
245 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
246 (flags & G_SPAWN_SEARCH_PATH) != 0,
247 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
248 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
249 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
250 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
255 standard_output ? &outpipe : NULL,
256 standard_error ? &errpipe : NULL,
260 /* Read data from child. */
266 outstr = g_string_new ("");
271 errstr = g_string_new ("");
274 /* Read data until we get EOF on both pipes. */
283 FD_SET (outpipe, &fds);
285 FD_SET (errpipe, &fds);
287 ret = select (MAX (outpipe, errpipe) + 1,
290 NULL /* no timeout */);
292 if (ret < 0 && errno != EINTR)
299 _("Unexpected error in select() reading data from a child process (%s)"),
305 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
307 switch (read_data (outstr, outpipe, error))
313 close_and_invalidate (&outpipe);
324 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
326 switch (read_data (errstr, errpipe, error))
332 close_and_invalidate (&errpipe);
344 /* These should only be open still if we had an error. */
347 close_and_invalidate (&outpipe);
349 close_and_invalidate (&errpipe);
351 /* Wait for child to exit, even if we have
356 ret = waitpid (pid, &status, 0);
362 else if (errno == ECHILD)
366 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.");
370 /* We don't need the exit status. */
375 if (!failed) /* avoid error pileups */
382 _("Unexpected error in waitpid() (%s)"),
391 g_string_free (outstr, TRUE);
393 g_string_free (errstr, TRUE);
400 *exit_status = status;
403 *standard_output = g_string_free (outstr, FALSE);
406 *standard_error = g_string_free (errstr, FALSE);
413 * g_spawn_async_with_pipes:
414 * @working_directory: child's current working directory, or %NULL to inherit parent's
415 * @argv: child's argument vector
416 * @envp: child's environment, or %NULL to inherit parent's
417 * @flags: flags from #GSpawnFlags
418 * @child_setup: function to run in the child just before <function>exec()</function>
419 * @user_data: user data for @child_setup
420 * @child_pid: return location for child process ID, or %NULL
421 * @standard_input: return location for file descriptor to write to child's stdin, or %NULL
422 * @standard_output: return location for file descriptor to read child's stdout, or %NULL
423 * @standard_error: return location for file descriptor to read child's stderr, or %NULL
424 * @error: return location for error
426 * Executes a child program asynchronously (your program will not
427 * block waiting for the child to exit). The child program is
428 * specified by the only argument that must be provided, @argv. @argv
429 * should be a %NULL-terminated array of strings, to be passed as the
430 * argument vector for the child. The first string in @argv is of
431 * course the name of the program to execute. By default, the name of
432 * the program must be a full path; the <envar>PATH</envar> shell variable
433 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
435 * On Windows, the low-level child process creation API
436 * (<function>CreateProcess()</function>)doesn't use argument vectors,
437 * but a command line. The C runtime library's
438 * <function>spawn*()</function> family of functions (which
439 * g_spawn_async_with_pipes() eventually calls) paste the argument
440 * vector elements into a command line, and the C runtime startup code
441 * does a corresponding recostruction of an argument vector from the
442 * command line, to be passed to
443 * <function>main()</function>. Complications arise when you have
444 * argument vector elements that contain spaces of double quotes. The
445 * <function>spawn()</function> functions don't do any quoting or
446 * escaping, but on the other hand the startup code does do unquoting
447 * and unescaping in order to enable receiving arguments with embedded
448 * spaces or double quotes. To work around this asymmetry,
449 * g_spawn_async_with_pipes() will do quoting and escaping on argument
450 * vector elements that need it before calling the C runtime
451 * <function>spawn()</function> function.
453 * @envp is a %NULL-terminated array of strings, where each string
454 * has the form <literal>KEY=VALUE</literal>. This will become
455 * the child's environment. If @envp is %NULL, the child inherits its
456 * parent's environment.
458 * @flags should be the bitwise OR of any flags you want to affect the
459 * function's behavior. On Unix, the %G_SPAWN_DO_NOT_REAP_CHILD means
460 * that the child will not be automatically reaped; you must call
461 * <function>waitpid()</function> or handle %SIGCHLD yourself, or the
462 * child will become a zombie. On Windows, the flag means that a
463 * handle to the child will be returned @child_pid. You must call
464 * <function>CloseHandle()</function> on it eventually (or exit the
465 * process), or the child processs will continue to take up some table
466 * space even after its death. Quite similar to zombies on Unix,
469 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
470 * descriptors will be inherited by the child; otherwise all
471 * descriptors except stdin/stdout/stderr will be closed before
472 * calling <function>exec()</function> in the child. %G_SPAWN_SEARCH_PATH
473 * means that <literal>argv[0]</literal> need not be an absolute path, it
474 * will be looked for in the user's <envar>PATH</envar>.
475 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
476 * be discarded, instead of going to the same location as the parent's
477 * standard output. If you use this flag, @standard_output must be %NULL.
478 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
479 * will be discarded, instead of going to the same location as the parent's
480 * standard error. If you use this flag, @standard_error must be %NULL.
481 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
482 * standard input (by default, the child's standard input is attached to
483 * /dev/null). If you use this flag, @standard_input must be %NULL.
484 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
485 * the file to execute, while the remaining elements are the
486 * actual argument vector to pass to the file. Normally
487 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
488 * passes all of @argv to the child.
490 * @child_setup and @user_data are a function and user data. On POSIX
491 * platforms, the function is called in the child after GLib has
492 * performed all the setup it plans to perform (including creating
493 * pipes, closing file descriptors, etc.) but before calling
494 * <function>exec()</function>. That is, @child_setup is called just
495 * before calling <function>exec()</function> in the child. Obviously
496 * actions taken in this function will only affect the child, not the
497 * parent. On Windows, there is no separate
498 * <function>fork()</function> and <function>exec()</function>
499 * functionality. Child processes are created and run right away with
500 * one API call, <function>CreateProcess()</function>. @child_setup is
501 * called in the parent process just before creating the child
502 * process. You should carefully consider what you do in @child_setup
503 * if you intend your software to be portable to Windows.
505 * If non-%NULL, @child_pid will on Unix be filled with the child's
506 * process ID. You can use the process ID to send signals to the
507 * child, or to <function>waitpid()</function> if you specified the
508 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
509 * filled with a handle to the child process only if you specified the
510 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
511 * process using the Win32 API, for example wait for its termination
512 * with the <function>WaitFor*()</function> functions, or examine its
513 * exit code with <function>GetExitCodeProcess()</function>. You
514 * should close the handle with <function>CloseHandle()</function>
515 * when you no longer need it.
517 * If non-%NULL, the @standard_input, @standard_output, @standard_error
518 * locations will be filled with file descriptors for writing to the child's
519 * standard input or reading from its standard output or standard error.
520 * The caller of g_spawn_async_with_pipes() must close these file descriptors
521 * when they are no longer in use. If these parameters are %NULL, the corresponding
522 * pipe won't be created.
524 * If @standard_input is NULL, the child's standard input is attached to /dev/null
525 * unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
527 * If @standard_error is NULL, the child's standard error goes to the same location
528 * as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL is set.
530 * If @standard_output is NULL, the child's standard output goes to the same location
531 * as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL is set.
533 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
534 * If an error is set, the function returns %FALSE. Errors
535 * are reported even if they occur in the child (for example if the
536 * executable in <literal>argv[0]</literal> is not found). Typically
537 * the <literal>message</literal> field of returned errors should be displayed
538 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
540 * If an error occurs, @child_pid, @standard_input, @standard_output,
541 * and @standard_error will not be filled with valid values.
543 * Return value: %TRUE on success, %FALSE if an error was set
546 g_spawn_async_with_pipes (const gchar *working_directory,
550 GSpawnChildSetupFunc child_setup,
553 gint *standard_input,
554 gint *standard_output,
555 gint *standard_error,
558 g_return_val_if_fail (argv != NULL, FALSE);
559 g_return_val_if_fail (standard_output == NULL ||
560 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
561 g_return_val_if_fail (standard_error == NULL ||
562 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
563 /* can't inherit stdin if we have an input pipe. */
564 g_return_val_if_fail (standard_input == NULL ||
565 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
567 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
571 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
572 (flags & G_SPAWN_SEARCH_PATH) != 0,
573 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
574 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
575 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
576 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
587 * g_spawn_command_line_sync:
588 * @command_line: a command line
589 * @standard_output: return location for child output
590 * @standard_error: return location for child errors
591 * @exit_status: return location for child exit status
592 * @error: return location for errors
594 * A simple version of g_spawn_sync() with little-used parameters
595 * removed, taking a command line instead of an argument vector. See
596 * g_spawn_sync() for full details. @command_line will be parsed by
597 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
598 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
599 * implications, so consider using g_spawn_sync() directly if
600 * appropriate. Possible errors are those from g_spawn_sync() and those
601 * from g_shell_parse_argv().
603 * On Windows, please note the implications of g_shell_parse_argv()
604 * parsing @command_line. Space is a separator, and backslashes are
605 * special. Thus you cannot simply pass a @command_line containing
606 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
607 * the backslashes will be eaten, and the space will act as a
608 * separator. You need to enclose such paths with single quotes, like
609 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
611 * Return value: %TRUE on success, %FALSE if an error was set
614 g_spawn_command_line_sync (const gchar *command_line,
615 gchar **standard_output,
616 gchar **standard_error,
623 g_return_val_if_fail (command_line != NULL, FALSE);
625 if (!g_shell_parse_argv (command_line,
630 retval = g_spawn_sync (NULL,
646 * g_spawn_command_line_async:
647 * @command_line: a command line
648 * @error: return location for errors
650 * A simple version of g_spawn_async() that parses a command line with
651 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
652 * command line in the background. Unlike g_spawn_async(), the
653 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
654 * that %G_SPAWN_SEARCH_PATH can have security implications, so
655 * consider using g_spawn_async() directly if appropriate. Possible
656 * errors are those from g_shell_parse_argv() and g_spawn_async().
658 * The same concerns on Windows apply as for g_spawn_command_line_sync().
660 * Return value: %TRUE on success, %FALSE if error is set.
663 g_spawn_command_line_async (const gchar *command_line,
669 g_return_val_if_fail (command_line != NULL, FALSE);
671 if (!g_shell_parse_argv (command_line,
676 retval = g_spawn_async (NULL,
690 exec_err_to_g_error (gint en)
696 return G_SPAWN_ERROR_ACCES;
702 return G_SPAWN_ERROR_PERM;
708 return G_SPAWN_ERROR_2BIG;
714 return G_SPAWN_ERROR_NOEXEC;
720 return G_SPAWN_ERROR_NAMETOOLONG;
726 return G_SPAWN_ERROR_NOENT;
732 return G_SPAWN_ERROR_NOMEM;
738 return G_SPAWN_ERROR_NOTDIR;
744 return G_SPAWN_ERROR_LOOP;
750 return G_SPAWN_ERROR_TXTBUSY;
756 return G_SPAWN_ERROR_IO;
762 return G_SPAWN_ERROR_NFILE;
768 return G_SPAWN_ERROR_MFILE;
774 return G_SPAWN_ERROR_INVAL;
780 return G_SPAWN_ERROR_ISDIR;
786 return G_SPAWN_ERROR_LIBBAD;
791 return G_SPAWN_ERROR_FAILED;
797 write_err_and_exit (gint fd, gint msg)
801 write (fd, &msg, sizeof(msg));
802 write (fd, &en, sizeof(en));
808 set_cloexec (gint fd)
810 fcntl (fd, F_SETFD, FD_CLOEXEC);
814 sane_dup2 (gint fd1, gint fd2)
819 ret = dup2 (fd1, fd2);
820 if (ret < 0 && errno == EINTR)
835 do_exec (gint child_err_report_fd,
839 const gchar *working_directory,
842 gboolean close_descriptors,
843 gboolean search_path,
844 gboolean stdout_to_null,
845 gboolean stderr_to_null,
846 gboolean child_inherits_stdin,
847 gboolean file_and_argv_zero,
848 GSpawnChildSetupFunc child_setup,
851 if (working_directory && chdir (working_directory) < 0)
852 write_err_and_exit (child_err_report_fd,
855 /* Close all file descriptors but stdin stdout and stderr as
856 * soon as we exec. Note that this includes
857 * child_err_report_fd, which keeps the parent from blocking
858 * forever on the other end of that pipe.
860 if (close_descriptors)
865 open_max = sysconf (_SC_OPEN_MAX);
866 for (i = 3; i < open_max; i++)
871 /* We need to do child_err_report_fd anyway */
872 set_cloexec (child_err_report_fd);
875 /* Redirect pipes as required */
879 /* dup2 can't actually fail here I don't think */
881 if (sane_dup2 (stdin_fd, 0) < 0)
882 write_err_and_exit (child_err_report_fd,
885 /* ignore this if it doesn't work */
886 close_and_invalidate (&stdin_fd);
888 else if (!child_inherits_stdin)
890 /* Keep process from blocking on a read of stdin */
891 gint read_null = open ("/dev/null", O_RDONLY);
892 sane_dup2 (read_null, 0);
893 close_and_invalidate (&read_null);
898 /* dup2 can't actually fail here I don't think */
900 if (sane_dup2 (stdout_fd, 1) < 0)
901 write_err_and_exit (child_err_report_fd,
904 /* ignore this if it doesn't work */
905 close_and_invalidate (&stdout_fd);
907 else if (stdout_to_null)
909 gint write_null = open ("/dev/null", O_WRONLY);
910 sane_dup2 (write_null, 1);
911 close_and_invalidate (&write_null);
916 /* dup2 can't actually fail here I don't think */
918 if (sane_dup2 (stderr_fd, 2) < 0)
919 write_err_and_exit (child_err_report_fd,
922 /* ignore this if it doesn't work */
923 close_and_invalidate (&stderr_fd);
925 else if (stderr_to_null)
927 gint write_null = open ("/dev/null", O_WRONLY);
928 sane_dup2 (write_null, 2);
929 close_and_invalidate (&write_null);
932 /* Call user function just before we exec */
935 (* child_setup) (user_data);
939 file_and_argv_zero ? argv + 1 : argv,
943 write_err_and_exit (child_err_report_fd,
960 if (bytes >= sizeof(gint)*2)
961 break; /* give up, who knows what happened, should not be
967 ((gchar*)buf) + bytes,
968 sizeof(gint) * n_ints_in_buf - bytes);
969 if (chunk < 0 && errno == EINTR)
974 /* Some weird shit happened, bail out */
978 G_SPAWN_ERROR_FAILED,
979 _("Failed to read from child pipe (%s)"),
990 *n_ints_read = (gint)(bytes / sizeof(gint));
996 fork_exec_with_pipes (gboolean intermediate_child,
997 const gchar *working_directory,
1000 gboolean close_descriptors,
1001 gboolean search_path,
1002 gboolean stdout_to_null,
1003 gboolean stderr_to_null,
1004 gboolean child_inherits_stdin,
1005 gboolean file_and_argv_zero,
1006 GSpawnChildSetupFunc child_setup,
1009 gint *standard_input,
1010 gint *standard_output,
1011 gint *standard_error,
1015 gint stdin_pipe[2] = { -1, -1 };
1016 gint stdout_pipe[2] = { -1, -1 };
1017 gint stderr_pipe[2] = { -1, -1 };
1018 gint child_err_report_pipe[2] = { -1, -1 };
1019 gint child_pid_report_pipe[2] = { -1, -1 };
1022 if (!make_pipe (child_err_report_pipe, error))
1025 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1026 goto cleanup_and_fail;
1028 if (standard_input && !make_pipe (stdin_pipe, error))
1029 goto cleanup_and_fail;
1031 if (standard_output && !make_pipe (stdout_pipe, error))
1032 goto cleanup_and_fail;
1034 if (standard_error && !make_pipe (stderr_pipe, error))
1035 goto cleanup_and_fail;
1044 _("Failed to fork (%s)"),
1045 g_strerror (errno));
1047 goto cleanup_and_fail;
1051 /* Immediate child. This may or may not be the child that
1052 * actually execs the new process.
1055 /* Be sure we crash if the parent exits
1056 * and we write to the err_report_pipe
1058 signal (SIGPIPE, SIG_DFL);
1060 /* Close the parent's end of the pipes;
1061 * not needed in the close_descriptors case,
1064 close_and_invalidate (&child_err_report_pipe[0]);
1065 close_and_invalidate (&child_pid_report_pipe[0]);
1066 close_and_invalidate (&stdin_pipe[1]);
1067 close_and_invalidate (&stdout_pipe[0]);
1068 close_and_invalidate (&stderr_pipe[0]);
1070 if (intermediate_child)
1072 /* We need to fork an intermediate child that launches the
1073 * final child. The purpose of the intermediate child
1074 * is to exit, so we can waitpid() it immediately.
1075 * Then the grandchild will not become a zombie.
1077 gint grandchild_pid;
1079 grandchild_pid = fork ();
1081 if (grandchild_pid < 0)
1083 /* report -1 as child PID */
1084 write (child_pid_report_pipe[1], &grandchild_pid,
1085 sizeof(grandchild_pid));
1087 write_err_and_exit (child_err_report_pipe[1],
1090 else if (grandchild_pid == 0)
1092 do_exec (child_err_report_pipe[1],
1103 child_inherits_stdin,
1110 write (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1111 close_and_invalidate (&child_pid_report_pipe[1]);
1118 /* Just run the child.
1121 do_exec (child_err_report_pipe[1],
1132 child_inherits_stdin,
1145 /* Close the uncared-about ends of the pipes */
1146 close_and_invalidate (&child_err_report_pipe[1]);
1147 close_and_invalidate (&child_pid_report_pipe[1]);
1148 close_and_invalidate (&stdin_pipe[0]);
1149 close_and_invalidate (&stdout_pipe[1]);
1150 close_and_invalidate (&stderr_pipe[1]);
1152 /* If we had an intermediate child, reap it */
1153 if (intermediate_child)
1156 if (waitpid (pid, &status, 0) < 0)
1160 else if (errno == ECHILD)
1161 ; /* do nothing, child already reaped */
1163 g_warning ("waitpid() should not fail in "
1164 "'fork_exec_with_pipes'");
1169 if (!read_ints (child_err_report_pipe[0],
1172 goto cleanup_and_fail;
1176 /* Error from the child. */
1180 case CHILD_CHDIR_FAILED:
1183 G_SPAWN_ERROR_CHDIR,
1184 _("Failed to change to directory '%s' (%s)"),
1186 g_strerror (buf[1]));
1190 case CHILD_EXEC_FAILED:
1193 exec_err_to_g_error (buf[1]),
1194 _("Failed to execute child process \"%s\" (%s)"),
1196 g_strerror (buf[1]));
1200 case CHILD_DUP2_FAILED:
1203 G_SPAWN_ERROR_FAILED,
1204 _("Failed to redirect output or input of child process (%s)"),
1205 g_strerror (buf[1]));
1209 case CHILD_FORK_FAILED:
1213 _("Failed to fork child process (%s)"),
1214 g_strerror (buf[1]));
1220 G_SPAWN_ERROR_FAILED,
1221 _("Unknown error executing child process \"%s\""),
1226 goto cleanup_and_fail;
1229 /* Get child pid from intermediate child pipe. */
1230 if (intermediate_child)
1234 if (!read_ints (child_pid_report_pipe[0],
1235 buf, 1, &n_ints, error))
1236 goto cleanup_and_fail;
1242 G_SPAWN_ERROR_FAILED,
1243 _("Failed to read enough data from child pid pipe (%s)"),
1244 g_strerror (errno));
1245 goto cleanup_and_fail;
1249 /* we have the child pid */
1254 /* Success against all odds! return the information */
1255 close_and_invalidate (&child_err_report_pipe[0]);
1256 close_and_invalidate (&child_pid_report_pipe[0]);
1262 *standard_input = stdin_pipe[1];
1263 if (standard_output)
1264 *standard_output = stdout_pipe[0];
1266 *standard_error = stderr_pipe[0];
1273 /* There was an error from the Child, reap the child to avoid it being
1280 if (waitpid (pid, NULL, 0) < 0)
1284 else if (errno == ECHILD)
1285 ; /* do nothing, child already reaped */
1287 g_warning ("waitpid() should not fail in "
1288 "'fork_exec_with_pipes'");
1292 close_and_invalidate (&child_err_report_pipe[0]);
1293 close_and_invalidate (&child_err_report_pipe[1]);
1294 close_and_invalidate (&child_pid_report_pipe[0]);
1295 close_and_invalidate (&child_pid_report_pipe[1]);
1296 close_and_invalidate (&stdin_pipe[0]);
1297 close_and_invalidate (&stdin_pipe[1]);
1298 close_and_invalidate (&stdout_pipe[0]);
1299 close_and_invalidate (&stdout_pipe[1]);
1300 close_and_invalidate (&stderr_pipe[0]);
1301 close_and_invalidate (&stderr_pipe[1]);
1307 make_pipe (gint p[2],
1314 G_SPAWN_ERROR_FAILED,
1315 _("Failed to create pipe for communicating with child process (%s)"),
1316 g_strerror (errno));
1323 /* Based on execvp from GNU C Library */
1326 script_execute (const gchar *file,
1329 gboolean search_path)
1331 /* Count the arguments. */
1336 /* Construct an argument list for the shell. */
1340 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1342 new_argv[0] = (char *) "/bin/sh";
1343 new_argv[1] = (char *) file;
1346 new_argv[argc + 1] = argv[argc];
1350 /* Execute the shell. */
1352 execve (new_argv[0], new_argv, envp);
1354 execv (new_argv[0], new_argv);
1361 my_strchrnul (const gchar *str, gchar c)
1363 gchar *p = (gchar*) str;
1364 while (*p && (*p != c))
1371 g_execute (const gchar *file,
1374 gboolean search_path)
1378 /* We check the simple case first. */
1383 if (!search_path || strchr (file, '/') != NULL)
1385 /* Don't search when it contains a slash. */
1387 execve (file, argv, envp);
1391 if (errno == ENOEXEC)
1392 script_execute (file, argv, envp, FALSE);
1396 gboolean got_eacces = 0;
1397 const gchar *path, *p;
1398 gchar *name, *freeme;
1402 path = g_getenv ("PATH");
1405 /* There is no `PATH' in the environment. The default
1406 * search path in libc is the current directory followed by
1407 * the path `confstr' returns for `_CS_PATH'.
1410 /* In GLib we put . last, for security, and don't use the
1411 * unportable confstr(); UNIX98 does not actually specify
1412 * what to search if PATH is unset. POSIX may, dunno.
1415 path = "/bin:/usr/bin:.";
1418 len = strlen (file) + 1;
1419 pathlen = strlen (path);
1420 freeme = name = g_malloc (pathlen + len + 1);
1422 /* Copy the file name at the top, including '\0' */
1423 memcpy (name + pathlen + 1, file, len);
1424 name = name + pathlen;
1425 /* And add the slash before the filename */
1434 p = my_strchrnul (path, ':');
1437 /* Two adjacent colons, or a colon at the beginning or the end
1438 * of `PATH' means to search the current directory.
1442 startp = memcpy (name - (p - path), path, p - path);
1444 /* Try to execute this name. If it works, execv will not return. */
1446 execve (startp, argv, envp);
1448 execv (startp, argv);
1450 if (errno == ENOEXEC)
1451 script_execute (startp, argv, envp, search_path);
1456 /* Record the we got a `Permission denied' error. If we end
1457 * up finding no executable we can use, we want to diagnose
1458 * that we did find one but were denied access.
1471 /* Those errors indicate the file is missing or not executable
1472 * by us, in which case we want to just try the next path
1478 /* Some other error means we found an executable file, but
1479 * something went wrong executing it; return the error to our
1486 while (*p++ != '\0');
1488 /* We tried every element and none of them worked. */
1490 /* At least one failure was due to permissions, so report that
1498 /* Return the error from the last attempt (probably ENOENT). */