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: 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
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 * On Windows, please note the implications of g_shell_parse_argv()
616 * parsing @command_line. Space is a separator, and backslashes are
617 * special. Thus you cannot simply pass a @command_line containing
618 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
619 * the backslashes will be eaten, and the space will act as a
620 * separator. You need to enclose such paths with single quotes, like
621 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
623 * Return value: %TRUE on success, %FALSE if an error was set
626 g_spawn_command_line_sync (const gchar *command_line,
627 gchar **standard_output,
628 gchar **standard_error,
635 g_return_val_if_fail (command_line != NULL, FALSE);
637 if (!g_shell_parse_argv (command_line,
642 retval = g_spawn_sync (NULL,
658 * g_spawn_command_line_async:
659 * @command_line: a command line
660 * @error: return location for errors
662 * A simple version of g_spawn_async() that parses a command line with
663 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
664 * command line in the background. Unlike g_spawn_async(), the
665 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
666 * that %G_SPAWN_SEARCH_PATH can have security implications, so
667 * consider using g_spawn_async() directly if appropriate. Possible
668 * errors are those from g_shell_parse_argv() and g_spawn_async().
670 * The same concerns on Windows apply as for g_spawn_command_line_sync().
672 * Return value: %TRUE on success, %FALSE if error is set.
675 g_spawn_command_line_async (const gchar *command_line,
681 g_return_val_if_fail (command_line != NULL, FALSE);
683 if (!g_shell_parse_argv (command_line,
688 retval = g_spawn_async (NULL,
702 exec_err_to_g_error (gint en)
708 return G_SPAWN_ERROR_ACCES;
714 return G_SPAWN_ERROR_PERM;
720 return G_SPAWN_ERROR_2BIG;
726 return G_SPAWN_ERROR_NOEXEC;
732 return G_SPAWN_ERROR_NAMETOOLONG;
738 return G_SPAWN_ERROR_NOENT;
744 return G_SPAWN_ERROR_NOMEM;
750 return G_SPAWN_ERROR_NOTDIR;
756 return G_SPAWN_ERROR_LOOP;
762 return G_SPAWN_ERROR_TXTBUSY;
768 return G_SPAWN_ERROR_IO;
774 return G_SPAWN_ERROR_NFILE;
780 return G_SPAWN_ERROR_MFILE;
786 return G_SPAWN_ERROR_INVAL;
792 return G_SPAWN_ERROR_ISDIR;
798 return G_SPAWN_ERROR_LIBBAD;
803 return G_SPAWN_ERROR_FAILED;
809 write_all (gint fd, gconstpointer vbuf, gsize to_write)
811 gchar *buf = (gchar *) vbuf;
815 gssize count = write (fd, buf, to_write);
832 write_err_and_exit (gint fd, gint msg)
836 write_all (fd, &msg, sizeof(msg));
837 write_all (fd, &en, sizeof(en));
843 set_cloexec (gint fd)
845 fcntl (fd, F_SETFD, FD_CLOEXEC);
849 sane_dup2 (gint fd1, gint fd2)
854 ret = dup2 (fd1, fd2);
855 if (ret < 0 && errno == EINTR)
870 do_exec (gint child_err_report_fd,
874 const gchar *working_directory,
877 gboolean close_descriptors,
878 gboolean search_path,
879 gboolean stdout_to_null,
880 gboolean stderr_to_null,
881 gboolean child_inherits_stdin,
882 gboolean file_and_argv_zero,
883 GSpawnChildSetupFunc child_setup,
886 if (working_directory && chdir (working_directory) < 0)
887 write_err_and_exit (child_err_report_fd,
890 /* Close all file descriptors but stdin stdout and stderr as
891 * soon as we exec. Note that this includes
892 * child_err_report_fd, which keeps the parent from blocking
893 * forever on the other end of that pipe.
895 if (close_descriptors)
900 open_max = sysconf (_SC_OPEN_MAX);
901 for (i = 3; i < open_max; i++)
906 /* We need to do child_err_report_fd anyway */
907 set_cloexec (child_err_report_fd);
910 /* Redirect pipes as required */
914 /* dup2 can't actually fail here I don't think */
916 if (sane_dup2 (stdin_fd, 0) < 0)
917 write_err_and_exit (child_err_report_fd,
920 /* ignore this if it doesn't work */
921 close_and_invalidate (&stdin_fd);
923 else if (!child_inherits_stdin)
925 /* Keep process from blocking on a read of stdin */
926 gint read_null = open ("/dev/null", O_RDONLY);
927 sane_dup2 (read_null, 0);
928 close_and_invalidate (&read_null);
933 /* dup2 can't actually fail here I don't think */
935 if (sane_dup2 (stdout_fd, 1) < 0)
936 write_err_and_exit (child_err_report_fd,
939 /* ignore this if it doesn't work */
940 close_and_invalidate (&stdout_fd);
942 else if (stdout_to_null)
944 gint write_null = open ("/dev/null", O_WRONLY);
945 sane_dup2 (write_null, 1);
946 close_and_invalidate (&write_null);
951 /* dup2 can't actually fail here I don't think */
953 if (sane_dup2 (stderr_fd, 2) < 0)
954 write_err_and_exit (child_err_report_fd,
957 /* ignore this if it doesn't work */
958 close_and_invalidate (&stderr_fd);
960 else if (stderr_to_null)
962 gint write_null = open ("/dev/null", O_WRONLY);
963 sane_dup2 (write_null, 2);
964 close_and_invalidate (&write_null);
967 /* Call user function just before we exec */
970 (* child_setup) (user_data);
974 file_and_argv_zero ? argv + 1 : argv,
978 write_err_and_exit (child_err_report_fd,
995 if (bytes >= sizeof(gint)*2)
996 break; /* give up, who knows what happened, should not be
1002 ((gchar*)buf) + bytes,
1003 sizeof(gint) * n_ints_in_buf - bytes);
1004 if (chunk < 0 && errno == EINTR)
1009 /* Some weird shit happened, bail out */
1013 G_SPAWN_ERROR_FAILED,
1014 _("Failed to read from child pipe (%s)"),
1015 g_strerror (errno));
1019 else if (chunk == 0)
1021 else /* chunk > 0 */
1025 *n_ints_read = (gint)(bytes / sizeof(gint));
1031 fork_exec_with_pipes (gboolean intermediate_child,
1032 const gchar *working_directory,
1035 gboolean close_descriptors,
1036 gboolean search_path,
1037 gboolean stdout_to_null,
1038 gboolean stderr_to_null,
1039 gboolean child_inherits_stdin,
1040 gboolean file_and_argv_zero,
1041 GSpawnChildSetupFunc child_setup,
1044 gint *standard_input,
1045 gint *standard_output,
1046 gint *standard_error,
1050 gint stdin_pipe[2] = { -1, -1 };
1051 gint stdout_pipe[2] = { -1, -1 };
1052 gint stderr_pipe[2] = { -1, -1 };
1053 gint child_err_report_pipe[2] = { -1, -1 };
1054 gint child_pid_report_pipe[2] = { -1, -1 };
1057 if (!make_pipe (child_err_report_pipe, error))
1060 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1061 goto cleanup_and_fail;
1063 if (standard_input && !make_pipe (stdin_pipe, error))
1064 goto cleanup_and_fail;
1066 if (standard_output && !make_pipe (stdout_pipe, error))
1067 goto cleanup_and_fail;
1069 if (standard_error && !make_pipe (stderr_pipe, error))
1070 goto cleanup_and_fail;
1079 _("Failed to fork (%s)"),
1080 g_strerror (errno));
1082 goto cleanup_and_fail;
1086 /* Immediate child. This may or may not be the child that
1087 * actually execs the new process.
1090 /* Be sure we crash if the parent exits
1091 * and we write to the err_report_pipe
1093 signal (SIGPIPE, SIG_DFL);
1095 /* Close the parent's end of the pipes;
1096 * not needed in the close_descriptors case,
1099 close_and_invalidate (&child_err_report_pipe[0]);
1100 close_and_invalidate (&child_pid_report_pipe[0]);
1101 close_and_invalidate (&stdin_pipe[1]);
1102 close_and_invalidate (&stdout_pipe[0]);
1103 close_and_invalidate (&stderr_pipe[0]);
1105 if (intermediate_child)
1107 /* We need to fork an intermediate child that launches the
1108 * final child. The purpose of the intermediate child
1109 * is to exit, so we can waitpid() it immediately.
1110 * Then the grandchild will not become a zombie.
1112 GPid grandchild_pid;
1114 grandchild_pid = FORK1 ();
1116 if (grandchild_pid < 0)
1118 /* report -1 as child PID */
1119 write_all (child_pid_report_pipe[1], &grandchild_pid,
1120 sizeof(grandchild_pid));
1122 write_err_and_exit (child_err_report_pipe[1],
1125 else if (grandchild_pid == 0)
1127 do_exec (child_err_report_pipe[1],
1138 child_inherits_stdin,
1145 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1146 close_and_invalidate (&child_pid_report_pipe[1]);
1153 /* Just run the child.
1156 do_exec (child_err_report_pipe[1],
1167 child_inherits_stdin,
1180 /* Close the uncared-about ends of the pipes */
1181 close_and_invalidate (&child_err_report_pipe[1]);
1182 close_and_invalidate (&child_pid_report_pipe[1]);
1183 close_and_invalidate (&stdin_pipe[0]);
1184 close_and_invalidate (&stdout_pipe[1]);
1185 close_and_invalidate (&stderr_pipe[1]);
1187 /* If we had an intermediate child, reap it */
1188 if (intermediate_child)
1191 if (waitpid (pid, &status, 0) < 0)
1195 else if (errno == ECHILD)
1196 ; /* do nothing, child already reaped */
1198 g_warning ("waitpid() should not fail in "
1199 "'fork_exec_with_pipes'");
1204 if (!read_ints (child_err_report_pipe[0],
1207 goto cleanup_and_fail;
1211 /* Error from the child. */
1215 case CHILD_CHDIR_FAILED:
1218 G_SPAWN_ERROR_CHDIR,
1219 _("Failed to change to directory '%s' (%s)"),
1221 g_strerror (buf[1]));
1225 case CHILD_EXEC_FAILED:
1228 exec_err_to_g_error (buf[1]),
1229 _("Failed to execute child process \"%s\" (%s)"),
1231 g_strerror (buf[1]));
1235 case CHILD_DUP2_FAILED:
1238 G_SPAWN_ERROR_FAILED,
1239 _("Failed to redirect output or input of child process (%s)"),
1240 g_strerror (buf[1]));
1244 case CHILD_FORK_FAILED:
1248 _("Failed to fork child process (%s)"),
1249 g_strerror (buf[1]));
1255 G_SPAWN_ERROR_FAILED,
1256 _("Unknown error executing child process \"%s\""),
1261 goto cleanup_and_fail;
1264 /* Get child pid from intermediate child pipe. */
1265 if (intermediate_child)
1269 if (!read_ints (child_pid_report_pipe[0],
1270 buf, 1, &n_ints, error))
1271 goto cleanup_and_fail;
1277 G_SPAWN_ERROR_FAILED,
1278 _("Failed to read enough data from child pid pipe (%s)"),
1279 g_strerror (errno));
1280 goto cleanup_and_fail;
1284 /* we have the child pid */
1289 /* Success against all odds! return the information */
1290 close_and_invalidate (&child_err_report_pipe[0]);
1291 close_and_invalidate (&child_pid_report_pipe[0]);
1297 *standard_input = stdin_pipe[1];
1298 if (standard_output)
1299 *standard_output = stdout_pipe[0];
1301 *standard_error = stderr_pipe[0];
1308 /* There was an error from the Child, reap the child to avoid it being
1315 if (waitpid (pid, NULL, 0) < 0)
1319 else if (errno == ECHILD)
1320 ; /* do nothing, child already reaped */
1322 g_warning ("waitpid() should not fail in "
1323 "'fork_exec_with_pipes'");
1327 close_and_invalidate (&child_err_report_pipe[0]);
1328 close_and_invalidate (&child_err_report_pipe[1]);
1329 close_and_invalidate (&child_pid_report_pipe[0]);
1330 close_and_invalidate (&child_pid_report_pipe[1]);
1331 close_and_invalidate (&stdin_pipe[0]);
1332 close_and_invalidate (&stdin_pipe[1]);
1333 close_and_invalidate (&stdout_pipe[0]);
1334 close_and_invalidate (&stdout_pipe[1]);
1335 close_and_invalidate (&stderr_pipe[0]);
1336 close_and_invalidate (&stderr_pipe[1]);
1342 make_pipe (gint p[2],
1349 G_SPAWN_ERROR_FAILED,
1350 _("Failed to create pipe for communicating with child process (%s)"),
1351 g_strerror (errno));
1358 /* Based on execvp from GNU C Library */
1361 script_execute (const gchar *file,
1364 gboolean search_path)
1366 /* Count the arguments. */
1371 /* Construct an argument list for the shell. */
1375 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1377 new_argv[0] = (char *) "/bin/sh";
1378 new_argv[1] = (char *) file;
1381 new_argv[argc + 1] = argv[argc];
1385 /* Execute the shell. */
1387 execve (new_argv[0], new_argv, envp);
1389 execv (new_argv[0], new_argv);
1396 my_strchrnul (const gchar *str, gchar c)
1398 gchar *p = (gchar*) str;
1399 while (*p && (*p != c))
1406 g_execute (const gchar *file,
1409 gboolean search_path)
1413 /* We check the simple case first. */
1418 if (!search_path || strchr (file, '/') != NULL)
1420 /* Don't search when it contains a slash. */
1422 execve (file, argv, envp);
1426 if (errno == ENOEXEC)
1427 script_execute (file, argv, envp, FALSE);
1431 gboolean got_eacces = 0;
1432 const gchar *path, *p;
1433 gchar *name, *freeme;
1437 path = g_getenv ("PATH");
1440 /* There is no `PATH' in the environment. The default
1441 * search path in libc is the current directory followed by
1442 * the path `confstr' returns for `_CS_PATH'.
1445 /* In GLib we put . last, for security, and don't use the
1446 * unportable confstr(); UNIX98 does not actually specify
1447 * what to search if PATH is unset. POSIX may, dunno.
1450 path = "/bin:/usr/bin:.";
1453 len = strlen (file) + 1;
1454 pathlen = strlen (path);
1455 freeme = name = g_malloc (pathlen + len + 1);
1457 /* Copy the file name at the top, including '\0' */
1458 memcpy (name + pathlen + 1, file, len);
1459 name = name + pathlen;
1460 /* And add the slash before the filename */
1469 p = my_strchrnul (path, ':');
1472 /* Two adjacent colons, or a colon at the beginning or the end
1473 * of `PATH' means to search the current directory.
1477 startp = memcpy (name - (p - path), path, p - path);
1479 /* Try to execute this name. If it works, execv will not return. */
1481 execve (startp, argv, envp);
1483 execv (startp, argv);
1485 if (errno == ENOEXEC)
1486 script_execute (startp, argv, envp, search_path);
1491 /* Record the we got a `Permission denied' error. If we end
1492 * up finding no executable we can use, we want to diagnose
1493 * that we did find one but were denied access.
1506 /* Those errors indicate the file is missing or not executable
1507 * by us, in which case we want to just try the next path
1513 /* Some other error means we found an executable file, but
1514 * something went wrong executing it; return the error to our
1521 while (*p++ != '\0');
1523 /* We tried every element and none of them worked. */
1525 /* At least one failure was due to permissions, so report that
1533 /* Return the error from the last attempt (probably ENOENT). */
1538 * g_spawn_close_pid:
1539 * @pid: The process identifier to close
1541 * On some platforms, notably WIN32, the #GPid type represents a resource
1542 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1543 * is provided for this purpose. It should be used on all platforms, even
1544 * though it doesn't do anything under UNIX.
1547 g_spawn_close_pid (GPid pid)