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 ID, 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.
94 * If you are writing a GTK+ application, and the program you
95 * are spawning is a graphical application, too, then you may
96 * want to use gdk_spawn_on_screen() instead to ensure that
97 * the spawned program opens its windows on the right screen.
100 * Return value: %TRUE on success, %FALSE if error is set
103 g_spawn_async (const gchar *working_directory,
107 GSpawnChildSetupFunc child_setup,
112 g_return_val_if_fail (argv != NULL, FALSE);
114 return g_spawn_async_with_pipes (working_directory,
124 /* Avoids a danger in threaded situations (calling close()
125 * on a file descriptor twice, and another thread has
126 * re-opened it since the first close)
129 close_and_invalidate (gint *fd)
144 /* Some versions of OS X define READ_OK in public headers */
149 READ_FAILED = 0, /* FALSE */
155 read_data (GString *str,
164 bytes = read (fd, buf, 4096);
170 g_string_append_len (str, buf, bytes);
173 else if (bytes < 0 && errno == EINTR)
180 _("Failed to read data from child process (%s)"),
191 * @working_directory: child's current working directory, or %NULL to inherit parent's
192 * @argv: child's argument vector
193 * @envp: child's environment, or %NULL to inherit parent's
194 * @flags: flags from #GSpawnFlags
195 * @child_setup: function to run in the child just before exec()
196 * @user_data: user data for @child_setup
197 * @standard_output: return location for child output
198 * @standard_error: return location for child error messages
199 * @exit_status: return location for child exit status, as returned by waitpid()
200 * @error: return location for error
202 * Executes a child synchronously (waits for the child to exit before returning).
203 * All output from the child is stored in @standard_output and @standard_error,
204 * if those parameters are non-%NULL. If @exit_status is non-%NULL, the exit
205 * status of the child is stored there as it would be returned by
206 * waitpid(); standard UNIX macros such as WIFEXITED() and WEXITSTATUS()
207 * must be used to evaluate the exit status. If an error occurs, no data is
208 * returned in @standard_output, @standard_error, or @exit_status.
210 * This function calls g_spawn_async_with_pipes() internally; see that
211 * function for full details on the other parameters and details on
212 * how these functions work on Windows.
214 * Return value: %TRUE on success, %FALSE if an error was set.
217 g_spawn_sync (const gchar *working_directory,
221 GSpawnChildSetupFunc child_setup,
223 gchar **standard_output,
224 gchar **standard_error,
233 GString *outstr = NULL;
234 GString *errstr = NULL;
238 g_return_val_if_fail (argv != NULL, FALSE);
239 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
240 g_return_val_if_fail (standard_output == NULL ||
241 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
242 g_return_val_if_fail (standard_error == NULL ||
243 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
245 /* Just to ensure segfaults if callers try to use
246 * these when an error is reported.
249 *standard_output = NULL;
252 *standard_error = NULL;
254 if (!fork_exec_with_pipes (FALSE,
258 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
259 (flags & G_SPAWN_SEARCH_PATH) != 0,
260 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
261 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
262 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
263 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
268 standard_output ? &outpipe : NULL,
269 standard_error ? &errpipe : NULL,
273 /* Read data from child. */
279 outstr = g_string_new (NULL);
284 errstr = g_string_new (NULL);
287 /* Read data until we get EOF on both pipes. */
296 FD_SET (outpipe, &fds);
298 FD_SET (errpipe, &fds);
300 ret = select (MAX (outpipe, errpipe) + 1,
303 NULL /* no timeout */);
305 if (ret < 0 && errno != EINTR)
312 _("Unexpected error in select() reading data from a child process (%s)"),
318 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
320 switch (read_data (outstr, outpipe, error))
326 close_and_invalidate (&outpipe);
337 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
339 switch (read_data (errstr, errpipe, error))
345 close_and_invalidate (&errpipe);
357 /* These should only be open still if we had an error. */
360 close_and_invalidate (&outpipe);
362 close_and_invalidate (&errpipe);
364 /* Wait for child to exit, even if we have
369 ret = waitpid (pid, &status, 0);
375 else if (errno == ECHILD)
379 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.");
383 /* We don't need the exit status. */
388 if (!failed) /* avoid error pileups */
395 _("Unexpected error in waitpid() (%s)"),
404 g_string_free (outstr, TRUE);
406 g_string_free (errstr, TRUE);
413 *exit_status = status;
416 *standard_output = g_string_free (outstr, FALSE);
419 *standard_error = g_string_free (errstr, FALSE);
426 * g_spawn_async_with_pipes:
427 * @working_directory: child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
428 * @argv: child's argument vector, in the GLib file name encoding
429 * @envp: child's environment, or %NULL to inherit parent's, in the GLib file name encoding
430 * @flags: flags from #GSpawnFlags
431 * @child_setup: function to run in the child just before exec()
432 * @user_data: user data for @child_setup
433 * @child_pid: return location for child process ID, or %NULL
434 * @standard_input: return location for file descriptor to write to child's stdin, or %NULL
435 * @standard_output: return location for file descriptor to read child's stdout, or %NULL
436 * @standard_error: return location for file descriptor to read child's stderr, or %NULL
437 * @error: return location for error
439 * Executes a child program asynchronously (your program will not
440 * block waiting for the child to exit). The child program is
441 * specified by the only argument that must be provided, @argv. @argv
442 * should be a %NULL-terminated array of strings, to be passed as the
443 * argument vector for the child. The first string in @argv is of
444 * course the name of the program to execute. By default, the name of
445 * the program must be a full path; the <envar>PATH</envar> shell variable
446 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
448 * On Windows, note that all the string or string vector arguments to
449 * this function and the other g_spawn*() functions are in UTF-8, the
450 * GLib file name encoding. Unicode characters that are not part of
451 * the system codepage passed in these arguments will be correctly
452 * available in the spawned program only if it uses wide character API
453 * to retrieve its command line. For C programs built with Microsoft's
454 * tools it is enough to make the program have a wmain() instead of
455 * main(). wmain() has a wide character argument vector as parameter.
457 * At least currently, mingw doesn't support wmain(), so if you use
458 * mingw to develop the spawned program, it will have to call the
459 * undocumented function __wgetmainargs() to get the wide character
460 * argument vector and environment. See gspawn-win32-helper.c in the
461 * GLib sources or init.c in the mingw runtime sources for a prototype
462 * for that function. Alternatively, you can retrieve the Win32 system
463 * level wide character command line passed to the spawned program
464 * using the GetCommandLineW() function.
466 * On Windows the low-level child process creation API
467 * <function>CreateProcess()</function> doesn't use argument vectors,
468 * but a command line. The C runtime library's
469 * <function>spawn*()</function> family of functions (which
470 * g_spawn_async_with_pipes() eventually calls) paste the argument
471 * vector elements together into a command line, and the C runtime startup code
472 * does a corresponding reconstruction of an argument vector from the
473 * command line, to be passed to main(). Complications arise when you have
474 * argument vector elements that contain spaces of double quotes. The
475 * <function>spawn*()</function> functions don't do any quoting or
476 * escaping, but on the other hand the startup code does do unquoting
477 * and unescaping in order to enable receiving arguments with embedded
478 * spaces or double quotes. To work around this asymmetry,
479 * g_spawn_async_with_pipes() will do quoting and escaping on argument
480 * vector elements that need it before calling the C runtime
483 * @envp is a %NULL-terminated array of strings, where each string
484 * has the form <literal>KEY=VALUE</literal>. This will become
485 * the child's environment. If @envp is %NULL, the child inherits its
486 * parent's environment.
488 * @flags should be the bitwise OR of any flags you want to affect the
489 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that
490 * the child will not automatically be reaped; you must use a
491 * #GChildWatch source to be notified about the death of the child
492 * process. Eventually you must call g_spawn_close_pid() on the
493 * @child_pid, in order to free resources which may be associated
494 * with the child process. (On Unix, using a #GChildWatch source is
495 * equivalent to calling waitpid() or handling the %SIGCHLD signal
496 * manually. On Windows, calling g_spawn_close_pid() is equivalent
497 * to calling CloseHandle() on the process handle returned in
500 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
501 * descriptors will be inherited by the child; otherwise all
502 * descriptors except stdin/stdout/stderr will be closed before
503 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
504 * means that <literal>argv[0]</literal> need not be an absolute path, it
505 * will be looked for in the user's <envar>PATH</envar>.
506 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
507 * be discarded, instead of going to the same location as the parent's
508 * standard output. If you use this flag, @standard_output must be %NULL.
509 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
510 * will be discarded, instead of going to the same location as the parent's
511 * standard error. If you use this flag, @standard_error must be %NULL.
512 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
513 * standard input (by default, the child's standard input is attached to
514 * /dev/null). If you use this flag, @standard_input must be %NULL.
515 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
516 * the file to execute, while the remaining elements are the
517 * actual argument vector to pass to the file. Normally
518 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
519 * passes all of @argv to the child.
521 * @child_setup and @user_data are a function and user data. On POSIX
522 * platforms, the function is called in the child after GLib has
523 * performed all the setup it plans to perform (including creating
524 * pipes, closing file descriptors, etc.) but before calling
525 * exec(). That is, @child_setup is called just
526 * before calling exec() in the child. Obviously
527 * actions taken in this function will only affect the child, not the
528 * parent. On Windows, there is no separate fork() and exec()
529 * functionality. Child processes are created and run with
530 * a single API call, CreateProcess(). @child_setup is
531 * called in the parent process just before creating the child
532 * process. You should carefully consider what you do in @child_setup
533 * if you intend your software to be portable to Windows.
535 * If non-%NULL, @child_pid will on Unix be filled with the child's
536 * process ID. You can use the process ID to send signals to the
537 * child, or to use g_child_watch_add() (or waitpid()) if you specified the
538 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
539 * filled with a handle to the child process only if you specified the
540 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
541 * process using the Win32 API, for example wait for its termination
542 * with the <function>WaitFor*()</function> functions, or examine its
543 * exit code with GetExitCodeProcess(). You should close the handle
544 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
546 * If non-%NULL, the @standard_input, @standard_output, @standard_error
547 * locations will be filled with file descriptors for writing to the child's
548 * standard input or reading from its standard output or standard error.
549 * The caller of g_spawn_async_with_pipes() must close these file descriptors
550 * when they are no longer in use. If these parameters are %NULL, the corresponding
551 * pipe won't be created.
553 * If @standard_input is NULL, the child's standard input is attached to
554 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
556 * If @standard_error is NULL, the child's standard error goes to the same
557 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
560 * If @standard_output is NULL, the child's standard output goes to the same
561 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
564 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
565 * If an error is set, the function returns %FALSE. Errors
566 * are reported even if they occur in the child (for example if the
567 * executable in <literal>argv[0]</literal> is not found). Typically
568 * the <literal>message</literal> field of returned errors should be displayed
569 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
571 * If an error occurs, @child_pid, @standard_input, @standard_output,
572 * and @standard_error will not be filled with valid values.
574 * If @child_pid is not %NULL and an error does not occur then the returned
575 * pid must be closed using g_spawn_close_pid().
578 * If you are writing a GTK+ application, and the program you
579 * are spawning is a graphical application, too, then you may
580 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
581 * the spawned program opens its windows no the right screen.
584 * Return value: %TRUE on success, %FALSE if an error was set
587 g_spawn_async_with_pipes (const gchar *working_directory,
591 GSpawnChildSetupFunc child_setup,
594 gint *standard_input,
595 gint *standard_output,
596 gint *standard_error,
599 g_return_val_if_fail (argv != NULL, FALSE);
600 g_return_val_if_fail (standard_output == NULL ||
601 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
602 g_return_val_if_fail (standard_error == NULL ||
603 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
604 /* can't inherit stdin if we have an input pipe. */
605 g_return_val_if_fail (standard_input == NULL ||
606 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
608 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
612 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
613 (flags & G_SPAWN_SEARCH_PATH) != 0,
614 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
615 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
616 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
617 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
628 * g_spawn_command_line_sync:
629 * @command_line: a command line
630 * @standard_output: return location for child output
631 * @standard_error: return location for child errors
632 * @exit_status: return location for child exit status, as returned by waitpid()
633 * @error: return location for errors
635 * A simple version of g_spawn_sync() with little-used parameters
636 * removed, taking a command line instead of an argument vector. See
637 * g_spawn_sync() for full details. @command_line will be parsed by
638 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
639 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
640 * implications, so consider using g_spawn_sync() directly if
641 * appropriate. Possible errors are those from g_spawn_sync() and those
642 * from g_shell_parse_argv().
644 * If @exit_status is non-%NULL, the exit status of the child is stored there as
645 * it would be returned by waitpid(); standard UNIX macros such as WIFEXITED()
646 * and WEXITSTATUS() must be used to evaluate the exit status.
648 * On Windows, please note the implications of g_shell_parse_argv()
649 * parsing @command_line. Parsing is done according to Unix shell rules, not
650 * Windows command interpreter rules.
651 * Space is a separator, and backslashes are
652 * special. Thus you cannot simply pass a @command_line containing
653 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
654 * the backslashes will be eaten, and the space will act as a
655 * separator. You need to enclose such paths with single quotes, like
656 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
658 * Return value: %TRUE on success, %FALSE if an error was set
661 g_spawn_command_line_sync (const gchar *command_line,
662 gchar **standard_output,
663 gchar **standard_error,
670 g_return_val_if_fail (command_line != NULL, FALSE);
672 if (!g_shell_parse_argv (command_line,
677 retval = g_spawn_sync (NULL,
693 * g_spawn_command_line_async:
694 * @command_line: a command line
695 * @error: return location for errors
697 * A simple version of g_spawn_async() that parses a command line with
698 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
699 * command line in the background. Unlike g_spawn_async(), the
700 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
701 * that %G_SPAWN_SEARCH_PATH can have security implications, so
702 * consider using g_spawn_async() directly if appropriate. Possible
703 * errors are those from g_shell_parse_argv() and g_spawn_async().
705 * The same concerns on Windows apply as for g_spawn_command_line_sync().
707 * Return value: %TRUE on success, %FALSE if error is set.
710 g_spawn_command_line_async (const gchar *command_line,
716 g_return_val_if_fail (command_line != NULL, FALSE);
718 if (!g_shell_parse_argv (command_line,
723 retval = g_spawn_async (NULL,
737 exec_err_to_g_error (gint en)
743 return G_SPAWN_ERROR_ACCES;
749 return G_SPAWN_ERROR_PERM;
755 return G_SPAWN_ERROR_2BIG;
761 return G_SPAWN_ERROR_NOEXEC;
767 return G_SPAWN_ERROR_NAMETOOLONG;
773 return G_SPAWN_ERROR_NOENT;
779 return G_SPAWN_ERROR_NOMEM;
785 return G_SPAWN_ERROR_NOTDIR;
791 return G_SPAWN_ERROR_LOOP;
797 return G_SPAWN_ERROR_TXTBUSY;
803 return G_SPAWN_ERROR_IO;
809 return G_SPAWN_ERROR_NFILE;
815 return G_SPAWN_ERROR_MFILE;
821 return G_SPAWN_ERROR_INVAL;
827 return G_SPAWN_ERROR_ISDIR;
833 return G_SPAWN_ERROR_LIBBAD;
838 return G_SPAWN_ERROR_FAILED;
844 write_all (gint fd, gconstpointer vbuf, gsize to_write)
846 gchar *buf = (gchar *) vbuf;
850 gssize count = write (fd, buf, to_write);
867 write_err_and_exit (gint fd, gint msg)
871 write_all (fd, &msg, sizeof(msg));
872 write_all (fd, &en, sizeof(en));
878 set_cloexec (void *data, gint fd)
880 if (fd >= GPOINTER_TO_INT (data))
881 fcntl (fd, F_SETFD, FD_CLOEXEC);
888 fdwalk (int (*cb)(void *data, int fd), void *data)
894 #ifdef HAVE_SYS_RESOURCE_H
901 if ((d = opendir("/proc/self/fd"))) {
904 while ((de = readdir(d))) {
908 if (de->d_name[0] == '.')
912 l = strtol(de->d_name, &e, 10);
913 if (errno != 0 || !e || *e)
924 if ((res = cb (data, fd)) != 0)
932 /* If /proc is not mounted or not accessible we fall back to the old
937 #ifdef HAVE_SYS_RESOURCE_H
939 if (getrlimit(RLIMIT_NOFILE, &rl) == 0)
940 open_max = rl.rlim_max;
943 open_max = sysconf (_SC_OPEN_MAX);
945 for (fd = 0; fd < open_max; fd++)
946 if ((res = cb (data, fd)) != 0)
954 sane_dup2 (gint fd1, gint fd2)
959 ret = dup2 (fd1, fd2);
960 if (ret < 0 && errno == EINTR)
975 do_exec (gint child_err_report_fd,
979 const gchar *working_directory,
982 gboolean close_descriptors,
983 gboolean search_path,
984 gboolean stdout_to_null,
985 gboolean stderr_to_null,
986 gboolean child_inherits_stdin,
987 gboolean file_and_argv_zero,
988 GSpawnChildSetupFunc child_setup,
991 if (working_directory && chdir (working_directory) < 0)
992 write_err_and_exit (child_err_report_fd,
995 /* Close all file descriptors but stdin stdout and stderr as
996 * soon as we exec. Note that this includes
997 * child_err_report_fd, which keeps the parent from blocking
998 * forever on the other end of that pipe.
1000 if (close_descriptors)
1002 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1006 /* We need to do child_err_report_fd anyway */
1007 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1010 /* Redirect pipes as required */
1014 /* dup2 can't actually fail here I don't think */
1016 if (sane_dup2 (stdin_fd, 0) < 0)
1017 write_err_and_exit (child_err_report_fd,
1020 /* ignore this if it doesn't work */
1021 close_and_invalidate (&stdin_fd);
1023 else if (!child_inherits_stdin)
1025 /* Keep process from blocking on a read of stdin */
1026 gint read_null = open ("/dev/null", O_RDONLY);
1027 sane_dup2 (read_null, 0);
1028 close_and_invalidate (&read_null);
1033 /* dup2 can't actually fail here I don't think */
1035 if (sane_dup2 (stdout_fd, 1) < 0)
1036 write_err_and_exit (child_err_report_fd,
1039 /* ignore this if it doesn't work */
1040 close_and_invalidate (&stdout_fd);
1042 else if (stdout_to_null)
1044 gint write_null = open ("/dev/null", O_WRONLY);
1045 sane_dup2 (write_null, 1);
1046 close_and_invalidate (&write_null);
1051 /* dup2 can't actually fail here I don't think */
1053 if (sane_dup2 (stderr_fd, 2) < 0)
1054 write_err_and_exit (child_err_report_fd,
1057 /* ignore this if it doesn't work */
1058 close_and_invalidate (&stderr_fd);
1060 else if (stderr_to_null)
1062 gint write_null = open ("/dev/null", O_WRONLY);
1063 sane_dup2 (write_null, 2);
1064 close_and_invalidate (&write_null);
1067 /* Call user function just before we exec */
1070 (* child_setup) (user_data);
1074 file_and_argv_zero ? argv + 1 : argv,
1078 write_err_and_exit (child_err_report_fd,
1095 if (bytes >= sizeof(gint)*2)
1096 break; /* give up, who knows what happened, should not be
1102 ((gchar*)buf) + bytes,
1103 sizeof(gint) * n_ints_in_buf - bytes);
1104 if (chunk < 0 && errno == EINTR)
1109 /* Some weird shit happened, bail out */
1113 G_SPAWN_ERROR_FAILED,
1114 _("Failed to read from child pipe (%s)"),
1115 g_strerror (errno));
1119 else if (chunk == 0)
1121 else /* chunk > 0 */
1125 *n_ints_read = (gint)(bytes / sizeof(gint));
1131 fork_exec_with_pipes (gboolean intermediate_child,
1132 const gchar *working_directory,
1135 gboolean close_descriptors,
1136 gboolean search_path,
1137 gboolean stdout_to_null,
1138 gboolean stderr_to_null,
1139 gboolean child_inherits_stdin,
1140 gboolean file_and_argv_zero,
1141 GSpawnChildSetupFunc child_setup,
1144 gint *standard_input,
1145 gint *standard_output,
1146 gint *standard_error,
1150 gint stdin_pipe[2] = { -1, -1 };
1151 gint stdout_pipe[2] = { -1, -1 };
1152 gint stderr_pipe[2] = { -1, -1 };
1153 gint child_err_report_pipe[2] = { -1, -1 };
1154 gint child_pid_report_pipe[2] = { -1, -1 };
1157 if (!make_pipe (child_err_report_pipe, error))
1160 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1161 goto cleanup_and_fail;
1163 if (standard_input && !make_pipe (stdin_pipe, error))
1164 goto cleanup_and_fail;
1166 if (standard_output && !make_pipe (stdout_pipe, error))
1167 goto cleanup_and_fail;
1169 if (standard_error && !make_pipe (stderr_pipe, error))
1170 goto cleanup_and_fail;
1179 _("Failed to fork (%s)"),
1180 g_strerror (errno));
1182 goto cleanup_and_fail;
1186 /* Immediate child. This may or may not be the child that
1187 * actually execs the new process.
1190 /* Be sure we crash if the parent exits
1191 * and we write to the err_report_pipe
1193 signal (SIGPIPE, SIG_DFL);
1195 /* Close the parent's end of the pipes;
1196 * not needed in the close_descriptors case,
1199 close_and_invalidate (&child_err_report_pipe[0]);
1200 close_and_invalidate (&child_pid_report_pipe[0]);
1201 close_and_invalidate (&stdin_pipe[1]);
1202 close_and_invalidate (&stdout_pipe[0]);
1203 close_and_invalidate (&stderr_pipe[0]);
1205 if (intermediate_child)
1207 /* We need to fork an intermediate child that launches the
1208 * final child. The purpose of the intermediate child
1209 * is to exit, so we can waitpid() it immediately.
1210 * Then the grandchild will not become a zombie.
1212 GPid grandchild_pid;
1214 grandchild_pid = fork ();
1216 if (grandchild_pid < 0)
1218 /* report -1 as child PID */
1219 write_all (child_pid_report_pipe[1], &grandchild_pid,
1220 sizeof(grandchild_pid));
1222 write_err_and_exit (child_err_report_pipe[1],
1225 else if (grandchild_pid == 0)
1227 do_exec (child_err_report_pipe[1],
1238 child_inherits_stdin,
1245 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1246 close_and_invalidate (&child_pid_report_pipe[1]);
1253 /* Just run the child.
1256 do_exec (child_err_report_pipe[1],
1267 child_inherits_stdin,
1280 /* Close the uncared-about ends of the pipes */
1281 close_and_invalidate (&child_err_report_pipe[1]);
1282 close_and_invalidate (&child_pid_report_pipe[1]);
1283 close_and_invalidate (&stdin_pipe[0]);
1284 close_and_invalidate (&stdout_pipe[1]);
1285 close_and_invalidate (&stderr_pipe[1]);
1287 /* If we had an intermediate child, reap it */
1288 if (intermediate_child)
1291 if (waitpid (pid, &status, 0) < 0)
1295 else if (errno == ECHILD)
1296 ; /* do nothing, child already reaped */
1298 g_warning ("waitpid() should not fail in "
1299 "'fork_exec_with_pipes'");
1304 if (!read_ints (child_err_report_pipe[0],
1307 goto cleanup_and_fail;
1311 /* Error from the child. */
1315 case CHILD_CHDIR_FAILED:
1318 G_SPAWN_ERROR_CHDIR,
1319 _("Failed to change to directory '%s' (%s)"),
1321 g_strerror (buf[1]));
1325 case CHILD_EXEC_FAILED:
1328 exec_err_to_g_error (buf[1]),
1329 _("Failed to execute child process \"%s\" (%s)"),
1331 g_strerror (buf[1]));
1335 case CHILD_DUP2_FAILED:
1338 G_SPAWN_ERROR_FAILED,
1339 _("Failed to redirect output or input of child process (%s)"),
1340 g_strerror (buf[1]));
1344 case CHILD_FORK_FAILED:
1348 _("Failed to fork child process (%s)"),
1349 g_strerror (buf[1]));
1355 G_SPAWN_ERROR_FAILED,
1356 _("Unknown error executing child process \"%s\""),
1361 goto cleanup_and_fail;
1364 /* Get child pid from intermediate child pipe. */
1365 if (intermediate_child)
1369 if (!read_ints (child_pid_report_pipe[0],
1370 buf, 1, &n_ints, error))
1371 goto cleanup_and_fail;
1377 G_SPAWN_ERROR_FAILED,
1378 _("Failed to read enough data from child pid pipe (%s)"),
1379 g_strerror (errno));
1380 goto cleanup_and_fail;
1384 /* we have the child pid */
1389 /* Success against all odds! return the information */
1390 close_and_invalidate (&child_err_report_pipe[0]);
1391 close_and_invalidate (&child_pid_report_pipe[0]);
1397 *standard_input = stdin_pipe[1];
1398 if (standard_output)
1399 *standard_output = stdout_pipe[0];
1401 *standard_error = stderr_pipe[0];
1408 /* There was an error from the Child, reap the child to avoid it being
1415 if (waitpid (pid, NULL, 0) < 0)
1419 else if (errno == ECHILD)
1420 ; /* do nothing, child already reaped */
1422 g_warning ("waitpid() should not fail in "
1423 "'fork_exec_with_pipes'");
1427 close_and_invalidate (&child_err_report_pipe[0]);
1428 close_and_invalidate (&child_err_report_pipe[1]);
1429 close_and_invalidate (&child_pid_report_pipe[0]);
1430 close_and_invalidate (&child_pid_report_pipe[1]);
1431 close_and_invalidate (&stdin_pipe[0]);
1432 close_and_invalidate (&stdin_pipe[1]);
1433 close_and_invalidate (&stdout_pipe[0]);
1434 close_and_invalidate (&stdout_pipe[1]);
1435 close_and_invalidate (&stderr_pipe[0]);
1436 close_and_invalidate (&stderr_pipe[1]);
1442 make_pipe (gint p[2],
1449 G_SPAWN_ERROR_FAILED,
1450 _("Failed to create pipe for communicating with child process (%s)"),
1451 g_strerror (errno));
1458 /* Based on execvp from GNU C Library */
1461 script_execute (const gchar *file,
1464 gboolean search_path)
1466 /* Count the arguments. */
1471 /* Construct an argument list for the shell. */
1475 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1477 new_argv[0] = (char *) "/bin/sh";
1478 new_argv[1] = (char *) file;
1481 new_argv[argc + 1] = argv[argc];
1485 /* Execute the shell. */
1487 execve (new_argv[0], new_argv, envp);
1489 execv (new_argv[0], new_argv);
1496 my_strchrnul (const gchar *str, gchar c)
1498 gchar *p = (gchar*) str;
1499 while (*p && (*p != c))
1506 g_execute (const gchar *file,
1509 gboolean search_path)
1513 /* We check the simple case first. */
1518 if (!search_path || strchr (file, '/') != NULL)
1520 /* Don't search when it contains a slash. */
1522 execve (file, argv, envp);
1526 if (errno == ENOEXEC)
1527 script_execute (file, argv, envp, FALSE);
1531 gboolean got_eacces = 0;
1532 const gchar *path, *p;
1533 gchar *name, *freeme;
1537 path = g_getenv ("PATH");
1540 /* There is no `PATH' in the environment. The default
1541 * search path in libc is the current directory followed by
1542 * the path `confstr' returns for `_CS_PATH'.
1545 /* In GLib we put . last, for security, and don't use the
1546 * unportable confstr(); UNIX98 does not actually specify
1547 * what to search if PATH is unset. POSIX may, dunno.
1550 path = "/bin:/usr/bin:.";
1553 len = strlen (file) + 1;
1554 pathlen = strlen (path);
1555 freeme = name = g_malloc (pathlen + len + 1);
1557 /* Copy the file name at the top, including '\0' */
1558 memcpy (name + pathlen + 1, file, len);
1559 name = name + pathlen;
1560 /* And add the slash before the filename */
1569 p = my_strchrnul (path, ':');
1572 /* Two adjacent colons, or a colon at the beginning or the end
1573 * of `PATH' means to search the current directory.
1577 startp = memcpy (name - (p - path), path, p - path);
1579 /* Try to execute this name. If it works, execv will not return. */
1581 execve (startp, argv, envp);
1583 execv (startp, argv);
1585 if (errno == ENOEXEC)
1586 script_execute (startp, argv, envp, search_path);
1591 /* Record the we got a `Permission denied' error. If we end
1592 * up finding no executable we can use, we want to diagnose
1593 * that we did find one but were denied access.
1606 /* Those errors indicate the file is missing or not executable
1607 * by us, in which case we want to just try the next path
1613 /* Some other error means we found an executable file, but
1614 * something went wrong executing it; return the error to our
1621 while (*p++ != '\0');
1623 /* We tried every element and none of them worked. */
1625 /* At least one failure was due to permissions, so report that
1633 /* Return the error from the last attempt (probably ENOENT). */
1638 * g_spawn_close_pid:
1639 * @pid: The process identifier to close
1641 * On some platforms, notably WIN32, the #GPid type represents a resource
1642 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1643 * is provided for this purpose. It should be used on all platforms, even
1644 * though it doesn't do anything under UNIX.
1647 g_spawn_close_pid (GPid pid)
1651 #define __G_SPAWN_C__
1652 #include "galiasdef.c"