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 static gint g_execute (const gchar *file,
46 gboolean search_path);
48 static gboolean make_pipe (gint p[2],
50 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
51 const gchar *working_directory,
54 gboolean close_descriptors,
56 gboolean stdout_to_null,
57 gboolean stderr_to_null,
58 gboolean child_inherits_stdin,
59 gboolean file_and_argv_zero,
60 GSpawnChildSetupFunc child_setup,
64 gint *standard_output,
69 g_spawn_error_quark (void)
71 return g_quark_from_static_string ("g-exec-error-quark");
76 * @working_directory: child's current working directory, or %NULL to inherit parent's
77 * @argv: child's argument vector
78 * @envp: child's environment, or %NULL to inherit parent's
79 * @flags: flags from #GSpawnFlags
80 * @child_setup: function to run in the child just before exec()
81 * @user_data: user data for @child_setup
82 * @child_pid: return location for child process ID, or %NULL
83 * @error: return location for error
85 * See g_spawn_async_with_pipes() for a full description; this function
86 * simply calls the g_spawn_async_with_pipes() without any pipes.
88 * Return value: %TRUE on success, %FALSE if error is set
91 g_spawn_async (const gchar *working_directory,
95 GSpawnChildSetupFunc child_setup,
100 g_return_val_if_fail (argv != NULL, FALSE);
102 return g_spawn_async_with_pipes (working_directory,
112 /* Avoids a danger in threaded situations (calling close()
113 * on a file descriptor twice, and another thread has
114 * re-opened it since the first close)
117 close_and_invalidate (gint *fd)
134 READ_FAILED = 0, /* FALSE */
140 read_data (GString *str,
149 bytes = read (fd, buf, 4096);
155 g_string_append_len (str, buf, bytes);
158 else if (bytes < 0 && errno == EINTR)
165 _("Failed to read data from child process (%s)"),
176 * @working_directory: child's current working directory, or %NULL to inherit parent's
177 * @argv: child's argument vector
178 * @envp: child's environment, or %NULL to inherit parent's
179 * @flags: flags from #GSpawnFlags
180 * @child_setup: function to run in the child just before exec()
181 * @user_data: user data for @child_setup
182 * @standard_output: return location for child output
183 * @standard_error: return location for child error messages
184 * @exit_status: return location for child exit status, as returned by waitpid()
185 * @error: return location for error
187 * Executes a child synchronously (waits for the child to exit before returning).
188 * All output from the child is stored in @standard_output and @standard_error,
189 * if those parameters are non-%NULL. If @exit_status is non-%NULL, the exit
190 * status of the child is stored there as it would be returned by
191 * waitpid(); standard UNIX macros such as WIFEXITED() and WEXITSTATUS()
192 * must be used to evaluate the exit status. If an error occurs, no data is
193 * returned in @standard_output, @standard_error, or @exit_status.
195 * This function calls g_spawn_async_with_pipes() internally; see that
196 * function for full details on the other parameters and details on
197 * how these functions work on Windows.
199 * Return value: %TRUE on success, %FALSE if an error was set.
202 g_spawn_sync (const gchar *working_directory,
206 GSpawnChildSetupFunc child_setup,
208 gchar **standard_output,
209 gchar **standard_error,
218 GString *outstr = NULL;
219 GString *errstr = NULL;
223 g_return_val_if_fail (argv != NULL, FALSE);
224 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
225 g_return_val_if_fail (standard_output == NULL ||
226 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
227 g_return_val_if_fail (standard_error == NULL ||
228 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
230 /* Just to ensure segfaults if callers try to use
231 * these when an error is reported.
234 *standard_output = NULL;
237 *standard_error = NULL;
239 if (!fork_exec_with_pipes (FALSE,
243 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
244 (flags & G_SPAWN_SEARCH_PATH) != 0,
245 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
246 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
247 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
248 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
253 standard_output ? &outpipe : NULL,
254 standard_error ? &errpipe : NULL,
258 /* Read data from child. */
264 outstr = g_string_new (NULL);
269 errstr = g_string_new (NULL);
272 /* Read data until we get EOF on both pipes. */
281 FD_SET (outpipe, &fds);
283 FD_SET (errpipe, &fds);
285 ret = select (MAX (outpipe, errpipe) + 1,
288 NULL /* no timeout */);
290 if (ret < 0 && errno != EINTR)
297 _("Unexpected error in select() reading data from a child process (%s)"),
303 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
305 switch (read_data (outstr, outpipe, error))
311 close_and_invalidate (&outpipe);
322 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
324 switch (read_data (errstr, errpipe, error))
330 close_and_invalidate (&errpipe);
342 /* These should only be open still if we had an error. */
345 close_and_invalidate (&outpipe);
347 close_and_invalidate (&errpipe);
349 /* Wait for child to exit, even if we have
354 ret = waitpid (pid, &status, 0);
360 else if (errno == ECHILD)
364 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.");
368 /* We don't need the exit status. */
373 if (!failed) /* avoid error pileups */
380 _("Unexpected error in waitpid() (%s)"),
389 g_string_free (outstr, TRUE);
391 g_string_free (errstr, TRUE);
398 *exit_status = status;
401 *standard_output = g_string_free (outstr, FALSE);
404 *standard_error = g_string_free (errstr, FALSE);
411 * g_spawn_async_with_pipes:
412 * @working_directory: child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
413 * @argv: child's argument vector, in the GLib file name encoding
414 * @envp: child's environment, or %NULL to inherit parent's, in the GLib file name encoding
415 * @flags: flags from #GSpawnFlags
416 * @child_setup: function to run in the child just before exec()
417 * @user_data: user data for @child_setup
418 * @child_pid: return location for child process ID, or %NULL
419 * @standard_input: return location for file descriptor to write to child's stdin, or %NULL
420 * @standard_output: return location for file descriptor to read child's stdout, or %NULL
421 * @standard_error: return location for file descriptor to read child's stderr, or %NULL
422 * @error: return location for error
424 * Executes a child program asynchronously (your program will not
425 * block waiting for the child to exit). The child program is
426 * specified by the only argument that must be provided, @argv. @argv
427 * should be a %NULL-terminated array of strings, to be passed as the
428 * argument vector for the child. The first string in @argv is of
429 * course the name of the program to execute. By default, the name of
430 * the program must be a full path; the <envar>PATH</envar> shell variable
431 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
433 * On Windows, note that all the string or string vector arguments to
434 * this function and the other g_spawn*() functions are in UTF-8, the
435 * GLib file name encoding. Unicode characters that are not part of
436 * the system codepage passed in argument vectors will be correctly
437 * available in the spawned program only if it uses wide character API
438 * to retrieve its command line. For C programs built with Microsoft's
439 * tools it is enough to make the program have a wmain() instead of
440 * main(). wmain() has a wide character argument vector as parameter.
442 * At least currently, mingw doesn't support wmain(), so if you use
443 * mingw to develop the spawned program, it will have to call the
444 * undocumented function __wgetmainargs() to get the wide character
445 * argument vector and environment. See gspawn-win32-helper.c in the
446 * GLib sources or init.c in the mingw runtime sources for a prototype
447 * for that function. Alternatively, you can retrieve the Win32 system
448 * level wide character command line passed to the spawned program
449 * using the GetCommandLineW() function.
451 * On Windows the low-level child process creation API
452 * <function>CreateProcess()</function> doesn't use argument vectors,
453 * but a command line. The C runtime library's
454 * <function>spawn*()</function> family of functions (which
455 * g_spawn_async_with_pipes() eventually calls) paste the argument
456 * vector elements together into a command line, and the C runtime startup code
457 * does a corresponding reconstruction of an argument vector from the
458 * command line, to be passed to main(). Complications arise when you have
459 * argument vector elements that contain spaces of double quotes. The
460 * <function>spawn*()</function> functions don't do any quoting or
461 * escaping, but on the other hand the startup code does do unquoting
462 * and unescaping in order to enable receiving arguments with embedded
463 * spaces or double quotes. To work around this asymmetry,
464 * g_spawn_async_with_pipes() will do quoting and escaping on argument
465 * vector elements that need it before calling the C runtime
468 * @envp is a %NULL-terminated array of strings, where each string
469 * has the form <literal>KEY=VALUE</literal>. This will become
470 * the child's environment. If @envp is %NULL, the child inherits its
471 * parent's environment.
473 * @flags should be the bitwise OR of any flags you want to affect the
474 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that
475 * the child will not automatically be reaped; you must use a
476 * #GChildWatch source to be notified about the death of the child
477 * process. Eventually you must call g_spawn_close_pid() on the
478 * @child_pid, in order to free resources which may be associated
479 * with the child process. (On Unix, using a #GChildWatch source is
480 * equivalent to calling waitpid() or handling the %SIGCHLD signal
481 * manually. On Windows, calling g_spawn_close_pid() is equivalent
482 * to calling CloseHandle() on the process handle returned in
485 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
486 * descriptors will be inherited by the child; otherwise all
487 * descriptors except stdin/stdout/stderr will be closed before
488 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
489 * means that <literal>argv[0]</literal> need not be an absolute path, it
490 * will be looked for in the user's <envar>PATH</envar>.
491 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
492 * be discarded, instead of going to the same location as the parent's
493 * standard output. If you use this flag, @standard_output must be %NULL.
494 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
495 * will be discarded, instead of going to the same location as the parent's
496 * standard error. If you use this flag, @standard_error must be %NULL.
497 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
498 * standard input (by default, the child's standard input is attached to
499 * /dev/null). If you use this flag, @standard_input must be %NULL.
500 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
501 * the file to execute, while the remaining elements are the
502 * actual argument vector to pass to the file. Normally
503 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
504 * passes all of @argv to the child.
506 * @child_setup and @user_data are a function and user data. On POSIX
507 * platforms, the function is called in the child after GLib has
508 * performed all the setup it plans to perform (including creating
509 * pipes, closing file descriptors, etc.) but before calling
510 * exec(). That is, @child_setup is called just
511 * before calling exec() in the child. Obviously
512 * actions taken in this function will only affect the child, not the
513 * parent. On Windows, there is no separate fork() and exec()
514 * functionality. Child processes are created and run with
515 * a single API call, CreateProcess(). @child_setup is
516 * called in the parent process just before creating the child
517 * process. You should carefully consider what you do in @child_setup
518 * if you intend your software to be portable to Windows.
520 * If non-%NULL, @child_pid will on Unix be filled with the child's
521 * process ID. You can use the process ID to send signals to the
522 * child, or to waitpid() if you specified the
523 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
524 * filled with a handle to the child process only if you specified the
525 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
526 * process using the Win32 API, for example wait for its termination
527 * with the <function>WaitFor*()</function> functions, or examine its
528 * exit code with GetExitCodeProcess(). You should close the handle
529 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
531 * If non-%NULL, the @standard_input, @standard_output, @standard_error
532 * locations will be filled with file descriptors for writing to the child's
533 * standard input or reading from its standard output or standard error.
534 * The caller of g_spawn_async_with_pipes() must close these file descriptors
535 * when they are no longer in use. If these parameters are %NULL, the corresponding
536 * pipe won't be created.
538 * If @standard_input is NULL, the child's standard input is attached to /dev/null
539 * unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
541 * If @standard_error is NULL, the child's standard error goes to the same location
542 * as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL is set.
544 * If @standard_output is NULL, the child's standard output goes to the same location
545 * as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL is set.
547 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
548 * If an error is set, the function returns %FALSE. Errors
549 * are reported even if they occur in the child (for example if the
550 * executable in <literal>argv[0]</literal> is not found). Typically
551 * the <literal>message</literal> field of returned errors should be displayed
552 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
554 * If an error occurs, @child_pid, @standard_input, @standard_output,
555 * and @standard_error will not be filled with valid values.
557 * If @child_pid is not %NULL and an error does not occur then the returned
558 * pid must be closed using g_spawn_close_pid().
560 * Return value: %TRUE on success, %FALSE if an error was set
563 g_spawn_async_with_pipes (const gchar *working_directory,
567 GSpawnChildSetupFunc child_setup,
570 gint *standard_input,
571 gint *standard_output,
572 gint *standard_error,
575 g_return_val_if_fail (argv != NULL, FALSE);
576 g_return_val_if_fail (standard_output == NULL ||
577 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
578 g_return_val_if_fail (standard_error == NULL ||
579 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
580 /* can't inherit stdin if we have an input pipe. */
581 g_return_val_if_fail (standard_input == NULL ||
582 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
584 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
588 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
589 (flags & G_SPAWN_SEARCH_PATH) != 0,
590 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
591 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
592 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
593 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
604 * g_spawn_command_line_sync:
605 * @command_line: a command line
606 * @standard_output: return location for child output
607 * @standard_error: return location for child errors
608 * @exit_status: return location for child exit status, as returned by waitpid()
609 * @error: return location for errors
611 * A simple version of g_spawn_sync() with little-used parameters
612 * removed, taking a command line instead of an argument vector. See
613 * g_spawn_sync() for full details. @command_line will be parsed by
614 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
615 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
616 * implications, so consider using g_spawn_sync() directly if
617 * appropriate. Possible errors are those from g_spawn_sync() and those
618 * from g_shell_parse_argv().
620 * If @exit_status is non-%NULL, the exit status of the child is stored there as
621 * it would be returned by waitpid(); standard UNIX macros such as WIFEXITED()
622 * and WEXITSTATUS() must be used to evaluate the exit status.
624 * On Windows, please note the implications of g_shell_parse_argv()
625 * parsing @command_line. Parsing is done according to Unix shell rules, not
626 * Windows command interpreter rules.
627 * Space is a separator, and backslashes are
628 * special. Thus you cannot simply pass a @command_line containing
629 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
630 * the backslashes will be eaten, and the space will act as a
631 * separator. You need to enclose such paths with single quotes, like
632 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
634 * Return value: %TRUE on success, %FALSE if an error was set
637 g_spawn_command_line_sync (const gchar *command_line,
638 gchar **standard_output,
639 gchar **standard_error,
646 g_return_val_if_fail (command_line != NULL, FALSE);
648 if (!g_shell_parse_argv (command_line,
653 retval = g_spawn_sync (NULL,
669 * g_spawn_command_line_async:
670 * @command_line: a command line
671 * @error: return location for errors
673 * A simple version of g_spawn_async() that parses a command line with
674 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
675 * command line in the background. Unlike g_spawn_async(), the
676 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
677 * that %G_SPAWN_SEARCH_PATH can have security implications, so
678 * consider using g_spawn_async() directly if appropriate. Possible
679 * errors are those from g_shell_parse_argv() and g_spawn_async().
681 * The same concerns on Windows apply as for g_spawn_command_line_sync().
683 * Return value: %TRUE on success, %FALSE if error is set.
686 g_spawn_command_line_async (const gchar *command_line,
692 g_return_val_if_fail (command_line != NULL, FALSE);
694 if (!g_shell_parse_argv (command_line,
699 retval = g_spawn_async (NULL,
713 exec_err_to_g_error (gint en)
719 return G_SPAWN_ERROR_ACCES;
725 return G_SPAWN_ERROR_PERM;
731 return G_SPAWN_ERROR_2BIG;
737 return G_SPAWN_ERROR_NOEXEC;
743 return G_SPAWN_ERROR_NAMETOOLONG;
749 return G_SPAWN_ERROR_NOENT;
755 return G_SPAWN_ERROR_NOMEM;
761 return G_SPAWN_ERROR_NOTDIR;
767 return G_SPAWN_ERROR_LOOP;
773 return G_SPAWN_ERROR_TXTBUSY;
779 return G_SPAWN_ERROR_IO;
785 return G_SPAWN_ERROR_NFILE;
791 return G_SPAWN_ERROR_MFILE;
797 return G_SPAWN_ERROR_INVAL;
803 return G_SPAWN_ERROR_ISDIR;
809 return G_SPAWN_ERROR_LIBBAD;
814 return G_SPAWN_ERROR_FAILED;
820 write_all (gint fd, gconstpointer vbuf, gsize to_write)
822 gchar *buf = (gchar *) vbuf;
826 gssize count = write (fd, buf, to_write);
843 write_err_and_exit (gint fd, gint msg)
847 write_all (fd, &msg, sizeof(msg));
848 write_all (fd, &en, sizeof(en));
854 set_cloexec (gint fd)
856 fcntl (fd, F_SETFD, FD_CLOEXEC);
860 sane_dup2 (gint fd1, gint fd2)
865 ret = dup2 (fd1, fd2);
866 if (ret < 0 && errno == EINTR)
881 do_exec (gint child_err_report_fd,
885 const gchar *working_directory,
888 gboolean close_descriptors,
889 gboolean search_path,
890 gboolean stdout_to_null,
891 gboolean stderr_to_null,
892 gboolean child_inherits_stdin,
893 gboolean file_and_argv_zero,
894 GSpawnChildSetupFunc child_setup,
897 if (working_directory && chdir (working_directory) < 0)
898 write_err_and_exit (child_err_report_fd,
901 /* Close all file descriptors but stdin stdout and stderr as
902 * soon as we exec. Note that this includes
903 * child_err_report_fd, which keeps the parent from blocking
904 * forever on the other end of that pipe.
906 if (close_descriptors)
911 open_max = sysconf (_SC_OPEN_MAX);
912 for (i = 3; i < open_max; i++)
917 /* We need to do child_err_report_fd anyway */
918 set_cloexec (child_err_report_fd);
921 /* Redirect pipes as required */
925 /* dup2 can't actually fail here I don't think */
927 if (sane_dup2 (stdin_fd, 0) < 0)
928 write_err_and_exit (child_err_report_fd,
931 /* ignore this if it doesn't work */
932 close_and_invalidate (&stdin_fd);
934 else if (!child_inherits_stdin)
936 /* Keep process from blocking on a read of stdin */
937 gint read_null = open ("/dev/null", O_RDONLY);
938 sane_dup2 (read_null, 0);
939 close_and_invalidate (&read_null);
944 /* dup2 can't actually fail here I don't think */
946 if (sane_dup2 (stdout_fd, 1) < 0)
947 write_err_and_exit (child_err_report_fd,
950 /* ignore this if it doesn't work */
951 close_and_invalidate (&stdout_fd);
953 else if (stdout_to_null)
955 gint write_null = open ("/dev/null", O_WRONLY);
956 sane_dup2 (write_null, 1);
957 close_and_invalidate (&write_null);
962 /* dup2 can't actually fail here I don't think */
964 if (sane_dup2 (stderr_fd, 2) < 0)
965 write_err_and_exit (child_err_report_fd,
968 /* ignore this if it doesn't work */
969 close_and_invalidate (&stderr_fd);
971 else if (stderr_to_null)
973 gint write_null = open ("/dev/null", O_WRONLY);
974 sane_dup2 (write_null, 2);
975 close_and_invalidate (&write_null);
978 /* Call user function just before we exec */
981 (* child_setup) (user_data);
985 file_and_argv_zero ? argv + 1 : argv,
989 write_err_and_exit (child_err_report_fd,
1006 if (bytes >= sizeof(gint)*2)
1007 break; /* give up, who knows what happened, should not be
1013 ((gchar*)buf) + bytes,
1014 sizeof(gint) * n_ints_in_buf - bytes);
1015 if (chunk < 0 && errno == EINTR)
1020 /* Some weird shit happened, bail out */
1024 G_SPAWN_ERROR_FAILED,
1025 _("Failed to read from child pipe (%s)"),
1026 g_strerror (errno));
1030 else if (chunk == 0)
1032 else /* chunk > 0 */
1036 *n_ints_read = (gint)(bytes / sizeof(gint));
1042 fork_exec_with_pipes (gboolean intermediate_child,
1043 const gchar *working_directory,
1046 gboolean close_descriptors,
1047 gboolean search_path,
1048 gboolean stdout_to_null,
1049 gboolean stderr_to_null,
1050 gboolean child_inherits_stdin,
1051 gboolean file_and_argv_zero,
1052 GSpawnChildSetupFunc child_setup,
1055 gint *standard_input,
1056 gint *standard_output,
1057 gint *standard_error,
1061 gint stdin_pipe[2] = { -1, -1 };
1062 gint stdout_pipe[2] = { -1, -1 };
1063 gint stderr_pipe[2] = { -1, -1 };
1064 gint child_err_report_pipe[2] = { -1, -1 };
1065 gint child_pid_report_pipe[2] = { -1, -1 };
1068 if (!make_pipe (child_err_report_pipe, error))
1071 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1072 goto cleanup_and_fail;
1074 if (standard_input && !make_pipe (stdin_pipe, error))
1075 goto cleanup_and_fail;
1077 if (standard_output && !make_pipe (stdout_pipe, error))
1078 goto cleanup_and_fail;
1080 if (standard_error && !make_pipe (stderr_pipe, error))
1081 goto cleanup_and_fail;
1090 _("Failed to fork (%s)"),
1091 g_strerror (errno));
1093 goto cleanup_and_fail;
1097 /* Immediate child. This may or may not be the child that
1098 * actually execs the new process.
1101 /* Be sure we crash if the parent exits
1102 * and we write to the err_report_pipe
1104 signal (SIGPIPE, SIG_DFL);
1106 /* Close the parent's end of the pipes;
1107 * not needed in the close_descriptors case,
1110 close_and_invalidate (&child_err_report_pipe[0]);
1111 close_and_invalidate (&child_pid_report_pipe[0]);
1112 close_and_invalidate (&stdin_pipe[1]);
1113 close_and_invalidate (&stdout_pipe[0]);
1114 close_and_invalidate (&stderr_pipe[0]);
1116 if (intermediate_child)
1118 /* We need to fork an intermediate child that launches the
1119 * final child. The purpose of the intermediate child
1120 * is to exit, so we can waitpid() it immediately.
1121 * Then the grandchild will not become a zombie.
1123 GPid grandchild_pid;
1125 grandchild_pid = fork ();
1127 if (grandchild_pid < 0)
1129 /* report -1 as child PID */
1130 write_all (child_pid_report_pipe[1], &grandchild_pid,
1131 sizeof(grandchild_pid));
1133 write_err_and_exit (child_err_report_pipe[1],
1136 else if (grandchild_pid == 0)
1138 do_exec (child_err_report_pipe[1],
1149 child_inherits_stdin,
1156 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1157 close_and_invalidate (&child_pid_report_pipe[1]);
1164 /* Just run the child.
1167 do_exec (child_err_report_pipe[1],
1178 child_inherits_stdin,
1191 /* Close the uncared-about ends of the pipes */
1192 close_and_invalidate (&child_err_report_pipe[1]);
1193 close_and_invalidate (&child_pid_report_pipe[1]);
1194 close_and_invalidate (&stdin_pipe[0]);
1195 close_and_invalidate (&stdout_pipe[1]);
1196 close_and_invalidate (&stderr_pipe[1]);
1198 /* If we had an intermediate child, reap it */
1199 if (intermediate_child)
1202 if (waitpid (pid, &status, 0) < 0)
1206 else if (errno == ECHILD)
1207 ; /* do nothing, child already reaped */
1209 g_warning ("waitpid() should not fail in "
1210 "'fork_exec_with_pipes'");
1215 if (!read_ints (child_err_report_pipe[0],
1218 goto cleanup_and_fail;
1222 /* Error from the child. */
1226 case CHILD_CHDIR_FAILED:
1229 G_SPAWN_ERROR_CHDIR,
1230 _("Failed to change to directory '%s' (%s)"),
1232 g_strerror (buf[1]));
1236 case CHILD_EXEC_FAILED:
1239 exec_err_to_g_error (buf[1]),
1240 _("Failed to execute child process \"%s\" (%s)"),
1242 g_strerror (buf[1]));
1246 case CHILD_DUP2_FAILED:
1249 G_SPAWN_ERROR_FAILED,
1250 _("Failed to redirect output or input of child process (%s)"),
1251 g_strerror (buf[1]));
1255 case CHILD_FORK_FAILED:
1259 _("Failed to fork child process (%s)"),
1260 g_strerror (buf[1]));
1266 G_SPAWN_ERROR_FAILED,
1267 _("Unknown error executing child process \"%s\""),
1272 goto cleanup_and_fail;
1275 /* Get child pid from intermediate child pipe. */
1276 if (intermediate_child)
1280 if (!read_ints (child_pid_report_pipe[0],
1281 buf, 1, &n_ints, error))
1282 goto cleanup_and_fail;
1288 G_SPAWN_ERROR_FAILED,
1289 _("Failed to read enough data from child pid pipe (%s)"),
1290 g_strerror (errno));
1291 goto cleanup_and_fail;
1295 /* we have the child pid */
1300 /* Success against all odds! return the information */
1301 close_and_invalidate (&child_err_report_pipe[0]);
1302 close_and_invalidate (&child_pid_report_pipe[0]);
1308 *standard_input = stdin_pipe[1];
1309 if (standard_output)
1310 *standard_output = stdout_pipe[0];
1312 *standard_error = stderr_pipe[0];
1319 /* There was an error from the Child, reap the child to avoid it being
1326 if (waitpid (pid, NULL, 0) < 0)
1330 else if (errno == ECHILD)
1331 ; /* do nothing, child already reaped */
1333 g_warning ("waitpid() should not fail in "
1334 "'fork_exec_with_pipes'");
1338 close_and_invalidate (&child_err_report_pipe[0]);
1339 close_and_invalidate (&child_err_report_pipe[1]);
1340 close_and_invalidate (&child_pid_report_pipe[0]);
1341 close_and_invalidate (&child_pid_report_pipe[1]);
1342 close_and_invalidate (&stdin_pipe[0]);
1343 close_and_invalidate (&stdin_pipe[1]);
1344 close_and_invalidate (&stdout_pipe[0]);
1345 close_and_invalidate (&stdout_pipe[1]);
1346 close_and_invalidate (&stderr_pipe[0]);
1347 close_and_invalidate (&stderr_pipe[1]);
1353 make_pipe (gint p[2],
1360 G_SPAWN_ERROR_FAILED,
1361 _("Failed to create pipe for communicating with child process (%s)"),
1362 g_strerror (errno));
1369 /* Based on execvp from GNU C Library */
1372 script_execute (const gchar *file,
1375 gboolean search_path)
1377 /* Count the arguments. */
1382 /* Construct an argument list for the shell. */
1386 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1388 new_argv[0] = (char *) "/bin/sh";
1389 new_argv[1] = (char *) file;
1392 new_argv[argc + 1] = argv[argc];
1396 /* Execute the shell. */
1398 execve (new_argv[0], new_argv, envp);
1400 execv (new_argv[0], new_argv);
1407 my_strchrnul (const gchar *str, gchar c)
1409 gchar *p = (gchar*) str;
1410 while (*p && (*p != c))
1417 g_execute (const gchar *file,
1420 gboolean search_path)
1424 /* We check the simple case first. */
1429 if (!search_path || strchr (file, '/') != NULL)
1431 /* Don't search when it contains a slash. */
1433 execve (file, argv, envp);
1437 if (errno == ENOEXEC)
1438 script_execute (file, argv, envp, FALSE);
1442 gboolean got_eacces = 0;
1443 const gchar *path, *p;
1444 gchar *name, *freeme;
1448 path = g_getenv ("PATH");
1451 /* There is no `PATH' in the environment. The default
1452 * search path in libc is the current directory followed by
1453 * the path `confstr' returns for `_CS_PATH'.
1456 /* In GLib we put . last, for security, and don't use the
1457 * unportable confstr(); UNIX98 does not actually specify
1458 * what to search if PATH is unset. POSIX may, dunno.
1461 path = "/bin:/usr/bin:.";
1464 len = strlen (file) + 1;
1465 pathlen = strlen (path);
1466 freeme = name = g_malloc (pathlen + len + 1);
1468 /* Copy the file name at the top, including '\0' */
1469 memcpy (name + pathlen + 1, file, len);
1470 name = name + pathlen;
1471 /* And add the slash before the filename */
1480 p = my_strchrnul (path, ':');
1483 /* Two adjacent colons, or a colon at the beginning or the end
1484 * of `PATH' means to search the current directory.
1488 startp = memcpy (name - (p - path), path, p - path);
1490 /* Try to execute this name. If it works, execv will not return. */
1492 execve (startp, argv, envp);
1494 execv (startp, argv);
1496 if (errno == ENOEXEC)
1497 script_execute (startp, argv, envp, search_path);
1502 /* Record the we got a `Permission denied' error. If we end
1503 * up finding no executable we can use, we want to diagnose
1504 * that we did find one but were denied access.
1517 /* Those errors indicate the file is missing or not executable
1518 * by us, in which case we want to just try the next path
1524 /* Some other error means we found an executable file, but
1525 * something went wrong executing it; return the error to our
1532 while (*p++ != '\0');
1534 /* We tried every element and none of them worked. */
1536 /* At least one failure was due to permissions, so report that
1544 /* Return the error from the last attempt (probably ENOENT). */
1549 * g_spawn_close_pid:
1550 * @pid: The process identifier to close
1552 * On some platforms, notably WIN32, the #GPid type represents a resource
1553 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1554 * is provided for this purpose. It should be used on all platforms, even
1555 * though it doesn't do anything under UNIX.
1558 g_spawn_close_pid (GPid pid)
1562 #define __G_SPAWN_C__
1563 #include "galiasdef.c"