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>
33 #include <stdlib.h> /* for fdwalk */
36 #ifdef HAVE_SYS_SELECT_H
37 #include <sys/select.h>
38 #endif /* HAVE_SYS_SELECT_H */
40 #ifdef HAVE_SYS_RESOURCE_H
41 #include <sys/resource.h>
42 #endif /* HAVE_SYS_RESOURCE_H */
48 static gint g_execute (const gchar *file,
51 gboolean search_path);
53 static gboolean make_pipe (gint p[2],
55 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
56 const gchar *working_directory,
59 gboolean close_descriptors,
61 gboolean stdout_to_null,
62 gboolean stderr_to_null,
63 gboolean child_inherits_stdin,
64 gboolean file_and_argv_zero,
65 GSpawnChildSetupFunc child_setup,
69 gint *standard_output,
74 g_spawn_error_quark (void)
76 return g_quark_from_static_string ("g-exec-error-quark");
81 * @working_directory: child's current working directory, or %NULL to inherit parent's
82 * @argv: child's argument vector
83 * @envp: child's environment, or %NULL to inherit parent's
84 * @flags: flags from #GSpawnFlags
85 * @child_setup: function to run in the child just before exec()
86 * @user_data: user data for @child_setup
87 * @child_pid: return location for child process reference, or %NULL
88 * @error: return location for error
90 * See g_spawn_async_with_pipes() for a full description; this function
91 * simply calls the g_spawn_async_with_pipes() without any pipes.
93 * You should call g_spawn_close_pid() on the returned child process
94 * reference when you don't need it any more.
97 * If you are writing a GTK+ application, and the program you
98 * are spawning is a graphical application, too, then you may
99 * want to use gdk_spawn_on_screen() instead to ensure that
100 * the spawned program opens its windows on the right screen.
103 * <note><para> Note that the returned @child_pid on Windows is a
104 * handle to the child process and not its identifier. Process handles
105 * and process identifiers are different concepts on Windows.
108 * Return value: %TRUE on success, %FALSE if error is set
111 g_spawn_async (const gchar *working_directory,
115 GSpawnChildSetupFunc child_setup,
120 g_return_val_if_fail (argv != NULL, FALSE);
122 return g_spawn_async_with_pipes (working_directory,
132 /* Avoids a danger in threaded situations (calling close()
133 * on a file descriptor twice, and another thread has
134 * re-opened it since the first close)
137 close_and_invalidate (gint *fd)
152 /* Some versions of OS X define READ_OK in public headers */
157 READ_FAILED = 0, /* FALSE */
163 read_data (GString *str,
172 bytes = read (fd, buf, 4096);
178 g_string_append_len (str, buf, bytes);
181 else if (bytes < 0 && errno == EINTR)
190 _("Failed to read data from child process (%s)"),
201 * @working_directory: child's current working directory, or %NULL to inherit parent's
202 * @argv: child's argument vector
203 * @envp: child's environment, or %NULL to inherit parent's
204 * @flags: flags from #GSpawnFlags
205 * @child_setup: function to run in the child just before exec()
206 * @user_data: user data for @child_setup
207 * @standard_output: return location for child output, or %NULL
208 * @standard_error: return location for child error messages, or %NULL
209 * @exit_status: return location for child exit status, as returned by waitpid(), or %NULL
210 * @error: return location for error, or %NULL
212 * Executes a child synchronously (waits for the child to exit before returning).
213 * All output from the child is stored in @standard_output and @standard_error,
214 * if those parameters are non-%NULL. Note that you must set the
215 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
216 * passing %NULL for @standard_output and @standard_error.
217 * If @exit_status is non-%NULL, the exit status of the child is stored
218 * there as it would be returned by waitpid(); standard UNIX macros such
219 * as WIFEXITED() and WEXITSTATUS() must be used to evaluate the exit status.
220 * Note that this function call waitpid() even if @exit_status is %NULL, and
221 * does not accept the %G_SPAWN_DO_NOT_REAP_CHILD flag.
222 * If an error occurs, no data is returned in @standard_output,
223 * @standard_error, or @exit_status.
225 * This function calls g_spawn_async_with_pipes() internally; see that
226 * function for full details on the other parameters and details on
227 * how these functions work on Windows.
229 * Return value: %TRUE on success, %FALSE if an error was set.
232 g_spawn_sync (const gchar *working_directory,
236 GSpawnChildSetupFunc child_setup,
238 gchar **standard_output,
239 gchar **standard_error,
248 GString *outstr = NULL;
249 GString *errstr = NULL;
253 g_return_val_if_fail (argv != NULL, FALSE);
254 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
255 g_return_val_if_fail (standard_output == NULL ||
256 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
257 g_return_val_if_fail (standard_error == NULL ||
258 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
260 /* Just to ensure segfaults if callers try to use
261 * these when an error is reported.
264 *standard_output = NULL;
267 *standard_error = NULL;
269 if (!fork_exec_with_pipes (FALSE,
273 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
274 (flags & G_SPAWN_SEARCH_PATH) != 0,
275 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
276 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
277 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
278 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
283 standard_output ? &outpipe : NULL,
284 standard_error ? &errpipe : NULL,
288 /* Read data from child. */
294 outstr = g_string_new (NULL);
299 errstr = g_string_new (NULL);
302 /* Read data until we get EOF on both pipes. */
311 FD_SET (outpipe, &fds);
313 FD_SET (errpipe, &fds);
315 ret = select (MAX (outpipe, errpipe) + 1,
318 NULL /* no timeout */);
320 if (ret < 0 && errno != EINTR)
329 _("Unexpected error in select() reading data from a child process (%s)"),
335 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
337 switch (read_data (outstr, outpipe, error))
343 close_and_invalidate (&outpipe);
354 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
356 switch (read_data (errstr, errpipe, error))
362 close_and_invalidate (&errpipe);
374 /* These should only be open still if we had an error. */
377 close_and_invalidate (&outpipe);
379 close_and_invalidate (&errpipe);
381 /* Wait for child to exit, even if we have
386 ret = waitpid (pid, &status, 0);
392 else if (errno == ECHILD)
396 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.");
400 /* We don't need the exit status. */
405 if (!failed) /* avoid error pileups */
414 _("Unexpected error in waitpid() (%s)"),
423 g_string_free (outstr, TRUE);
425 g_string_free (errstr, TRUE);
432 *exit_status = status;
435 *standard_output = g_string_free (outstr, FALSE);
438 *standard_error = g_string_free (errstr, FALSE);
445 * g_spawn_async_with_pipes:
446 * @working_directory: child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
447 * @argv: child's argument vector, in the GLib file name encoding
448 * @envp: child's environment, or %NULL to inherit parent's, in the GLib file name encoding
449 * @flags: flags from #GSpawnFlags
450 * @child_setup: function to run in the child just before exec()
451 * @user_data: user data for @child_setup
452 * @child_pid: return location for child process ID, or %NULL
453 * @standard_input: return location for file descriptor to write to child's stdin, or %NULL
454 * @standard_output: return location for file descriptor to read child's stdout, or %NULL
455 * @standard_error: return location for file descriptor to read child's stderr, or %NULL
456 * @error: return location for error
458 * Executes a child program asynchronously (your program will not
459 * block waiting for the child to exit). The child program is
460 * specified by the only argument that must be provided, @argv. @argv
461 * should be a %NULL-terminated array of strings, to be passed as the
462 * argument vector for the child. The first string in @argv is of
463 * course the name of the program to execute. By default, the name of
464 * the program must be a full path; the <envar>PATH</envar> shell variable
465 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
467 * On Windows, note that all the string or string vector arguments to
468 * this function and the other g_spawn*() functions are in UTF-8, the
469 * GLib file name encoding. Unicode characters that are not part of
470 * the system codepage passed in these arguments will be correctly
471 * available in the spawned program only if it uses wide character API
472 * to retrieve its command line. For C programs built with Microsoft's
473 * tools it is enough to make the program have a wmain() instead of
474 * main(). wmain() has a wide character argument vector as parameter.
476 * At least currently, mingw doesn't support wmain(), so if you use
477 * mingw to develop the spawned program, it will have to call the
478 * undocumented function __wgetmainargs() to get the wide character
479 * argument vector and environment. See gspawn-win32-helper.c in the
480 * GLib sources or init.c in the mingw runtime sources for a prototype
481 * for that function. Alternatively, you can retrieve the Win32 system
482 * level wide character command line passed to the spawned program
483 * using the GetCommandLineW() function.
485 * On Windows the low-level child process creation API
486 * <function>CreateProcess()</function> doesn't use argument vectors,
487 * but a command line. The C runtime library's
488 * <function>spawn*()</function> family of functions (which
489 * g_spawn_async_with_pipes() eventually calls) paste the argument
490 * vector elements together into a command line, and the C runtime startup code
491 * does a corresponding reconstruction of an argument vector from the
492 * command line, to be passed to main(). Complications arise when you have
493 * argument vector elements that contain spaces of double quotes. The
494 * <function>spawn*()</function> functions don't do any quoting or
495 * escaping, but on the other hand the startup code does do unquoting
496 * and unescaping in order to enable receiving arguments with embedded
497 * spaces or double quotes. To work around this asymmetry,
498 * g_spawn_async_with_pipes() will do quoting and escaping on argument
499 * vector elements that need it before calling the C runtime
502 * The returned @child_pid on Windows is a handle to the child
503 * process, not its identifier. Process handles and process
504 * identifiers are different concepts on Windows.
506 * @envp is a %NULL-terminated array of strings, where each string
507 * has the form <literal>KEY=VALUE</literal>. This will become
508 * the child's environment. If @envp is %NULL, the child inherits its
509 * parent's environment.
511 * @flags should be the bitwise OR of any flags you want to affect the
512 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that
513 * the child will not automatically be reaped; you must use a
514 * #GChildWatch source to be notified about the death of the child
515 * process. Eventually you must call g_spawn_close_pid() on the
516 * @child_pid, in order to free resources which may be associated
517 * with the child process. (On Unix, using a #GChildWatch source is
518 * equivalent to calling waitpid() or handling the %SIGCHLD signal
519 * manually. On Windows, calling g_spawn_close_pid() is equivalent
520 * to calling CloseHandle() on the process handle returned in
523 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
524 * descriptors will be inherited by the child; otherwise all
525 * descriptors except stdin/stdout/stderr will be closed before
526 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
527 * means that <literal>argv[0]</literal> need not be an absolute path, it
528 * will be looked for in the user's <envar>PATH</envar>.
529 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
530 * be discarded, instead of going to the same location as the parent's
531 * standard output. If you use this flag, @standard_output must be %NULL.
532 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
533 * will be discarded, instead of going to the same location as the parent's
534 * standard error. If you use this flag, @standard_error must be %NULL.
535 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
536 * standard input (by default, the child's standard input is attached to
537 * /dev/null). If you use this flag, @standard_input must be %NULL.
538 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
539 * the file to execute, while the remaining elements are the
540 * actual argument vector to pass to the file. Normally
541 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
542 * passes all of @argv to the child.
544 * @child_setup and @user_data are a function and user data. On POSIX
545 * platforms, the function is called in the child after GLib has
546 * performed all the setup it plans to perform (including creating
547 * pipes, closing file descriptors, etc.) but before calling
548 * exec(). That is, @child_setup is called just
549 * before calling exec() in the child. Obviously
550 * actions taken in this function will only affect the child, not the
553 * On Windows, there is no separate fork() and exec()
554 * functionality. Child processes are created and run with a single
555 * API call, CreateProcess(). There is no sensible thing @child_setup
556 * could be used for on Windows so it is ignored and not called.
558 * If non-%NULL, @child_pid will on Unix be filled with the child's
559 * process ID. You can use the process ID to send signals to the
560 * child, or to use g_child_watch_add() (or waitpid()) if you specified the
561 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
562 * filled with a handle to the child process only if you specified the
563 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
564 * process using the Win32 API, for example wait for its termination
565 * with the <function>WaitFor*()</function> functions, or examine its
566 * exit code with GetExitCodeProcess(). You should close the handle
567 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
569 * If non-%NULL, the @standard_input, @standard_output, @standard_error
570 * locations will be filled with file descriptors for writing to the child's
571 * standard input or reading from its standard output or standard error.
572 * The caller of g_spawn_async_with_pipes() must close these file descriptors
573 * when they are no longer in use. If these parameters are %NULL, the corresponding
574 * pipe won't be created.
576 * If @standard_input is NULL, the child's standard input is attached to
577 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
579 * If @standard_error is NULL, the child's standard error goes to the same
580 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
583 * If @standard_output is NULL, the child's standard output goes to the same
584 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
587 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
588 * If an error is set, the function returns %FALSE. Errors
589 * are reported even if they occur in the child (for example if the
590 * executable in <literal>argv[0]</literal> is not found). Typically
591 * the <literal>message</literal> field of returned errors should be displayed
592 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
594 * If an error occurs, @child_pid, @standard_input, @standard_output,
595 * and @standard_error will not be filled with valid values.
597 * If @child_pid is not %NULL and an error does not occur then the returned
598 * process reference must be closed using g_spawn_close_pid().
601 * If you are writing a GTK+ application, and the program you
602 * are spawning is a graphical application, too, then you may
603 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
604 * the spawned program opens its windows on the right screen.
607 * Return value: %TRUE on success, %FALSE if an error was set
610 g_spawn_async_with_pipes (const gchar *working_directory,
614 GSpawnChildSetupFunc child_setup,
617 gint *standard_input,
618 gint *standard_output,
619 gint *standard_error,
622 g_return_val_if_fail (argv != NULL, FALSE);
623 g_return_val_if_fail (standard_output == NULL ||
624 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
625 g_return_val_if_fail (standard_error == NULL ||
626 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
627 /* can't inherit stdin if we have an input pipe. */
628 g_return_val_if_fail (standard_input == NULL ||
629 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
631 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
635 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
636 (flags & G_SPAWN_SEARCH_PATH) != 0,
637 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
638 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
639 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
640 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
651 * g_spawn_command_line_sync:
652 * @command_line: a command line
653 * @standard_output: return location for child output
654 * @standard_error: return location for child errors
655 * @exit_status: return location for child exit status, as returned by waitpid()
656 * @error: return location for errors
658 * A simple version of g_spawn_sync() with little-used parameters
659 * removed, taking a command line instead of an argument vector. See
660 * g_spawn_sync() for full details. @command_line will be parsed by
661 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
662 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
663 * implications, so consider using g_spawn_sync() directly if
664 * appropriate. Possible errors are those from g_spawn_sync() and those
665 * from g_shell_parse_argv().
667 * If @exit_status is non-%NULL, the exit status of the child is stored there as
668 * it would be returned by waitpid(); standard UNIX macros such as WIFEXITED()
669 * and WEXITSTATUS() must be used to evaluate the exit status.
671 * On Windows, please note the implications of g_shell_parse_argv()
672 * parsing @command_line. Parsing is done according to Unix shell rules, not
673 * Windows command interpreter rules.
674 * Space is a separator, and backslashes are
675 * special. Thus you cannot simply pass a @command_line containing
676 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
677 * the backslashes will be eaten, and the space will act as a
678 * separator. You need to enclose such paths with single quotes, like
679 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
681 * Return value: %TRUE on success, %FALSE if an error was set
684 g_spawn_command_line_sync (const gchar *command_line,
685 gchar **standard_output,
686 gchar **standard_error,
693 g_return_val_if_fail (command_line != NULL, FALSE);
695 if (!g_shell_parse_argv (command_line,
700 retval = g_spawn_sync (NULL,
716 * g_spawn_command_line_async:
717 * @command_line: a command line
718 * @error: return location for errors
720 * A simple version of g_spawn_async() that parses a command line with
721 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
722 * command line in the background. Unlike g_spawn_async(), the
723 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
724 * that %G_SPAWN_SEARCH_PATH can have security implications, so
725 * consider using g_spawn_async() directly if appropriate. Possible
726 * errors are those from g_shell_parse_argv() and g_spawn_async().
728 * The same concerns on Windows apply as for g_spawn_command_line_sync().
730 * Return value: %TRUE on success, %FALSE if error is set.
733 g_spawn_command_line_async (const gchar *command_line,
739 g_return_val_if_fail (command_line != NULL, FALSE);
741 if (!g_shell_parse_argv (command_line,
746 retval = g_spawn_async (NULL,
760 exec_err_to_g_error (gint en)
766 return G_SPAWN_ERROR_ACCES;
772 return G_SPAWN_ERROR_PERM;
778 return G_SPAWN_ERROR_2BIG;
784 return G_SPAWN_ERROR_NOEXEC;
790 return G_SPAWN_ERROR_NAMETOOLONG;
796 return G_SPAWN_ERROR_NOENT;
802 return G_SPAWN_ERROR_NOMEM;
808 return G_SPAWN_ERROR_NOTDIR;
814 return G_SPAWN_ERROR_LOOP;
820 return G_SPAWN_ERROR_TXTBUSY;
826 return G_SPAWN_ERROR_IO;
832 return G_SPAWN_ERROR_NFILE;
838 return G_SPAWN_ERROR_MFILE;
844 return G_SPAWN_ERROR_INVAL;
850 return G_SPAWN_ERROR_ISDIR;
856 return G_SPAWN_ERROR_LIBBAD;
861 return G_SPAWN_ERROR_FAILED;
867 write_all (gint fd, gconstpointer vbuf, gsize to_write)
869 gchar *buf = (gchar *) vbuf;
873 gssize count = write (fd, buf, to_write);
891 write_err_and_exit (gint fd, gint msg)
895 write_all (fd, &msg, sizeof(msg));
896 write_all (fd, &en, sizeof(en));
902 set_cloexec (void *data, gint fd)
904 if (fd >= GPOINTER_TO_INT (data))
905 fcntl (fd, F_SETFD, FD_CLOEXEC);
912 fdwalk (int (*cb)(void *data, int fd), void *data)
918 #ifdef HAVE_SYS_RESOURCE_H
925 if ((d = opendir("/proc/self/fd"))) {
928 while ((de = readdir(d))) {
932 if (de->d_name[0] == '.')
936 l = strtol(de->d_name, &e, 10);
937 if (errno != 0 || !e || *e)
948 if ((res = cb (data, fd)) != 0)
956 /* If /proc is not mounted or not accessible we fall back to the old
961 #ifdef HAVE_SYS_RESOURCE_H
963 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
964 open_max = rl.rlim_max;
967 open_max = sysconf (_SC_OPEN_MAX);
969 for (fd = 0; fd < open_max; fd++)
970 if ((res = cb (data, fd)) != 0)
978 sane_dup2 (gint fd1, gint fd2)
983 ret = dup2 (fd1, fd2);
984 if (ret < 0 && errno == EINTR)
999 do_exec (gint child_err_report_fd,
1003 const gchar *working_directory,
1006 gboolean close_descriptors,
1007 gboolean search_path,
1008 gboolean stdout_to_null,
1009 gboolean stderr_to_null,
1010 gboolean child_inherits_stdin,
1011 gboolean file_and_argv_zero,
1012 GSpawnChildSetupFunc child_setup,
1015 if (working_directory && chdir (working_directory) < 0)
1016 write_err_and_exit (child_err_report_fd,
1017 CHILD_CHDIR_FAILED);
1019 /* Close all file descriptors but stdin stdout and stderr as
1020 * soon as we exec. Note that this includes
1021 * child_err_report_fd, which keeps the parent from blocking
1022 * forever on the other end of that pipe.
1024 if (close_descriptors)
1026 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1030 /* We need to do child_err_report_fd anyway */
1031 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1034 /* Redirect pipes as required */
1038 /* dup2 can't actually fail here I don't think */
1040 if (sane_dup2 (stdin_fd, 0) < 0)
1041 write_err_and_exit (child_err_report_fd,
1044 /* ignore this if it doesn't work */
1045 close_and_invalidate (&stdin_fd);
1047 else if (!child_inherits_stdin)
1049 /* Keep process from blocking on a read of stdin */
1050 gint read_null = open ("/dev/null", O_RDONLY);
1051 sane_dup2 (read_null, 0);
1052 close_and_invalidate (&read_null);
1057 /* dup2 can't actually fail here I don't think */
1059 if (sane_dup2 (stdout_fd, 1) < 0)
1060 write_err_and_exit (child_err_report_fd,
1063 /* ignore this if it doesn't work */
1064 close_and_invalidate (&stdout_fd);
1066 else if (stdout_to_null)
1068 gint write_null = open ("/dev/null", O_WRONLY);
1069 sane_dup2 (write_null, 1);
1070 close_and_invalidate (&write_null);
1075 /* dup2 can't actually fail here I don't think */
1077 if (sane_dup2 (stderr_fd, 2) < 0)
1078 write_err_and_exit (child_err_report_fd,
1081 /* ignore this if it doesn't work */
1082 close_and_invalidate (&stderr_fd);
1084 else if (stderr_to_null)
1086 gint write_null = open ("/dev/null", O_WRONLY);
1087 sane_dup2 (write_null, 2);
1088 close_and_invalidate (&write_null);
1091 /* Call user function just before we exec */
1094 (* child_setup) (user_data);
1098 file_and_argv_zero ? argv + 1 : argv,
1102 write_err_and_exit (child_err_report_fd,
1119 if (bytes >= sizeof(gint)*2)
1120 break; /* give up, who knows what happened, should not be
1126 ((gchar*)buf) + bytes,
1127 sizeof(gint) * n_ints_in_buf - bytes);
1128 if (chunk < 0 && errno == EINTR)
1135 /* Some weird shit happened, bail out */
1138 G_SPAWN_ERROR_FAILED,
1139 _("Failed to read from child pipe (%s)"),
1140 g_strerror (errsv));
1144 else if (chunk == 0)
1146 else /* chunk > 0 */
1150 *n_ints_read = (gint)(bytes / sizeof(gint));
1156 fork_exec_with_pipes (gboolean intermediate_child,
1157 const gchar *working_directory,
1160 gboolean close_descriptors,
1161 gboolean search_path,
1162 gboolean stdout_to_null,
1163 gboolean stderr_to_null,
1164 gboolean child_inherits_stdin,
1165 gboolean file_and_argv_zero,
1166 GSpawnChildSetupFunc child_setup,
1169 gint *standard_input,
1170 gint *standard_output,
1171 gint *standard_error,
1175 gint stdin_pipe[2] = { -1, -1 };
1176 gint stdout_pipe[2] = { -1, -1 };
1177 gint stderr_pipe[2] = { -1, -1 };
1178 gint child_err_report_pipe[2] = { -1, -1 };
1179 gint child_pid_report_pipe[2] = { -1, -1 };
1182 if (!make_pipe (child_err_report_pipe, error))
1185 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1186 goto cleanup_and_fail;
1188 if (standard_input && !make_pipe (stdin_pipe, error))
1189 goto cleanup_and_fail;
1191 if (standard_output && !make_pipe (stdout_pipe, error))
1192 goto cleanup_and_fail;
1194 if (standard_error && !make_pipe (stderr_pipe, error))
1195 goto cleanup_and_fail;
1206 _("Failed to fork (%s)"),
1207 g_strerror (errsv));
1209 goto cleanup_and_fail;
1213 /* Immediate child. This may or may not be the child that
1214 * actually execs the new process.
1217 /* Be sure we crash if the parent exits
1218 * and we write to the err_report_pipe
1220 signal (SIGPIPE, SIG_DFL);
1222 /* Close the parent's end of the pipes;
1223 * not needed in the close_descriptors case,
1226 close_and_invalidate (&child_err_report_pipe[0]);
1227 close_and_invalidate (&child_pid_report_pipe[0]);
1228 close_and_invalidate (&stdin_pipe[1]);
1229 close_and_invalidate (&stdout_pipe[0]);
1230 close_and_invalidate (&stderr_pipe[0]);
1232 if (intermediate_child)
1234 /* We need to fork an intermediate child that launches the
1235 * final child. The purpose of the intermediate child
1236 * is to exit, so we can waitpid() it immediately.
1237 * Then the grandchild will not become a zombie.
1239 GPid grandchild_pid;
1241 grandchild_pid = fork ();
1243 if (grandchild_pid < 0)
1245 /* report -1 as child PID */
1246 write_all (child_pid_report_pipe[1], &grandchild_pid,
1247 sizeof(grandchild_pid));
1249 write_err_and_exit (child_err_report_pipe[1],
1252 else if (grandchild_pid == 0)
1254 do_exec (child_err_report_pipe[1],
1265 child_inherits_stdin,
1272 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1273 close_and_invalidate (&child_pid_report_pipe[1]);
1280 /* Just run the child.
1283 do_exec (child_err_report_pipe[1],
1294 child_inherits_stdin,
1307 /* Close the uncared-about ends of the pipes */
1308 close_and_invalidate (&child_err_report_pipe[1]);
1309 close_and_invalidate (&child_pid_report_pipe[1]);
1310 close_and_invalidate (&stdin_pipe[0]);
1311 close_and_invalidate (&stdout_pipe[1]);
1312 close_and_invalidate (&stderr_pipe[1]);
1314 /* If we had an intermediate child, reap it */
1315 if (intermediate_child)
1318 if (waitpid (pid, &status, 0) < 0)
1322 else if (errno == ECHILD)
1323 ; /* do nothing, child already reaped */
1325 g_warning ("waitpid() should not fail in "
1326 "'fork_exec_with_pipes'");
1331 if (!read_ints (child_err_report_pipe[0],
1334 goto cleanup_and_fail;
1338 /* Error from the child. */
1342 case CHILD_CHDIR_FAILED:
1345 G_SPAWN_ERROR_CHDIR,
1346 _("Failed to change to directory '%s' (%s)"),
1348 g_strerror (buf[1]));
1352 case CHILD_EXEC_FAILED:
1355 exec_err_to_g_error (buf[1]),
1356 _("Failed to execute child process \"%s\" (%s)"),
1358 g_strerror (buf[1]));
1362 case CHILD_DUP2_FAILED:
1365 G_SPAWN_ERROR_FAILED,
1366 _("Failed to redirect output or input of child process (%s)"),
1367 g_strerror (buf[1]));
1371 case CHILD_FORK_FAILED:
1375 _("Failed to fork child process (%s)"),
1376 g_strerror (buf[1]));
1382 G_SPAWN_ERROR_FAILED,
1383 _("Unknown error executing child process \"%s\""),
1388 goto cleanup_and_fail;
1391 /* Get child pid from intermediate child pipe. */
1392 if (intermediate_child)
1396 if (!read_ints (child_pid_report_pipe[0],
1397 buf, 1, &n_ints, error))
1398 goto cleanup_and_fail;
1406 G_SPAWN_ERROR_FAILED,
1407 _("Failed to read enough data from child pid pipe (%s)"),
1408 g_strerror (errsv));
1409 goto cleanup_and_fail;
1413 /* we have the child pid */
1418 /* Success against all odds! return the information */
1419 close_and_invalidate (&child_err_report_pipe[0]);
1420 close_and_invalidate (&child_pid_report_pipe[0]);
1426 *standard_input = stdin_pipe[1];
1427 if (standard_output)
1428 *standard_output = stdout_pipe[0];
1430 *standard_error = stderr_pipe[0];
1437 /* There was an error from the Child, reap the child to avoid it being
1444 if (waitpid (pid, NULL, 0) < 0)
1448 else if (errno == ECHILD)
1449 ; /* do nothing, child already reaped */
1451 g_warning ("waitpid() should not fail in "
1452 "'fork_exec_with_pipes'");
1456 close_and_invalidate (&child_err_report_pipe[0]);
1457 close_and_invalidate (&child_err_report_pipe[1]);
1458 close_and_invalidate (&child_pid_report_pipe[0]);
1459 close_and_invalidate (&child_pid_report_pipe[1]);
1460 close_and_invalidate (&stdin_pipe[0]);
1461 close_and_invalidate (&stdin_pipe[1]);
1462 close_and_invalidate (&stdout_pipe[0]);
1463 close_and_invalidate (&stdout_pipe[1]);
1464 close_and_invalidate (&stderr_pipe[0]);
1465 close_and_invalidate (&stderr_pipe[1]);
1471 make_pipe (gint p[2],
1479 G_SPAWN_ERROR_FAILED,
1480 _("Failed to create pipe for communicating with child process (%s)"),
1481 g_strerror (errsv));
1488 /* Based on execvp from GNU C Library */
1491 script_execute (const gchar *file,
1494 gboolean search_path)
1496 /* Count the arguments. */
1501 /* Construct an argument list for the shell. */
1505 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1507 new_argv[0] = (char *) "/bin/sh";
1508 new_argv[1] = (char *) file;
1511 new_argv[argc + 1] = argv[argc];
1515 /* Execute the shell. */
1517 execve (new_argv[0], new_argv, envp);
1519 execv (new_argv[0], new_argv);
1526 my_strchrnul (const gchar *str, gchar c)
1528 gchar *p = (gchar*) str;
1529 while (*p && (*p != c))
1536 g_execute (const gchar *file,
1539 gboolean search_path)
1543 /* We check the simple case first. */
1548 if (!search_path || strchr (file, '/') != NULL)
1550 /* Don't search when it contains a slash. */
1552 execve (file, argv, envp);
1556 if (errno == ENOEXEC)
1557 script_execute (file, argv, envp, FALSE);
1561 gboolean got_eacces = 0;
1562 const gchar *path, *p;
1563 gchar *name, *freeme;
1567 path = g_getenv ("PATH");
1570 /* There is no `PATH' in the environment. The default
1571 * search path in libc is the current directory followed by
1572 * the path `confstr' returns for `_CS_PATH'.
1575 /* In GLib we put . last, for security, and don't use the
1576 * unportable confstr(); UNIX98 does not actually specify
1577 * what to search if PATH is unset. POSIX may, dunno.
1580 path = "/bin:/usr/bin:.";
1583 len = strlen (file) + 1;
1584 pathlen = strlen (path);
1585 freeme = name = g_malloc (pathlen + len + 1);
1587 /* Copy the file name at the top, including '\0' */
1588 memcpy (name + pathlen + 1, file, len);
1589 name = name + pathlen;
1590 /* And add the slash before the filename */
1599 p = my_strchrnul (path, ':');
1602 /* Two adjacent colons, or a colon at the beginning or the end
1603 * of `PATH' means to search the current directory.
1607 startp = memcpy (name - (p - path), path, p - path);
1609 /* Try to execute this name. If it works, execv will not return. */
1611 execve (startp, argv, envp);
1613 execv (startp, argv);
1615 if (errno == ENOEXEC)
1616 script_execute (startp, argv, envp, search_path);
1621 /* Record the we got a `Permission denied' error. If we end
1622 * up finding no executable we can use, we want to diagnose
1623 * that we did find one but were denied access.
1636 /* Those errors indicate the file is missing or not executable
1637 * by us, in which case we want to just try the next path
1643 /* Some other error means we found an executable file, but
1644 * something went wrong executing it; return the error to our
1651 while (*p++ != '\0');
1653 /* We tried every element and none of them worked. */
1655 /* At least one failure was due to permissions, so report that
1663 /* Return the error from the last attempt (probably ENOENT). */
1668 * g_spawn_close_pid:
1669 * @pid: The process reference to close
1671 * On some platforms, notably Windows, the #GPid type represents a resource
1672 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1673 * is provided for this purpose. It should be used on all platforms, even
1674 * though it doesn't do anything under UNIX.
1677 g_spawn_close_pid (GPid pid)
1681 #define __G_SPAWN_C__
1682 #include "galiasdef.c"