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 exec()
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 exec()
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 waitpid()
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 * waitpid(); standard UNIX macros such as WIFEXITED() and WEXITSTATUS()
194 * must be used to evaluate the exit status. If an error occurs, no data is
195 * returned in @standard_output, @standard_error, or @exit_status.
197 * This function calls g_spawn_async_with_pipes() internally; see that function
198 * for full details on the other parameters.
200 * Return value: %TRUE on success, %FALSE if an error was set.
203 g_spawn_sync (const gchar *working_directory,
207 GSpawnChildSetupFunc child_setup,
209 gchar **standard_output,
210 gchar **standard_error,
219 GString *outstr = NULL;
220 GString *errstr = NULL;
224 g_return_val_if_fail (argv != NULL, FALSE);
225 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
226 g_return_val_if_fail (standard_output == NULL ||
227 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
228 g_return_val_if_fail (standard_error == NULL ||
229 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
231 /* Just to ensure segfaults if callers try to use
232 * these when an error is reported.
235 *standard_output = NULL;
238 *standard_error = NULL;
240 if (!fork_exec_with_pipes (FALSE,
244 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
245 (flags & G_SPAWN_SEARCH_PATH) != 0,
246 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
247 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
248 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
249 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
254 standard_output ? &outpipe : NULL,
255 standard_error ? &errpipe : NULL,
259 /* Read data from child. */
265 outstr = g_string_new (NULL);
270 errstr = g_string_new (NULL);
273 /* Read data until we get EOF on both pipes. */
282 FD_SET (outpipe, &fds);
284 FD_SET (errpipe, &fds);
286 ret = select (MAX (outpipe, errpipe) + 1,
289 NULL /* no timeout */);
291 if (ret < 0 && errno != EINTR)
298 _("Unexpected error in select() reading data from a child process (%s)"),
304 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
306 switch (read_data (outstr, outpipe, error))
312 close_and_invalidate (&outpipe);
323 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
325 switch (read_data (errstr, errpipe, error))
331 close_and_invalidate (&errpipe);
343 /* These should only be open still if we had an error. */
346 close_and_invalidate (&outpipe);
348 close_and_invalidate (&errpipe);
350 /* Wait for child to exit, even if we have
355 ret = waitpid (pid, &status, 0);
361 else if (errno == ECHILD)
365 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.");
369 /* We don't need the exit status. */
374 if (!failed) /* avoid error pileups */
381 _("Unexpected error in waitpid() (%s)"),
390 g_string_free (outstr, TRUE);
392 g_string_free (errstr, TRUE);
399 *exit_status = status;
402 *standard_output = g_string_free (outstr, FALSE);
405 *standard_error = g_string_free (errstr, FALSE);
412 * g_spawn_async_with_pipes:
413 * @working_directory: child's current working directory, or %NULL to inherit parent's
414 * @argv: child's argument vector
415 * @envp: child's environment, or %NULL to inherit parent's
416 * @flags: flags from #GSpawnFlags
417 * @child_setup: function to run in the child just before exec()
418 * @user_data: user data for @child_setup
419 * @child_pid: return location for child process ID, or %NULL
420 * @standard_input: return location for file descriptor to write to child's stdin, or %NULL
421 * @standard_output: return location for file descriptor to read child's stdout, or %NULL
422 * @standard_error: return location for file descriptor to read child's stderr, or %NULL
423 * @error: return location for error
425 * Executes a child program asynchronously (your program will not
426 * block waiting for the child to exit). The child program is
427 * specified by the only argument that must be provided, @argv. @argv
428 * should be a %NULL-terminated array of strings, to be passed as the
429 * argument vector for the child. The first string in @argv is of
430 * course the name of the program to execute. By default, the name of
431 * the program must be a full path; the <envar>PATH</envar> shell variable
432 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
434 * On Windows, the low-level child process creation API
435 * (CreateProcess())doesn't use argument vectors,
436 * but a command line. The C runtime library's
437 * <function>spawn*()</function> family of functions (which
438 * g_spawn_async_with_pipes() eventually calls) paste the argument
439 * vector elements into a command line, and the C runtime startup code
440 * does a corresponding recostruction of an argument vector from the
441 * command line, to be passed to main(). Complications arise when you have
442 * argument vector elements that contain spaces of double quotes. The
443 * <function>spawn*()</function> functions don't do any quoting or
444 * escaping, but on the other hand the startup code does do unquoting
445 * and unescaping in order to enable receiving arguments with embedded
446 * spaces or double quotes. To work around this asymmetry,
447 * g_spawn_async_with_pipes() will do quoting and escaping on argument
448 * vector elements that need it before calling the C runtime
451 * @envp is a %NULL-terminated array of strings, where each string
452 * has the form <literal>KEY=VALUE</literal>. This will become
453 * the child's environment. If @envp is %NULL, the child inherits its
454 * parent's environment.
456 * @flags should be the bitwise OR of any flags you want to affect the
457 * function's behavior. On Unix, the %G_SPAWN_DO_NOT_REAP_CHILD means
458 * that the child will not be automatically reaped; you must call
459 * waitpid() or handle %SIGCHLD yourself, or the
460 * child will become a zombie. On Windows, the flag means that a
461 * handle to the child will be returned @child_pid. You must call
462 * CloseHandle() on it eventually (or exit the
463 * process), or the child processs will continue to take up some table
464 * space even after its death. Quite similar to zombies on Unix,
467 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
468 * descriptors will be inherited by the child; otherwise all
469 * descriptors except stdin/stdout/stderr will be closed before
470 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
471 * means that <literal>argv[0]</literal> need not be an absolute path, it
472 * will be looked for in the user's <envar>PATH</envar>.
473 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
474 * be discarded, instead of going to the same location as the parent's
475 * standard output. If you use this flag, @standard_output must be %NULL.
476 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
477 * will be discarded, instead of going to the same location as the parent's
478 * standard error. If you use this flag, @standard_error must be %NULL.
479 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
480 * standard input (by default, the child's standard input is attached to
481 * /dev/null). If you use this flag, @standard_input must be %NULL.
482 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
483 * the file to execute, while the remaining elements are the
484 * actual argument vector to pass to the file. Normally
485 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
486 * passes all of @argv to the child.
488 * @child_setup and @user_data are a function and user data. On POSIX
489 * platforms, the function is called in the child after GLib has
490 * performed all the setup it plans to perform (including creating
491 * pipes, closing file descriptors, etc.) but before calling
492 * exec(). That is, @child_setup is called just
493 * before calling exec() in the child. Obviously
494 * actions taken in this function will only affect the child, not the
495 * parent. On Windows, there is no separate fork() and exec()
496 * functionality. Child processes are created and run right away with
497 * one API call, CreateProcess(). @child_setup is
498 * called in the parent process just before creating the child
499 * process. You should carefully consider what you do in @child_setup
500 * if you intend your software to be portable to Windows.
502 * If non-%NULL, @child_pid will on Unix be filled with the child's
503 * process ID. You can use the process ID to send signals to the
504 * child, or to waitpid() if you specified the
505 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
506 * filled with a handle to the child process only if you specified the
507 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
508 * process using the Win32 API, for example wait for its termination
509 * with the <function>WaitFor*()</function> functions, or examine its
510 * exit code with GetExitCodeProcess(). You should close the handle
511 * with CloseHandle() when you no longer need it.
513 * If non-%NULL, the @standard_input, @standard_output, @standard_error
514 * locations will be filled with file descriptors for writing to the child's
515 * standard input or reading from its standard output or standard error.
516 * The caller of g_spawn_async_with_pipes() must close these file descriptors
517 * when they are no longer in use. If these parameters are %NULL, the corresponding
518 * pipe won't be created.
520 * If @standard_input is NULL, the child's standard input is attached to /dev/null
521 * unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
523 * If @standard_error is NULL, the child's standard error goes to the same location
524 * as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL is set.
526 * If @standard_output is NULL, the child's standard output goes to the same location
527 * as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL is set.
529 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
530 * If an error is set, the function returns %FALSE. Errors
531 * are reported even if they occur in the child (for example if the
532 * executable in <literal>argv[0]</literal> is not found). Typically
533 * the <literal>message</literal> field of returned errors should be displayed
534 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
536 * If an error occurs, @child_pid, @standard_input, @standard_output,
537 * and @standard_error will not be filled with valid values.
539 * If @child_pid is not %NULL and an error does not occur then the returned
540 * pid must be closed using g_spawn_close_pid().
542 * Return value: %TRUE on success, %FALSE if an error was set
545 g_spawn_async_with_pipes (const gchar *working_directory,
549 GSpawnChildSetupFunc child_setup,
552 gint *standard_input,
553 gint *standard_output,
554 gint *standard_error,
557 g_return_val_if_fail (argv != NULL, FALSE);
558 g_return_val_if_fail (standard_output == NULL ||
559 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
560 g_return_val_if_fail (standard_error == NULL ||
561 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
562 /* can't inherit stdin if we have an input pipe. */
563 g_return_val_if_fail (standard_input == NULL ||
564 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
566 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
570 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
571 (flags & G_SPAWN_SEARCH_PATH) != 0,
572 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
573 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
574 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
575 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
586 * g_spawn_command_line_sync:
587 * @command_line: a command line
588 * @standard_output: return location for child output
589 * @standard_error: return location for child errors
590 * @exit_status: return location for child exit status
591 * @error: return location for errors
593 * A simple version of g_spawn_sync() with little-used parameters
594 * removed, taking a command line instead of an argument vector. See
595 * g_spawn_sync() for full details. @command_line will be parsed by
596 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
597 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
598 * implications, so consider using g_spawn_sync() directly if
599 * appropriate. Possible errors are those from g_spawn_sync() and those
600 * from g_shell_parse_argv().
602 * On Windows, please note the implications of g_shell_parse_argv()
603 * parsing @command_line. Space is a separator, and backslashes are
604 * special. Thus you cannot simply pass a @command_line containing
605 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
606 * the backslashes will be eaten, and the space will act as a
607 * separator. You need to enclose such paths with single quotes, like
608 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
610 * Return value: %TRUE on success, %FALSE if an error was set
613 g_spawn_command_line_sync (const gchar *command_line,
614 gchar **standard_output,
615 gchar **standard_error,
622 g_return_val_if_fail (command_line != NULL, FALSE);
624 if (!g_shell_parse_argv (command_line,
629 retval = g_spawn_sync (NULL,
645 * g_spawn_command_line_async:
646 * @command_line: a command line
647 * @error: return location for errors
649 * A simple version of g_spawn_async() that parses a command line with
650 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
651 * command line in the background. Unlike g_spawn_async(), the
652 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
653 * that %G_SPAWN_SEARCH_PATH can have security implications, so
654 * consider using g_spawn_async() directly if appropriate. Possible
655 * errors are those from g_shell_parse_argv() and g_spawn_async().
657 * The same concerns on Windows apply as for g_spawn_command_line_sync().
659 * Return value: %TRUE on success, %FALSE if error is set.
662 g_spawn_command_line_async (const gchar *command_line,
668 g_return_val_if_fail (command_line != NULL, FALSE);
670 if (!g_shell_parse_argv (command_line,
675 retval = g_spawn_async (NULL,
689 exec_err_to_g_error (gint en)
695 return G_SPAWN_ERROR_ACCES;
701 return G_SPAWN_ERROR_PERM;
707 return G_SPAWN_ERROR_2BIG;
713 return G_SPAWN_ERROR_NOEXEC;
719 return G_SPAWN_ERROR_NAMETOOLONG;
725 return G_SPAWN_ERROR_NOENT;
731 return G_SPAWN_ERROR_NOMEM;
737 return G_SPAWN_ERROR_NOTDIR;
743 return G_SPAWN_ERROR_LOOP;
749 return G_SPAWN_ERROR_TXTBUSY;
755 return G_SPAWN_ERROR_IO;
761 return G_SPAWN_ERROR_NFILE;
767 return G_SPAWN_ERROR_MFILE;
773 return G_SPAWN_ERROR_INVAL;
779 return G_SPAWN_ERROR_ISDIR;
785 return G_SPAWN_ERROR_LIBBAD;
790 return G_SPAWN_ERROR_FAILED;
796 write_all (gint fd, gconstpointer vbuf, gsize to_write)
798 gchar *buf = (gchar *) vbuf;
802 gssize count = write (fd, buf, to_write);
819 write_err_and_exit (gint fd, gint msg)
823 write_all (fd, &msg, sizeof(msg));
824 write_all (fd, &en, sizeof(en));
830 set_cloexec (gint fd)
832 fcntl (fd, F_SETFD, FD_CLOEXEC);
836 sane_dup2 (gint fd1, gint fd2)
841 ret = dup2 (fd1, fd2);
842 if (ret < 0 && errno == EINTR)
857 do_exec (gint child_err_report_fd,
861 const gchar *working_directory,
864 gboolean close_descriptors,
865 gboolean search_path,
866 gboolean stdout_to_null,
867 gboolean stderr_to_null,
868 gboolean child_inherits_stdin,
869 gboolean file_and_argv_zero,
870 GSpawnChildSetupFunc child_setup,
873 if (working_directory && chdir (working_directory) < 0)
874 write_err_and_exit (child_err_report_fd,
877 /* Close all file descriptors but stdin stdout and stderr as
878 * soon as we exec. Note that this includes
879 * child_err_report_fd, which keeps the parent from blocking
880 * forever on the other end of that pipe.
882 if (close_descriptors)
887 open_max = sysconf (_SC_OPEN_MAX);
888 for (i = 3; i < open_max; i++)
893 /* We need to do child_err_report_fd anyway */
894 set_cloexec (child_err_report_fd);
897 /* Redirect pipes as required */
901 /* dup2 can't actually fail here I don't think */
903 if (sane_dup2 (stdin_fd, 0) < 0)
904 write_err_and_exit (child_err_report_fd,
907 /* ignore this if it doesn't work */
908 close_and_invalidate (&stdin_fd);
910 else if (!child_inherits_stdin)
912 /* Keep process from blocking on a read of stdin */
913 gint read_null = open ("/dev/null", O_RDONLY);
914 sane_dup2 (read_null, 0);
915 close_and_invalidate (&read_null);
920 /* dup2 can't actually fail here I don't think */
922 if (sane_dup2 (stdout_fd, 1) < 0)
923 write_err_and_exit (child_err_report_fd,
926 /* ignore this if it doesn't work */
927 close_and_invalidate (&stdout_fd);
929 else if (stdout_to_null)
931 gint write_null = open ("/dev/null", O_WRONLY);
932 sane_dup2 (write_null, 1);
933 close_and_invalidate (&write_null);
938 /* dup2 can't actually fail here I don't think */
940 if (sane_dup2 (stderr_fd, 2) < 0)
941 write_err_and_exit (child_err_report_fd,
944 /* ignore this if it doesn't work */
945 close_and_invalidate (&stderr_fd);
947 else if (stderr_to_null)
949 gint write_null = open ("/dev/null", O_WRONLY);
950 sane_dup2 (write_null, 2);
951 close_and_invalidate (&write_null);
954 /* Call user function just before we exec */
957 (* child_setup) (user_data);
961 file_and_argv_zero ? argv + 1 : argv,
965 write_err_and_exit (child_err_report_fd,
982 if (bytes >= sizeof(gint)*2)
983 break; /* give up, who knows what happened, should not be
989 ((gchar*)buf) + bytes,
990 sizeof(gint) * n_ints_in_buf - bytes);
991 if (chunk < 0 && errno == EINTR)
996 /* Some weird shit happened, bail out */
1000 G_SPAWN_ERROR_FAILED,
1001 _("Failed to read from child pipe (%s)"),
1002 g_strerror (errno));
1006 else if (chunk == 0)
1008 else /* chunk > 0 */
1012 *n_ints_read = (gint)(bytes / sizeof(gint));
1018 fork_exec_with_pipes (gboolean intermediate_child,
1019 const gchar *working_directory,
1022 gboolean close_descriptors,
1023 gboolean search_path,
1024 gboolean stdout_to_null,
1025 gboolean stderr_to_null,
1026 gboolean child_inherits_stdin,
1027 gboolean file_and_argv_zero,
1028 GSpawnChildSetupFunc child_setup,
1031 gint *standard_input,
1032 gint *standard_output,
1033 gint *standard_error,
1037 gint stdin_pipe[2] = { -1, -1 };
1038 gint stdout_pipe[2] = { -1, -1 };
1039 gint stderr_pipe[2] = { -1, -1 };
1040 gint child_err_report_pipe[2] = { -1, -1 };
1041 gint child_pid_report_pipe[2] = { -1, -1 };
1044 if (!make_pipe (child_err_report_pipe, error))
1047 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1048 goto cleanup_and_fail;
1050 if (standard_input && !make_pipe (stdin_pipe, error))
1051 goto cleanup_and_fail;
1053 if (standard_output && !make_pipe (stdout_pipe, error))
1054 goto cleanup_and_fail;
1056 if (standard_error && !make_pipe (stderr_pipe, error))
1057 goto cleanup_and_fail;
1066 _("Failed to fork (%s)"),
1067 g_strerror (errno));
1069 goto cleanup_and_fail;
1073 /* Immediate child. This may or may not be the child that
1074 * actually execs the new process.
1077 /* Be sure we crash if the parent exits
1078 * and we write to the err_report_pipe
1080 signal (SIGPIPE, SIG_DFL);
1082 /* Close the parent's end of the pipes;
1083 * not needed in the close_descriptors case,
1086 close_and_invalidate (&child_err_report_pipe[0]);
1087 close_and_invalidate (&child_pid_report_pipe[0]);
1088 close_and_invalidate (&stdin_pipe[1]);
1089 close_and_invalidate (&stdout_pipe[0]);
1090 close_and_invalidate (&stderr_pipe[0]);
1092 if (intermediate_child)
1094 /* We need to fork an intermediate child that launches the
1095 * final child. The purpose of the intermediate child
1096 * is to exit, so we can waitpid() it immediately.
1097 * Then the grandchild will not become a zombie.
1099 GPid grandchild_pid;
1101 grandchild_pid = fork ();
1103 if (grandchild_pid < 0)
1105 /* report -1 as child PID */
1106 write_all (child_pid_report_pipe[1], &grandchild_pid,
1107 sizeof(grandchild_pid));
1109 write_err_and_exit (child_err_report_pipe[1],
1112 else if (grandchild_pid == 0)
1114 do_exec (child_err_report_pipe[1],
1125 child_inherits_stdin,
1132 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1133 close_and_invalidate (&child_pid_report_pipe[1]);
1140 /* Just run the child.
1143 do_exec (child_err_report_pipe[1],
1154 child_inherits_stdin,
1167 /* Close the uncared-about ends of the pipes */
1168 close_and_invalidate (&child_err_report_pipe[1]);
1169 close_and_invalidate (&child_pid_report_pipe[1]);
1170 close_and_invalidate (&stdin_pipe[0]);
1171 close_and_invalidate (&stdout_pipe[1]);
1172 close_and_invalidate (&stderr_pipe[1]);
1174 /* If we had an intermediate child, reap it */
1175 if (intermediate_child)
1178 if (waitpid (pid, &status, 0) < 0)
1182 else if (errno == ECHILD)
1183 ; /* do nothing, child already reaped */
1185 g_warning ("waitpid() should not fail in "
1186 "'fork_exec_with_pipes'");
1191 if (!read_ints (child_err_report_pipe[0],
1194 goto cleanup_and_fail;
1198 /* Error from the child. */
1202 case CHILD_CHDIR_FAILED:
1205 G_SPAWN_ERROR_CHDIR,
1206 _("Failed to change to directory '%s' (%s)"),
1208 g_strerror (buf[1]));
1212 case CHILD_EXEC_FAILED:
1215 exec_err_to_g_error (buf[1]),
1216 _("Failed to execute child process \"%s\" (%s)"),
1218 g_strerror (buf[1]));
1222 case CHILD_DUP2_FAILED:
1225 G_SPAWN_ERROR_FAILED,
1226 _("Failed to redirect output or input of child process (%s)"),
1227 g_strerror (buf[1]));
1231 case CHILD_FORK_FAILED:
1235 _("Failed to fork child process (%s)"),
1236 g_strerror (buf[1]));
1242 G_SPAWN_ERROR_FAILED,
1243 _("Unknown error executing child process \"%s\""),
1248 goto cleanup_and_fail;
1251 /* Get child pid from intermediate child pipe. */
1252 if (intermediate_child)
1256 if (!read_ints (child_pid_report_pipe[0],
1257 buf, 1, &n_ints, error))
1258 goto cleanup_and_fail;
1264 G_SPAWN_ERROR_FAILED,
1265 _("Failed to read enough data from child pid pipe (%s)"),
1266 g_strerror (errno));
1267 goto cleanup_and_fail;
1271 /* we have the child pid */
1276 /* Success against all odds! return the information */
1277 close_and_invalidate (&child_err_report_pipe[0]);
1278 close_and_invalidate (&child_pid_report_pipe[0]);
1284 *standard_input = stdin_pipe[1];
1285 if (standard_output)
1286 *standard_output = stdout_pipe[0];
1288 *standard_error = stderr_pipe[0];
1295 /* There was an error from the Child, reap the child to avoid it being
1302 if (waitpid (pid, NULL, 0) < 0)
1306 else if (errno == ECHILD)
1307 ; /* do nothing, child already reaped */
1309 g_warning ("waitpid() should not fail in "
1310 "'fork_exec_with_pipes'");
1314 close_and_invalidate (&child_err_report_pipe[0]);
1315 close_and_invalidate (&child_err_report_pipe[1]);
1316 close_and_invalidate (&child_pid_report_pipe[0]);
1317 close_and_invalidate (&child_pid_report_pipe[1]);
1318 close_and_invalidate (&stdin_pipe[0]);
1319 close_and_invalidate (&stdin_pipe[1]);
1320 close_and_invalidate (&stdout_pipe[0]);
1321 close_and_invalidate (&stdout_pipe[1]);
1322 close_and_invalidate (&stderr_pipe[0]);
1323 close_and_invalidate (&stderr_pipe[1]);
1329 make_pipe (gint p[2],
1336 G_SPAWN_ERROR_FAILED,
1337 _("Failed to create pipe for communicating with child process (%s)"),
1338 g_strerror (errno));
1345 /* Based on execvp from GNU C Library */
1348 script_execute (const gchar *file,
1351 gboolean search_path)
1353 /* Count the arguments. */
1358 /* Construct an argument list for the shell. */
1362 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1364 new_argv[0] = (char *) "/bin/sh";
1365 new_argv[1] = (char *) file;
1368 new_argv[argc + 1] = argv[argc];
1372 /* Execute the shell. */
1374 execve (new_argv[0], new_argv, envp);
1376 execv (new_argv[0], new_argv);
1383 my_strchrnul (const gchar *str, gchar c)
1385 gchar *p = (gchar*) str;
1386 while (*p && (*p != c))
1393 g_execute (const gchar *file,
1396 gboolean search_path)
1400 /* We check the simple case first. */
1405 if (!search_path || strchr (file, '/') != NULL)
1407 /* Don't search when it contains a slash. */
1409 execve (file, argv, envp);
1413 if (errno == ENOEXEC)
1414 script_execute (file, argv, envp, FALSE);
1418 gboolean got_eacces = 0;
1419 const gchar *path, *p;
1420 gchar *name, *freeme;
1424 path = g_getenv ("PATH");
1427 /* There is no `PATH' in the environment. The default
1428 * search path in libc is the current directory followed by
1429 * the path `confstr' returns for `_CS_PATH'.
1432 /* In GLib we put . last, for security, and don't use the
1433 * unportable confstr(); UNIX98 does not actually specify
1434 * what to search if PATH is unset. POSIX may, dunno.
1437 path = "/bin:/usr/bin:.";
1440 len = strlen (file) + 1;
1441 pathlen = strlen (path);
1442 freeme = name = g_malloc (pathlen + len + 1);
1444 /* Copy the file name at the top, including '\0' */
1445 memcpy (name + pathlen + 1, file, len);
1446 name = name + pathlen;
1447 /* And add the slash before the filename */
1456 p = my_strchrnul (path, ':');
1459 /* Two adjacent colons, or a colon at the beginning or the end
1460 * of `PATH' means to search the current directory.
1464 startp = memcpy (name - (p - path), path, p - path);
1466 /* Try to execute this name. If it works, execv will not return. */
1468 execve (startp, argv, envp);
1470 execv (startp, argv);
1472 if (errno == ENOEXEC)
1473 script_execute (startp, argv, envp, search_path);
1478 /* Record the we got a `Permission denied' error. If we end
1479 * up finding no executable we can use, we want to diagnose
1480 * that we did find one but were denied access.
1493 /* Those errors indicate the file is missing or not executable
1494 * by us, in which case we want to just try the next path
1500 /* Some other error means we found an executable file, but
1501 * something went wrong executing it; return the error to our
1508 while (*p++ != '\0');
1510 /* We tried every element and none of them worked. */
1512 /* At least one failure was due to permissions, so report that
1520 /* Return the error from the last attempt (probably ENOENT). */
1525 * g_spawn_close_pid:
1526 * @pid: The process identifier to close
1528 * On some platforms, notably WIN32, the #GPid type represents a resource
1529 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1530 * is provided for this purpose. It should be used on all platforms, even
1531 * though it doesn't do anything under UNIX.
1534 g_spawn_close_pid (GPid pid)