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)
188 _("Failed to read data from child process (%s)"),
199 * @working_directory: child's current working directory, or %NULL to inherit parent's
200 * @argv: child's argument vector
201 * @envp: child's environment, or %NULL to inherit parent's
202 * @flags: flags from #GSpawnFlags
203 * @child_setup: function to run in the child just before exec()
204 * @user_data: user data for @child_setup
205 * @standard_output: return location for child output, or %NULL
206 * @standard_error: return location for child error messages, or %NULL
207 * @exit_status: return location for child exit status, as returned by waitpid(), or %NULL
208 * @error: return location for error, or %NULL
210 * Executes a child synchronously (waits for the child to exit before returning).
211 * All output from the child is stored in @standard_output and @standard_error,
212 * if those parameters are non-%NULL. Note that you must set the
213 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
214 * passing %NULL for @standard_output and @standard_error.
215 * If @exit_status is non-%NULL, the exit status of the child is stored
216 * there as it would be returned by waitpid(); standard UNIX macros such
217 * as WIFEXITED() and WEXITSTATUS() must be used to evaluate the exit status.
218 * Note that this function call waitpid() even if @exit_status is %NULL, and
219 * does not accept the %G_SPAWN_DO_NOT_REAP_CHILD flag.
220 * If an error occurs, no data is returned in @standard_output,
221 * @standard_error, or @exit_status.
223 * This function calls g_spawn_async_with_pipes() internally; see that
224 * function for full details on the other parameters and details on
225 * how these functions work on Windows.
227 * Return value: %TRUE on success, %FALSE if an error was set.
230 g_spawn_sync (const gchar *working_directory,
234 GSpawnChildSetupFunc child_setup,
236 gchar **standard_output,
237 gchar **standard_error,
246 GString *outstr = NULL;
247 GString *errstr = NULL;
251 g_return_val_if_fail (argv != NULL, FALSE);
252 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
253 g_return_val_if_fail (standard_output == NULL ||
254 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
255 g_return_val_if_fail (standard_error == NULL ||
256 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
258 /* Just to ensure segfaults if callers try to use
259 * these when an error is reported.
262 *standard_output = NULL;
265 *standard_error = NULL;
267 if (!fork_exec_with_pipes (FALSE,
271 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
272 (flags & G_SPAWN_SEARCH_PATH) != 0,
273 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
274 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
275 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
276 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
281 standard_output ? &outpipe : NULL,
282 standard_error ? &errpipe : NULL,
286 /* Read data from child. */
292 outstr = g_string_new (NULL);
297 errstr = g_string_new (NULL);
300 /* Read data until we get EOF on both pipes. */
309 FD_SET (outpipe, &fds);
311 FD_SET (errpipe, &fds);
313 ret = select (MAX (outpipe, errpipe) + 1,
316 NULL /* no timeout */);
318 if (ret < 0 && errno != EINTR)
325 _("Unexpected error in select() reading data from a child process (%s)"),
331 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
333 switch (read_data (outstr, outpipe, error))
339 close_and_invalidate (&outpipe);
350 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
352 switch (read_data (errstr, errpipe, error))
358 close_and_invalidate (&errpipe);
370 /* These should only be open still if we had an error. */
373 close_and_invalidate (&outpipe);
375 close_and_invalidate (&errpipe);
377 /* Wait for child to exit, even if we have
382 ret = waitpid (pid, &status, 0);
388 else if (errno == ECHILD)
392 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.");
396 /* We don't need the exit status. */
401 if (!failed) /* avoid error pileups */
408 _("Unexpected error in waitpid() (%s)"),
417 g_string_free (outstr, TRUE);
419 g_string_free (errstr, TRUE);
426 *exit_status = status;
429 *standard_output = g_string_free (outstr, FALSE);
432 *standard_error = g_string_free (errstr, FALSE);
439 * g_spawn_async_with_pipes:
440 * @working_directory: child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
441 * @argv: child's argument vector, in the GLib file name encoding
442 * @envp: child's environment, or %NULL to inherit parent's, in the GLib file name encoding
443 * @flags: flags from #GSpawnFlags
444 * @child_setup: function to run in the child just before exec()
445 * @user_data: user data for @child_setup
446 * @child_pid: return location for child process ID, or %NULL
447 * @standard_input: return location for file descriptor to write to child's stdin, or %NULL
448 * @standard_output: return location for file descriptor to read child's stdout, or %NULL
449 * @standard_error: return location for file descriptor to read child's stderr, or %NULL
450 * @error: return location for error
452 * Executes a child program asynchronously (your program will not
453 * block waiting for the child to exit). The child program is
454 * specified by the only argument that must be provided, @argv. @argv
455 * should be a %NULL-terminated array of strings, to be passed as the
456 * argument vector for the child. The first string in @argv is of
457 * course the name of the program to execute. By default, the name of
458 * the program must be a full path; the <envar>PATH</envar> shell variable
459 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
461 * On Windows, note that all the string or string vector arguments to
462 * this function and the other g_spawn*() functions are in UTF-8, the
463 * GLib file name encoding. Unicode characters that are not part of
464 * the system codepage passed in these arguments will be correctly
465 * available in the spawned program only if it uses wide character API
466 * to retrieve its command line. For C programs built with Microsoft's
467 * tools it is enough to make the program have a wmain() instead of
468 * main(). wmain() has a wide character argument vector as parameter.
470 * At least currently, mingw doesn't support wmain(), so if you use
471 * mingw to develop the spawned program, it will have to call the
472 * undocumented function __wgetmainargs() to get the wide character
473 * argument vector and environment. See gspawn-win32-helper.c in the
474 * GLib sources or init.c in the mingw runtime sources for a prototype
475 * for that function. Alternatively, you can retrieve the Win32 system
476 * level wide character command line passed to the spawned program
477 * using the GetCommandLineW() function.
479 * On Windows the low-level child process creation API
480 * <function>CreateProcess()</function> doesn't use argument vectors,
481 * but a command line. The C runtime library's
482 * <function>spawn*()</function> family of functions (which
483 * g_spawn_async_with_pipes() eventually calls) paste the argument
484 * vector elements together into a command line, and the C runtime startup code
485 * does a corresponding reconstruction of an argument vector from the
486 * command line, to be passed to main(). Complications arise when you have
487 * argument vector elements that contain spaces of double quotes. The
488 * <function>spawn*()</function> functions don't do any quoting or
489 * escaping, but on the other hand the startup code does do unquoting
490 * and unescaping in order to enable receiving arguments with embedded
491 * spaces or double quotes. To work around this asymmetry,
492 * g_spawn_async_with_pipes() will do quoting and escaping on argument
493 * vector elements that need it before calling the C runtime
496 * The returned @child_pid on Windows is a handle to the child
497 * process, not its identifier. Process handles and process
498 * identifiers are different concepts on Windows.
500 * @envp is a %NULL-terminated array of strings, where each string
501 * has the form <literal>KEY=VALUE</literal>. This will become
502 * the child's environment. If @envp is %NULL, the child inherits its
503 * parent's environment.
505 * @flags should be the bitwise OR of any flags you want to affect the
506 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that
507 * the child will not automatically be reaped; you must use a
508 * #GChildWatch source to be notified about the death of the child
509 * process. Eventually you must call g_spawn_close_pid() on the
510 * @child_pid, in order to free resources which may be associated
511 * with the child process. (On Unix, using a #GChildWatch source is
512 * equivalent to calling waitpid() or handling the %SIGCHLD signal
513 * manually. On Windows, calling g_spawn_close_pid() is equivalent
514 * to calling CloseHandle() on the process handle returned in
517 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
518 * descriptors will be inherited by the child; otherwise all
519 * descriptors except stdin/stdout/stderr will be closed before
520 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
521 * means that <literal>argv[0]</literal> need not be an absolute path, it
522 * will be looked for in the user's <envar>PATH</envar>.
523 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
524 * be discarded, instead of going to the same location as the parent's
525 * standard output. If you use this flag, @standard_output must be %NULL.
526 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
527 * will be discarded, instead of going to the same location as the parent's
528 * standard error. If you use this flag, @standard_error must be %NULL.
529 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
530 * standard input (by default, the child's standard input is attached to
531 * /dev/null). If you use this flag, @standard_input must be %NULL.
532 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
533 * the file to execute, while the remaining elements are the
534 * actual argument vector to pass to the file. Normally
535 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
536 * passes all of @argv to the child.
538 * @child_setup and @user_data are a function and user data. On POSIX
539 * platforms, the function is called in the child after GLib has
540 * performed all the setup it plans to perform (including creating
541 * pipes, closing file descriptors, etc.) but before calling
542 * exec(). That is, @child_setup is called just
543 * before calling exec() in the child. Obviously
544 * actions taken in this function will only affect the child, not the
547 * On Windows, there is no separate fork() and exec()
548 * functionality. Child processes are created and run with a single
549 * API call, CreateProcess(). There is no sensible thing @child_setup
550 * could be used for on Windows so it is ignored and not called.
552 * If non-%NULL, @child_pid will on Unix be filled with the child's
553 * process ID. You can use the process ID to send signals to the
554 * child, or to use g_child_watch_add() (or waitpid()) if you specified the
555 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
556 * filled with a handle to the child process only if you specified the
557 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
558 * process using the Win32 API, for example wait for its termination
559 * with the <function>WaitFor*()</function> functions, or examine its
560 * exit code with GetExitCodeProcess(). You should close the handle
561 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
563 * If non-%NULL, the @standard_input, @standard_output, @standard_error
564 * locations will be filled with file descriptors for writing to the child's
565 * standard input or reading from its standard output or standard error.
566 * The caller of g_spawn_async_with_pipes() must close these file descriptors
567 * when they are no longer in use. If these parameters are %NULL, the corresponding
568 * pipe won't be created.
570 * If @standard_input is NULL, the child's standard input is attached to
571 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
573 * If @standard_error is NULL, the child's standard error goes to the same
574 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
577 * If @standard_output is NULL, the child's standard output goes to the same
578 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
581 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
582 * If an error is set, the function returns %FALSE. Errors
583 * are reported even if they occur in the child (for example if the
584 * executable in <literal>argv[0]</literal> is not found). Typically
585 * the <literal>message</literal> field of returned errors should be displayed
586 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
588 * If an error occurs, @child_pid, @standard_input, @standard_output,
589 * and @standard_error will not be filled with valid values.
591 * If @child_pid is not %NULL and an error does not occur then the returned
592 * process reference must be closed using g_spawn_close_pid().
595 * If you are writing a GTK+ application, and the program you
596 * are spawning is a graphical application, too, then you may
597 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
598 * the spawned program opens its windows on the right screen.
601 * Return value: %TRUE on success, %FALSE if an error was set
604 g_spawn_async_with_pipes (const gchar *working_directory,
608 GSpawnChildSetupFunc child_setup,
611 gint *standard_input,
612 gint *standard_output,
613 gint *standard_error,
616 g_return_val_if_fail (argv != NULL, FALSE);
617 g_return_val_if_fail (standard_output == NULL ||
618 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
619 g_return_val_if_fail (standard_error == NULL ||
620 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
621 /* can't inherit stdin if we have an input pipe. */
622 g_return_val_if_fail (standard_input == NULL ||
623 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
625 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
629 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
630 (flags & G_SPAWN_SEARCH_PATH) != 0,
631 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
632 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
633 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
634 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
645 * g_spawn_command_line_sync:
646 * @command_line: a command line
647 * @standard_output: return location for child output
648 * @standard_error: return location for child errors
649 * @exit_status: return location for child exit status, as returned by waitpid()
650 * @error: return location for errors
652 * A simple version of g_spawn_sync() with little-used parameters
653 * removed, taking a command line instead of an argument vector. See
654 * g_spawn_sync() for full details. @command_line will be parsed by
655 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
656 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
657 * implications, so consider using g_spawn_sync() directly if
658 * appropriate. Possible errors are those from g_spawn_sync() and those
659 * from g_shell_parse_argv().
661 * If @exit_status is non-%NULL, the exit status of the child is stored there as
662 * it would be returned by waitpid(); standard UNIX macros such as WIFEXITED()
663 * and WEXITSTATUS() must be used to evaluate the exit status.
665 * On Windows, please note the implications of g_shell_parse_argv()
666 * parsing @command_line. Parsing is done according to Unix shell rules, not
667 * Windows command interpreter rules.
668 * Space is a separator, and backslashes are
669 * special. Thus you cannot simply pass a @command_line containing
670 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
671 * the backslashes will be eaten, and the space will act as a
672 * separator. You need to enclose such paths with single quotes, like
673 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
675 * Return value: %TRUE on success, %FALSE if an error was set
678 g_spawn_command_line_sync (const gchar *command_line,
679 gchar **standard_output,
680 gchar **standard_error,
687 g_return_val_if_fail (command_line != NULL, FALSE);
689 if (!g_shell_parse_argv (command_line,
694 retval = g_spawn_sync (NULL,
710 * g_spawn_command_line_async:
711 * @command_line: a command line
712 * @error: return location for errors
714 * A simple version of g_spawn_async() that parses a command line with
715 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
716 * command line in the background. Unlike g_spawn_async(), the
717 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
718 * that %G_SPAWN_SEARCH_PATH can have security implications, so
719 * consider using g_spawn_async() directly if appropriate. Possible
720 * errors are those from g_shell_parse_argv() and g_spawn_async().
722 * The same concerns on Windows apply as for g_spawn_command_line_sync().
724 * Return value: %TRUE on success, %FALSE if error is set.
727 g_spawn_command_line_async (const gchar *command_line,
733 g_return_val_if_fail (command_line != NULL, FALSE);
735 if (!g_shell_parse_argv (command_line,
740 retval = g_spawn_async (NULL,
754 exec_err_to_g_error (gint en)
760 return G_SPAWN_ERROR_ACCES;
766 return G_SPAWN_ERROR_PERM;
772 return G_SPAWN_ERROR_2BIG;
778 return G_SPAWN_ERROR_NOEXEC;
784 return G_SPAWN_ERROR_NAMETOOLONG;
790 return G_SPAWN_ERROR_NOENT;
796 return G_SPAWN_ERROR_NOMEM;
802 return G_SPAWN_ERROR_NOTDIR;
808 return G_SPAWN_ERROR_LOOP;
814 return G_SPAWN_ERROR_TXTBUSY;
820 return G_SPAWN_ERROR_IO;
826 return G_SPAWN_ERROR_NFILE;
832 return G_SPAWN_ERROR_MFILE;
838 return G_SPAWN_ERROR_INVAL;
844 return G_SPAWN_ERROR_ISDIR;
850 return G_SPAWN_ERROR_LIBBAD;
855 return G_SPAWN_ERROR_FAILED;
861 write_all (gint fd, gconstpointer vbuf, gsize to_write)
863 gchar *buf = (gchar *) vbuf;
867 gssize count = write (fd, buf, to_write);
884 write_err_and_exit (gint fd, gint msg)
888 write_all (fd, &msg, sizeof(msg));
889 write_all (fd, &en, sizeof(en));
895 set_cloexec (void *data, gint fd)
897 if (fd >= GPOINTER_TO_INT (data))
898 fcntl (fd, F_SETFD, FD_CLOEXEC);
905 fdwalk (int (*cb)(void *data, int fd), void *data)
911 #ifdef HAVE_SYS_RESOURCE_H
918 if ((d = opendir("/proc/self/fd"))) {
921 while ((de = readdir(d))) {
925 if (de->d_name[0] == '.')
929 l = strtol(de->d_name, &e, 10);
930 if (errno != 0 || !e || *e)
941 if ((res = cb (data, fd)) != 0)
949 /* If /proc is not mounted or not accessible we fall back to the old
954 #ifdef HAVE_SYS_RESOURCE_H
956 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
957 open_max = rl.rlim_max;
960 open_max = sysconf (_SC_OPEN_MAX);
962 for (fd = 0; fd < open_max; fd++)
963 if ((res = cb (data, fd)) != 0)
971 sane_dup2 (gint fd1, gint fd2)
976 ret = dup2 (fd1, fd2);
977 if (ret < 0 && errno == EINTR)
992 do_exec (gint child_err_report_fd,
996 const gchar *working_directory,
999 gboolean close_descriptors,
1000 gboolean search_path,
1001 gboolean stdout_to_null,
1002 gboolean stderr_to_null,
1003 gboolean child_inherits_stdin,
1004 gboolean file_and_argv_zero,
1005 GSpawnChildSetupFunc child_setup,
1008 if (working_directory && chdir (working_directory) < 0)
1009 write_err_and_exit (child_err_report_fd,
1010 CHILD_CHDIR_FAILED);
1012 /* Close all file descriptors but stdin stdout and stderr as
1013 * soon as we exec. Note that this includes
1014 * child_err_report_fd, which keeps the parent from blocking
1015 * forever on the other end of that pipe.
1017 if (close_descriptors)
1019 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1023 /* We need to do child_err_report_fd anyway */
1024 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1027 /* Redirect pipes as required */
1031 /* dup2 can't actually fail here I don't think */
1033 if (sane_dup2 (stdin_fd, 0) < 0)
1034 write_err_and_exit (child_err_report_fd,
1037 /* ignore this if it doesn't work */
1038 close_and_invalidate (&stdin_fd);
1040 else if (!child_inherits_stdin)
1042 /* Keep process from blocking on a read of stdin */
1043 gint read_null = open ("/dev/null", O_RDONLY);
1044 sane_dup2 (read_null, 0);
1045 close_and_invalidate (&read_null);
1050 /* dup2 can't actually fail here I don't think */
1052 if (sane_dup2 (stdout_fd, 1) < 0)
1053 write_err_and_exit (child_err_report_fd,
1056 /* ignore this if it doesn't work */
1057 close_and_invalidate (&stdout_fd);
1059 else if (stdout_to_null)
1061 gint write_null = open ("/dev/null", O_WRONLY);
1062 sane_dup2 (write_null, 1);
1063 close_and_invalidate (&write_null);
1068 /* dup2 can't actually fail here I don't think */
1070 if (sane_dup2 (stderr_fd, 2) < 0)
1071 write_err_and_exit (child_err_report_fd,
1074 /* ignore this if it doesn't work */
1075 close_and_invalidate (&stderr_fd);
1077 else if (stderr_to_null)
1079 gint write_null = open ("/dev/null", O_WRONLY);
1080 sane_dup2 (write_null, 2);
1081 close_and_invalidate (&write_null);
1084 /* Call user function just before we exec */
1087 (* child_setup) (user_data);
1091 file_and_argv_zero ? argv + 1 : argv,
1095 write_err_and_exit (child_err_report_fd,
1112 if (bytes >= sizeof(gint)*2)
1113 break; /* give up, who knows what happened, should not be
1119 ((gchar*)buf) + bytes,
1120 sizeof(gint) * n_ints_in_buf - bytes);
1121 if (chunk < 0 && errno == EINTR)
1126 /* Some weird shit happened, bail out */
1130 G_SPAWN_ERROR_FAILED,
1131 _("Failed to read from child pipe (%s)"),
1132 g_strerror (errno));
1136 else if (chunk == 0)
1138 else /* chunk > 0 */
1142 *n_ints_read = (gint)(bytes / sizeof(gint));
1148 fork_exec_with_pipes (gboolean intermediate_child,
1149 const gchar *working_directory,
1152 gboolean close_descriptors,
1153 gboolean search_path,
1154 gboolean stdout_to_null,
1155 gboolean stderr_to_null,
1156 gboolean child_inherits_stdin,
1157 gboolean file_and_argv_zero,
1158 GSpawnChildSetupFunc child_setup,
1161 gint *standard_input,
1162 gint *standard_output,
1163 gint *standard_error,
1167 gint stdin_pipe[2] = { -1, -1 };
1168 gint stdout_pipe[2] = { -1, -1 };
1169 gint stderr_pipe[2] = { -1, -1 };
1170 gint child_err_report_pipe[2] = { -1, -1 };
1171 gint child_pid_report_pipe[2] = { -1, -1 };
1174 if (!make_pipe (child_err_report_pipe, error))
1177 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1178 goto cleanup_and_fail;
1180 if (standard_input && !make_pipe (stdin_pipe, error))
1181 goto cleanup_and_fail;
1183 if (standard_output && !make_pipe (stdout_pipe, error))
1184 goto cleanup_and_fail;
1186 if (standard_error && !make_pipe (stderr_pipe, error))
1187 goto cleanup_and_fail;
1196 _("Failed to fork (%s)"),
1197 g_strerror (errno));
1199 goto cleanup_and_fail;
1203 /* Immediate child. This may or may not be the child that
1204 * actually execs the new process.
1207 /* Be sure we crash if the parent exits
1208 * and we write to the err_report_pipe
1210 signal (SIGPIPE, SIG_DFL);
1212 /* Close the parent's end of the pipes;
1213 * not needed in the close_descriptors case,
1216 close_and_invalidate (&child_err_report_pipe[0]);
1217 close_and_invalidate (&child_pid_report_pipe[0]);
1218 close_and_invalidate (&stdin_pipe[1]);
1219 close_and_invalidate (&stdout_pipe[0]);
1220 close_and_invalidate (&stderr_pipe[0]);
1222 if (intermediate_child)
1224 /* We need to fork an intermediate child that launches the
1225 * final child. The purpose of the intermediate child
1226 * is to exit, so we can waitpid() it immediately.
1227 * Then the grandchild will not become a zombie.
1229 GPid grandchild_pid;
1231 grandchild_pid = fork ();
1233 if (grandchild_pid < 0)
1235 /* report -1 as child PID */
1236 write_all (child_pid_report_pipe[1], &grandchild_pid,
1237 sizeof(grandchild_pid));
1239 write_err_and_exit (child_err_report_pipe[1],
1242 else if (grandchild_pid == 0)
1244 do_exec (child_err_report_pipe[1],
1255 child_inherits_stdin,
1262 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1263 close_and_invalidate (&child_pid_report_pipe[1]);
1270 /* Just run the child.
1273 do_exec (child_err_report_pipe[1],
1284 child_inherits_stdin,
1297 /* Close the uncared-about ends of the pipes */
1298 close_and_invalidate (&child_err_report_pipe[1]);
1299 close_and_invalidate (&child_pid_report_pipe[1]);
1300 close_and_invalidate (&stdin_pipe[0]);
1301 close_and_invalidate (&stdout_pipe[1]);
1302 close_and_invalidate (&stderr_pipe[1]);
1304 /* If we had an intermediate child, reap it */
1305 if (intermediate_child)
1308 if (waitpid (pid, &status, 0) < 0)
1312 else if (errno == ECHILD)
1313 ; /* do nothing, child already reaped */
1315 g_warning ("waitpid() should not fail in "
1316 "'fork_exec_with_pipes'");
1321 if (!read_ints (child_err_report_pipe[0],
1324 goto cleanup_and_fail;
1328 /* Error from the child. */
1332 case CHILD_CHDIR_FAILED:
1335 G_SPAWN_ERROR_CHDIR,
1336 _("Failed to change to directory '%s' (%s)"),
1338 g_strerror (buf[1]));
1342 case CHILD_EXEC_FAILED:
1345 exec_err_to_g_error (buf[1]),
1346 _("Failed to execute child process \"%s\" (%s)"),
1348 g_strerror (buf[1]));
1352 case CHILD_DUP2_FAILED:
1355 G_SPAWN_ERROR_FAILED,
1356 _("Failed to redirect output or input of child process (%s)"),
1357 g_strerror (buf[1]));
1361 case CHILD_FORK_FAILED:
1365 _("Failed to fork child process (%s)"),
1366 g_strerror (buf[1]));
1372 G_SPAWN_ERROR_FAILED,
1373 _("Unknown error executing child process \"%s\""),
1378 goto cleanup_and_fail;
1381 /* Get child pid from intermediate child pipe. */
1382 if (intermediate_child)
1386 if (!read_ints (child_pid_report_pipe[0],
1387 buf, 1, &n_ints, error))
1388 goto cleanup_and_fail;
1394 G_SPAWN_ERROR_FAILED,
1395 _("Failed to read enough data from child pid pipe (%s)"),
1396 g_strerror (errno));
1397 goto cleanup_and_fail;
1401 /* we have the child pid */
1406 /* Success against all odds! return the information */
1407 close_and_invalidate (&child_err_report_pipe[0]);
1408 close_and_invalidate (&child_pid_report_pipe[0]);
1414 *standard_input = stdin_pipe[1];
1415 if (standard_output)
1416 *standard_output = stdout_pipe[0];
1418 *standard_error = stderr_pipe[0];
1425 /* There was an error from the Child, reap the child to avoid it being
1432 if (waitpid (pid, NULL, 0) < 0)
1436 else if (errno == ECHILD)
1437 ; /* do nothing, child already reaped */
1439 g_warning ("waitpid() should not fail in "
1440 "'fork_exec_with_pipes'");
1444 close_and_invalidate (&child_err_report_pipe[0]);
1445 close_and_invalidate (&child_err_report_pipe[1]);
1446 close_and_invalidate (&child_pid_report_pipe[0]);
1447 close_and_invalidate (&child_pid_report_pipe[1]);
1448 close_and_invalidate (&stdin_pipe[0]);
1449 close_and_invalidate (&stdin_pipe[1]);
1450 close_and_invalidate (&stdout_pipe[0]);
1451 close_and_invalidate (&stdout_pipe[1]);
1452 close_and_invalidate (&stderr_pipe[0]);
1453 close_and_invalidate (&stderr_pipe[1]);
1459 make_pipe (gint p[2],
1466 G_SPAWN_ERROR_FAILED,
1467 _("Failed to create pipe for communicating with child process (%s)"),
1468 g_strerror (errno));
1475 /* Based on execvp from GNU C Library */
1478 script_execute (const gchar *file,
1481 gboolean search_path)
1483 /* Count the arguments. */
1488 /* Construct an argument list for the shell. */
1492 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1494 new_argv[0] = (char *) "/bin/sh";
1495 new_argv[1] = (char *) file;
1498 new_argv[argc + 1] = argv[argc];
1502 /* Execute the shell. */
1504 execve (new_argv[0], new_argv, envp);
1506 execv (new_argv[0], new_argv);
1513 my_strchrnul (const gchar *str, gchar c)
1515 gchar *p = (gchar*) str;
1516 while (*p && (*p != c))
1523 g_execute (const gchar *file,
1526 gboolean search_path)
1530 /* We check the simple case first. */
1535 if (!search_path || strchr (file, '/') != NULL)
1537 /* Don't search when it contains a slash. */
1539 execve (file, argv, envp);
1543 if (errno == ENOEXEC)
1544 script_execute (file, argv, envp, FALSE);
1548 gboolean got_eacces = 0;
1549 const gchar *path, *p;
1550 gchar *name, *freeme;
1554 path = g_getenv ("PATH");
1557 /* There is no `PATH' in the environment. The default
1558 * search path in libc is the current directory followed by
1559 * the path `confstr' returns for `_CS_PATH'.
1562 /* In GLib we put . last, for security, and don't use the
1563 * unportable confstr(); UNIX98 does not actually specify
1564 * what to search if PATH is unset. POSIX may, dunno.
1567 path = "/bin:/usr/bin:.";
1570 len = strlen (file) + 1;
1571 pathlen = strlen (path);
1572 freeme = name = g_malloc (pathlen + len + 1);
1574 /* Copy the file name at the top, including '\0' */
1575 memcpy (name + pathlen + 1, file, len);
1576 name = name + pathlen;
1577 /* And add the slash before the filename */
1586 p = my_strchrnul (path, ':');
1589 /* Two adjacent colons, or a colon at the beginning or the end
1590 * of `PATH' means to search the current directory.
1594 startp = memcpy (name - (p - path), path, p - path);
1596 /* Try to execute this name. If it works, execv will not return. */
1598 execve (startp, argv, envp);
1600 execv (startp, argv);
1602 if (errno == ENOEXEC)
1603 script_execute (startp, argv, envp, search_path);
1608 /* Record the we got a `Permission denied' error. If we end
1609 * up finding no executable we can use, we want to diagnose
1610 * that we did find one but were denied access.
1623 /* Those errors indicate the file is missing or not executable
1624 * by us, in which case we want to just try the next path
1630 /* Some other error means we found an executable file, but
1631 * something went wrong executing it; return the error to our
1638 while (*p++ != '\0');
1640 /* We tried every element and none of them worked. */
1642 /* At least one failure was due to permissions, so report that
1650 /* Return the error from the last attempt (probably ENOENT). */
1655 * g_spawn_close_pid:
1656 * @pid: The process reference to close
1658 * On some platforms, notably Windows, the #GPid type represents a resource
1659 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1660 * is provided for this purpose. It should be used on all platforms, even
1661 * though it doesn't do anything under UNIX.
1664 g_spawn_close_pid (GPid pid)
1668 #define __G_SPAWN_C__
1669 #include "galiasdef.c"