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 */
43 /* With solaris threads, fork() duplicates all threads, which
44 * a) could cause unexpected side-effects, and b) is expensive.
45 * Once we remove support for solaris threads, the FORK1 #define
48 #ifdef G_THREADS_IMPL_SOLARIS
49 #define FORK1() fork1()
51 #define FORK1() fork()
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 static GQuark quark = 0;
84 quark = g_quark_from_static_string ("g-exec-error-quark");
90 * @working_directory: child's current working directory, or %NULL to inherit parent's
91 * @argv: child's argument vector
92 * @envp: child's environment, or %NULL to inherit parent's
93 * @flags: flags from #GSpawnFlags
94 * @child_setup: function to run in the child just before exec()
95 * @user_data: user data for @child_setup
96 * @child_pid: return location for child process ID, or %NULL
97 * @error: return location for error
99 * See g_spawn_async_with_pipes() for a full description; this function
100 * simply calls the g_spawn_async_with_pipes() without any pipes.
102 * Return value: %TRUE on success, %FALSE if error is set
105 g_spawn_async (const gchar *working_directory,
109 GSpawnChildSetupFunc child_setup,
114 g_return_val_if_fail (argv != NULL, FALSE);
116 return g_spawn_async_with_pipes (working_directory,
126 /* Avoids a danger in threaded situations (calling close()
127 * on a file descriptor twice, and another thread has
128 * re-opened it since the first close)
131 close_and_invalidate (gint *fd)
148 READ_FAILED = 0, /* FALSE */
154 read_data (GString *str,
163 bytes = read (fd, buf, 4096);
169 g_string_append_len (str, buf, bytes);
172 else if (bytes < 0 && errno == EINTR)
179 _("Failed to read data from child process (%s)"),
190 * @working_directory: child's current working directory, or %NULL to inherit parent's
191 * @argv: child's argument vector
192 * @envp: child's environment, or %NULL to inherit parent's
193 * @flags: flags from #GSpawnFlags
194 * @child_setup: function to run in the child just before exec()
195 * @user_data: user data for @child_setup
196 * @standard_output: return location for child output
197 * @standard_error: return location for child error messages
198 * @exit_status: return location for child exit status, as returned by waitpid()
199 * @error: return location for error
201 * Executes a child synchronously (waits for the child to exit before returning).
202 * All output from the child is stored in @standard_output and @standard_error,
203 * if those parameters are non-%NULL. If @exit_status is non-%NULL, the exit
204 * status of the child is stored there as it would be returned by
205 * waitpid(); standard UNIX macros such as WIFEXITED() and WEXITSTATUS()
206 * must be used to evaluate the exit status. If an error occurs, no data is
207 * returned in @standard_output, @standard_error, or @exit_status.
209 * This function calls g_spawn_async_with_pipes() internally; see that function
210 * for full details on the other parameters.
212 * Return value: %TRUE on success, %FALSE if an error was set.
215 g_spawn_sync (const gchar *working_directory,
219 GSpawnChildSetupFunc child_setup,
221 gchar **standard_output,
222 gchar **standard_error,
231 GString *outstr = NULL;
232 GString *errstr = NULL;
236 g_return_val_if_fail (argv != NULL, FALSE);
237 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
238 g_return_val_if_fail (standard_output == NULL ||
239 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
240 g_return_val_if_fail (standard_error == NULL ||
241 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
243 /* Just to ensure segfaults if callers try to use
244 * these when an error is reported.
247 *standard_output = NULL;
250 *standard_error = NULL;
252 if (!fork_exec_with_pipes (FALSE,
256 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
257 (flags & G_SPAWN_SEARCH_PATH) != 0,
258 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
259 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
260 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
261 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
266 standard_output ? &outpipe : NULL,
267 standard_error ? &errpipe : NULL,
271 /* Read data from child. */
277 outstr = g_string_new (NULL);
282 errstr = g_string_new (NULL);
285 /* Read data until we get EOF on both pipes. */
294 FD_SET (outpipe, &fds);
296 FD_SET (errpipe, &fds);
298 ret = select (MAX (outpipe, errpipe) + 1,
301 NULL /* no timeout */);
303 if (ret < 0 && errno != EINTR)
310 _("Unexpected error in select() reading data from a child process (%s)"),
316 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
318 switch (read_data (outstr, outpipe, error))
324 close_and_invalidate (&outpipe);
335 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
337 switch (read_data (errstr, errpipe, error))
343 close_and_invalidate (&errpipe);
355 /* These should only be open still if we had an error. */
358 close_and_invalidate (&outpipe);
360 close_and_invalidate (&errpipe);
362 /* Wait for child to exit, even if we have
367 ret = waitpid (pid, &status, 0);
373 else if (errno == ECHILD)
377 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.");
381 /* We don't need the exit status. */
386 if (!failed) /* avoid error pileups */
393 _("Unexpected error in waitpid() (%s)"),
402 g_string_free (outstr, TRUE);
404 g_string_free (errstr, TRUE);
411 *exit_status = status;
414 *standard_output = g_string_free (outstr, FALSE);
417 *standard_error = g_string_free (errstr, FALSE);
424 * g_spawn_async_with_pipes:
425 * @working_directory: child's current working directory, or %NULL to inherit parent's
426 * @argv: child's argument vector
427 * @envp: child's environment, or %NULL to inherit parent's
428 * @flags: flags from #GSpawnFlags
429 * @child_setup: function to run in the child just before exec()
430 * @user_data: user data for @child_setup
431 * @child_pid: return location for child process ID, or %NULL
432 * @standard_input: return location for file descriptor to write to child's stdin, or %NULL
433 * @standard_output: return location for file descriptor to read child's stdout, or %NULL
434 * @standard_error: return location for file descriptor to read child's stderr, or %NULL
435 * @error: return location for error
437 * Executes a child program asynchronously (your program will not
438 * block waiting for the child to exit). The child program is
439 * specified by the only argument that must be provided, @argv. @argv
440 * should be a %NULL-terminated array of strings, to be passed as the
441 * argument vector for the child. The first string in @argv is of
442 * course the name of the program to execute. By default, the name of
443 * the program must be a full path; the <envar>PATH</envar> shell variable
444 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
446 * On Windows, the low-level child process creation API
447 * (CreateProcess())doesn't use argument vectors,
448 * but a command line. The C runtime library's
449 * <function>spawn*()</function> family of functions (which
450 * g_spawn_async_with_pipes() eventually calls) paste the argument
451 * vector elements into a command line, and the C runtime startup code
452 * does a corresponding reconstruction of an argument vector from the
453 * command line, to be passed to main(). Complications arise when you have
454 * argument vector elements that contain spaces of double quotes. The
455 * <function>spawn*()</function> functions don't do any quoting or
456 * escaping, but on the other hand the startup code does do unquoting
457 * and unescaping in order to enable receiving arguments with embedded
458 * spaces or double quotes. To work around this asymmetry,
459 * g_spawn_async_with_pipes() will do quoting and escaping on argument
460 * vector elements that need it before calling the C runtime
463 * @envp is a %NULL-terminated array of strings, where each string
464 * has the form <literal>KEY=VALUE</literal>. This will become
465 * the child's environment. If @envp is %NULL, the child inherits its
466 * parent's environment.
468 * @flags should be the bitwise OR of any flags you want to affect the
469 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that
470 * the child will not automatically be reaped; you must use a
471 * #GChildWatch source to be notified about the death of the child
472 * process. Eventually you must call g_spawn_close_pid() on the
473 * @child_pid, in order to free resources which may be associated
474 * with the child process. (On Unix, using a #GChildWatch source is
475 * equivalent to calling waitpid() or handling the %SIGCHLD signal
476 * manually. On Windows, calling g_spawn_close_pid() is equivalent
477 * to calling CloseHandle() on the process handle returned in
480 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
481 * descriptors will be inherited by the child; otherwise all
482 * descriptors except stdin/stdout/stderr will be closed before
483 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
484 * means that <literal>argv[0]</literal> need not be an absolute path, it
485 * will be looked for in the user's <envar>PATH</envar>.
486 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
487 * be discarded, instead of going to the same location as the parent's
488 * standard output. If you use this flag, @standard_output must be %NULL.
489 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
490 * will be discarded, instead of going to the same location as the parent's
491 * standard error. If you use this flag, @standard_error must be %NULL.
492 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
493 * standard input (by default, the child's standard input is attached to
494 * /dev/null). If you use this flag, @standard_input must be %NULL.
495 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
496 * the file to execute, while the remaining elements are the
497 * actual argument vector to pass to the file. Normally
498 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
499 * passes all of @argv to the child.
501 * @child_setup and @user_data are a function and user data. On POSIX
502 * platforms, the function is called in the child after GLib has
503 * performed all the setup it plans to perform (including creating
504 * pipes, closing file descriptors, etc.) but before calling
505 * exec(). That is, @child_setup is called just
506 * before calling exec() in the child. Obviously
507 * actions taken in this function will only affect the child, not the
508 * parent. On Windows, there is no separate fork() and exec()
509 * functionality. Child processes are created and run right away with
510 * one API call, CreateProcess(). @child_setup is
511 * called in the parent process just before creating the child
512 * process. You should carefully consider what you do in @child_setup
513 * if you intend your software to be portable to Windows.
515 * If non-%NULL, @child_pid will on Unix be filled with the child's
516 * process ID. You can use the process ID to send signals to the
517 * child, or to waitpid() if you specified the
518 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
519 * filled with a handle to the child process only if you specified the
520 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
521 * process using the Win32 API, for example wait for its termination
522 * with the <function>WaitFor*()</function> functions, or examine its
523 * exit code with GetExitCodeProcess(). You should close the handle
524 * with CloseHandle() when you no longer need it.
526 * If non-%NULL, the @standard_input, @standard_output, @standard_error
527 * locations will be filled with file descriptors for writing to the child's
528 * standard input or reading from its standard output or standard error.
529 * The caller of g_spawn_async_with_pipes() must close these file descriptors
530 * when they are no longer in use. If these parameters are %NULL, the corresponding
531 * pipe won't be created.
533 * If @standard_input is NULL, the child's standard input is attached to /dev/null
534 * unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
536 * If @standard_error is NULL, the child's standard error goes to the same location
537 * as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL is set.
539 * If @standard_output is NULL, the child's standard output goes to the same location
540 * as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL is set.
542 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
543 * If an error is set, the function returns %FALSE. Errors
544 * are reported even if they occur in the child (for example if the
545 * executable in <literal>argv[0]</literal> is not found). Typically
546 * the <literal>message</literal> field of returned errors should be displayed
547 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
549 * If an error occurs, @child_pid, @standard_input, @standard_output,
550 * and @standard_error will not be filled with valid values.
552 * If @child_pid is not %NULL and an error does not occur then the returned
553 * pid must be closed using g_spawn_close_pid().
555 * Return value: %TRUE on success, %FALSE if an error was set
558 g_spawn_async_with_pipes (const gchar *working_directory,
562 GSpawnChildSetupFunc child_setup,
565 gint *standard_input,
566 gint *standard_output,
567 gint *standard_error,
570 g_return_val_if_fail (argv != NULL, FALSE);
571 g_return_val_if_fail (standard_output == NULL ||
572 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
573 g_return_val_if_fail (standard_error == NULL ||
574 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
575 /* can't inherit stdin if we have an input pipe. */
576 g_return_val_if_fail (standard_input == NULL ||
577 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
579 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
583 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
584 (flags & G_SPAWN_SEARCH_PATH) != 0,
585 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
586 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
587 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
588 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
599 * g_spawn_command_line_sync:
600 * @command_line: a command line
601 * @standard_output: return location for child output
602 * @standard_error: return location for child errors
603 * @exit_status: return location for child exit status, as returned by waitpid()
604 * @error: return location for errors
606 * A simple version of g_spawn_sync() with little-used parameters
607 * removed, taking a command line instead of an argument vector. See
608 * g_spawn_sync() for full details. @command_line will be parsed by
609 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
610 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
611 * implications, so consider using g_spawn_sync() directly if
612 * appropriate. Possible errors are those from g_spawn_sync() and those
613 * from g_shell_parse_argv().
615 * If @exit_status is non-%NULL, the exit status of the child is stored there as
616 * it would be returned by waitpid(); standard UNIX macros such as WIFEXITED()
617 * and WEXITSTATUS() must be used to evaluate the exit status.
619 * On Windows, please note the implications of g_shell_parse_argv()
620 * parsing @command_line. Space is a separator, and backslashes are
621 * special. Thus you cannot simply pass a @command_line containing
622 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
623 * the backslashes will be eaten, and the space will act as a
624 * separator. You need to enclose such paths with single quotes, like
625 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
627 * Return value: %TRUE on success, %FALSE if an error was set
630 g_spawn_command_line_sync (const gchar *command_line,
631 gchar **standard_output,
632 gchar **standard_error,
639 g_return_val_if_fail (command_line != NULL, FALSE);
641 if (!g_shell_parse_argv (command_line,
646 retval = g_spawn_sync (NULL,
662 * g_spawn_command_line_async:
663 * @command_line: a command line
664 * @error: return location for errors
666 * A simple version of g_spawn_async() that parses a command line with
667 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
668 * command line in the background. Unlike g_spawn_async(), the
669 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
670 * that %G_SPAWN_SEARCH_PATH can have security implications, so
671 * consider using g_spawn_async() directly if appropriate. Possible
672 * errors are those from g_shell_parse_argv() and g_spawn_async().
674 * The same concerns on Windows apply as for g_spawn_command_line_sync().
676 * Return value: %TRUE on success, %FALSE if error is set.
679 g_spawn_command_line_async (const gchar *command_line,
685 g_return_val_if_fail (command_line != NULL, FALSE);
687 if (!g_shell_parse_argv (command_line,
692 retval = g_spawn_async (NULL,
706 exec_err_to_g_error (gint en)
712 return G_SPAWN_ERROR_ACCES;
718 return G_SPAWN_ERROR_PERM;
724 return G_SPAWN_ERROR_2BIG;
730 return G_SPAWN_ERROR_NOEXEC;
736 return G_SPAWN_ERROR_NAMETOOLONG;
742 return G_SPAWN_ERROR_NOENT;
748 return G_SPAWN_ERROR_NOMEM;
754 return G_SPAWN_ERROR_NOTDIR;
760 return G_SPAWN_ERROR_LOOP;
766 return G_SPAWN_ERROR_TXTBUSY;
772 return G_SPAWN_ERROR_IO;
778 return G_SPAWN_ERROR_NFILE;
784 return G_SPAWN_ERROR_MFILE;
790 return G_SPAWN_ERROR_INVAL;
796 return G_SPAWN_ERROR_ISDIR;
802 return G_SPAWN_ERROR_LIBBAD;
807 return G_SPAWN_ERROR_FAILED;
813 write_all (gint fd, gconstpointer vbuf, gsize to_write)
815 gchar *buf = (gchar *) vbuf;
819 gssize count = write (fd, buf, to_write);
836 write_err_and_exit (gint fd, gint msg)
840 write_all (fd, &msg, sizeof(msg));
841 write_all (fd, &en, sizeof(en));
847 set_cloexec (gint fd)
849 fcntl (fd, F_SETFD, FD_CLOEXEC);
853 sane_dup2 (gint fd1, gint fd2)
858 ret = dup2 (fd1, fd2);
859 if (ret < 0 && errno == EINTR)
874 do_exec (gint child_err_report_fd,
878 const gchar *working_directory,
881 gboolean close_descriptors,
882 gboolean search_path,
883 gboolean stdout_to_null,
884 gboolean stderr_to_null,
885 gboolean child_inherits_stdin,
886 gboolean file_and_argv_zero,
887 GSpawnChildSetupFunc child_setup,
890 if (working_directory && chdir (working_directory) < 0)
891 write_err_and_exit (child_err_report_fd,
894 /* Close all file descriptors but stdin stdout and stderr as
895 * soon as we exec. Note that this includes
896 * child_err_report_fd, which keeps the parent from blocking
897 * forever on the other end of that pipe.
899 if (close_descriptors)
904 open_max = sysconf (_SC_OPEN_MAX);
905 for (i = 3; i < open_max; i++)
910 /* We need to do child_err_report_fd anyway */
911 set_cloexec (child_err_report_fd);
914 /* Redirect pipes as required */
918 /* dup2 can't actually fail here I don't think */
920 if (sane_dup2 (stdin_fd, 0) < 0)
921 write_err_and_exit (child_err_report_fd,
924 /* ignore this if it doesn't work */
925 close_and_invalidate (&stdin_fd);
927 else if (!child_inherits_stdin)
929 /* Keep process from blocking on a read of stdin */
930 gint read_null = open ("/dev/null", O_RDONLY);
931 sane_dup2 (read_null, 0);
932 close_and_invalidate (&read_null);
937 /* dup2 can't actually fail here I don't think */
939 if (sane_dup2 (stdout_fd, 1) < 0)
940 write_err_and_exit (child_err_report_fd,
943 /* ignore this if it doesn't work */
944 close_and_invalidate (&stdout_fd);
946 else if (stdout_to_null)
948 gint write_null = open ("/dev/null", O_WRONLY);
949 sane_dup2 (write_null, 1);
950 close_and_invalidate (&write_null);
955 /* dup2 can't actually fail here I don't think */
957 if (sane_dup2 (stderr_fd, 2) < 0)
958 write_err_and_exit (child_err_report_fd,
961 /* ignore this if it doesn't work */
962 close_and_invalidate (&stderr_fd);
964 else if (stderr_to_null)
966 gint write_null = open ("/dev/null", O_WRONLY);
967 sane_dup2 (write_null, 2);
968 close_and_invalidate (&write_null);
971 /* Call user function just before we exec */
974 (* child_setup) (user_data);
978 file_and_argv_zero ? argv + 1 : argv,
982 write_err_and_exit (child_err_report_fd,
999 if (bytes >= sizeof(gint)*2)
1000 break; /* give up, who knows what happened, should not be
1006 ((gchar*)buf) + bytes,
1007 sizeof(gint) * n_ints_in_buf - bytes);
1008 if (chunk < 0 && errno == EINTR)
1013 /* Some weird shit happened, bail out */
1017 G_SPAWN_ERROR_FAILED,
1018 _("Failed to read from child pipe (%s)"),
1019 g_strerror (errno));
1023 else if (chunk == 0)
1025 else /* chunk > 0 */
1029 *n_ints_read = (gint)(bytes / sizeof(gint));
1035 fork_exec_with_pipes (gboolean intermediate_child,
1036 const gchar *working_directory,
1039 gboolean close_descriptors,
1040 gboolean search_path,
1041 gboolean stdout_to_null,
1042 gboolean stderr_to_null,
1043 gboolean child_inherits_stdin,
1044 gboolean file_and_argv_zero,
1045 GSpawnChildSetupFunc child_setup,
1048 gint *standard_input,
1049 gint *standard_output,
1050 gint *standard_error,
1054 gint stdin_pipe[2] = { -1, -1 };
1055 gint stdout_pipe[2] = { -1, -1 };
1056 gint stderr_pipe[2] = { -1, -1 };
1057 gint child_err_report_pipe[2] = { -1, -1 };
1058 gint child_pid_report_pipe[2] = { -1, -1 };
1061 if (!make_pipe (child_err_report_pipe, error))
1064 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1065 goto cleanup_and_fail;
1067 if (standard_input && !make_pipe (stdin_pipe, error))
1068 goto cleanup_and_fail;
1070 if (standard_output && !make_pipe (stdout_pipe, error))
1071 goto cleanup_and_fail;
1073 if (standard_error && !make_pipe (stderr_pipe, error))
1074 goto cleanup_and_fail;
1083 _("Failed to fork (%s)"),
1084 g_strerror (errno));
1086 goto cleanup_and_fail;
1090 /* Immediate child. This may or may not be the child that
1091 * actually execs the new process.
1094 /* Be sure we crash if the parent exits
1095 * and we write to the err_report_pipe
1097 signal (SIGPIPE, SIG_DFL);
1099 /* Close the parent's end of the pipes;
1100 * not needed in the close_descriptors case,
1103 close_and_invalidate (&child_err_report_pipe[0]);
1104 close_and_invalidate (&child_pid_report_pipe[0]);
1105 close_and_invalidate (&stdin_pipe[1]);
1106 close_and_invalidate (&stdout_pipe[0]);
1107 close_and_invalidate (&stderr_pipe[0]);
1109 if (intermediate_child)
1111 /* We need to fork an intermediate child that launches the
1112 * final child. The purpose of the intermediate child
1113 * is to exit, so we can waitpid() it immediately.
1114 * Then the grandchild will not become a zombie.
1116 GPid grandchild_pid;
1118 grandchild_pid = FORK1 ();
1120 if (grandchild_pid < 0)
1122 /* report -1 as child PID */
1123 write_all (child_pid_report_pipe[1], &grandchild_pid,
1124 sizeof(grandchild_pid));
1126 write_err_and_exit (child_err_report_pipe[1],
1129 else if (grandchild_pid == 0)
1131 do_exec (child_err_report_pipe[1],
1142 child_inherits_stdin,
1149 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1150 close_and_invalidate (&child_pid_report_pipe[1]);
1157 /* Just run the child.
1160 do_exec (child_err_report_pipe[1],
1171 child_inherits_stdin,
1184 /* Close the uncared-about ends of the pipes */
1185 close_and_invalidate (&child_err_report_pipe[1]);
1186 close_and_invalidate (&child_pid_report_pipe[1]);
1187 close_and_invalidate (&stdin_pipe[0]);
1188 close_and_invalidate (&stdout_pipe[1]);
1189 close_and_invalidate (&stderr_pipe[1]);
1191 /* If we had an intermediate child, reap it */
1192 if (intermediate_child)
1195 if (waitpid (pid, &status, 0) < 0)
1199 else if (errno == ECHILD)
1200 ; /* do nothing, child already reaped */
1202 g_warning ("waitpid() should not fail in "
1203 "'fork_exec_with_pipes'");
1208 if (!read_ints (child_err_report_pipe[0],
1211 goto cleanup_and_fail;
1215 /* Error from the child. */
1219 case CHILD_CHDIR_FAILED:
1222 G_SPAWN_ERROR_CHDIR,
1223 _("Failed to change to directory '%s' (%s)"),
1225 g_strerror (buf[1]));
1229 case CHILD_EXEC_FAILED:
1232 exec_err_to_g_error (buf[1]),
1233 _("Failed to execute child process \"%s\" (%s)"),
1235 g_strerror (buf[1]));
1239 case CHILD_DUP2_FAILED:
1242 G_SPAWN_ERROR_FAILED,
1243 _("Failed to redirect output or input of child process (%s)"),
1244 g_strerror (buf[1]));
1248 case CHILD_FORK_FAILED:
1252 _("Failed to fork child process (%s)"),
1253 g_strerror (buf[1]));
1259 G_SPAWN_ERROR_FAILED,
1260 _("Unknown error executing child process \"%s\""),
1265 goto cleanup_and_fail;
1268 /* Get child pid from intermediate child pipe. */
1269 if (intermediate_child)
1273 if (!read_ints (child_pid_report_pipe[0],
1274 buf, 1, &n_ints, error))
1275 goto cleanup_and_fail;
1281 G_SPAWN_ERROR_FAILED,
1282 _("Failed to read enough data from child pid pipe (%s)"),
1283 g_strerror (errno));
1284 goto cleanup_and_fail;
1288 /* we have the child pid */
1293 /* Success against all odds! return the information */
1294 close_and_invalidate (&child_err_report_pipe[0]);
1295 close_and_invalidate (&child_pid_report_pipe[0]);
1301 *standard_input = stdin_pipe[1];
1302 if (standard_output)
1303 *standard_output = stdout_pipe[0];
1305 *standard_error = stderr_pipe[0];
1312 /* There was an error from the Child, reap the child to avoid it being
1319 if (waitpid (pid, NULL, 0) < 0)
1323 else if (errno == ECHILD)
1324 ; /* do nothing, child already reaped */
1326 g_warning ("waitpid() should not fail in "
1327 "'fork_exec_with_pipes'");
1331 close_and_invalidate (&child_err_report_pipe[0]);
1332 close_and_invalidate (&child_err_report_pipe[1]);
1333 close_and_invalidate (&child_pid_report_pipe[0]);
1334 close_and_invalidate (&child_pid_report_pipe[1]);
1335 close_and_invalidate (&stdin_pipe[0]);
1336 close_and_invalidate (&stdin_pipe[1]);
1337 close_and_invalidate (&stdout_pipe[0]);
1338 close_and_invalidate (&stdout_pipe[1]);
1339 close_and_invalidate (&stderr_pipe[0]);
1340 close_and_invalidate (&stderr_pipe[1]);
1346 make_pipe (gint p[2],
1353 G_SPAWN_ERROR_FAILED,
1354 _("Failed to create pipe for communicating with child process (%s)"),
1355 g_strerror (errno));
1362 /* Based on execvp from GNU C Library */
1365 script_execute (const gchar *file,
1368 gboolean search_path)
1370 /* Count the arguments. */
1375 /* Construct an argument list for the shell. */
1379 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1381 new_argv[0] = (char *) "/bin/sh";
1382 new_argv[1] = (char *) file;
1385 new_argv[argc + 1] = argv[argc];
1389 /* Execute the shell. */
1391 execve (new_argv[0], new_argv, envp);
1393 execv (new_argv[0], new_argv);
1400 my_strchrnul (const gchar *str, gchar c)
1402 gchar *p = (gchar*) str;
1403 while (*p && (*p != c))
1410 g_execute (const gchar *file,
1413 gboolean search_path)
1417 /* We check the simple case first. */
1422 if (!search_path || strchr (file, '/') != NULL)
1424 /* Don't search when it contains a slash. */
1426 execve (file, argv, envp);
1430 if (errno == ENOEXEC)
1431 script_execute (file, argv, envp, FALSE);
1435 gboolean got_eacces = 0;
1436 const gchar *path, *p;
1437 gchar *name, *freeme;
1441 path = g_getenv ("PATH");
1444 /* There is no `PATH' in the environment. The default
1445 * search path in libc is the current directory followed by
1446 * the path `confstr' returns for `_CS_PATH'.
1449 /* In GLib we put . last, for security, and don't use the
1450 * unportable confstr(); UNIX98 does not actually specify
1451 * what to search if PATH is unset. POSIX may, dunno.
1454 path = "/bin:/usr/bin:.";
1457 len = strlen (file) + 1;
1458 pathlen = strlen (path);
1459 freeme = name = g_malloc (pathlen + len + 1);
1461 /* Copy the file name at the top, including '\0' */
1462 memcpy (name + pathlen + 1, file, len);
1463 name = name + pathlen;
1464 /* And add the slash before the filename */
1473 p = my_strchrnul (path, ':');
1476 /* Two adjacent colons, or a colon at the beginning or the end
1477 * of `PATH' means to search the current directory.
1481 startp = memcpy (name - (p - path), path, p - path);
1483 /* Try to execute this name. If it works, execv will not return. */
1485 execve (startp, argv, envp);
1487 execv (startp, argv);
1489 if (errno == ENOEXEC)
1490 script_execute (startp, argv, envp, search_path);
1495 /* Record the we got a `Permission denied' error. If we end
1496 * up finding no executable we can use, we want to diagnose
1497 * that we did find one but were denied access.
1510 /* Those errors indicate the file is missing or not executable
1511 * by us, in which case we want to just try the next path
1517 /* Some other error means we found an executable file, but
1518 * something went wrong executing it; return the error to our
1525 while (*p++ != '\0');
1527 /* We tried every element and none of them worked. */
1529 /* At least one failure was due to permissions, so report that
1537 /* Return the error from the last attempt (probably ENOENT). */
1542 * g_spawn_close_pid:
1543 * @pid: The process identifier to close
1545 * On some platforms, notably WIN32, the #GPid type represents a resource
1546 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1547 * is provided for this purpose. It should be used on all platforms, even
1548 * though it doesn't do anything under UNIX.
1551 g_spawn_close_pid (GPid pid)
1555 #define __G_SPAWN_C__
1556 #include "galiasdef.c"