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 */
35 #ifdef HAVE_SYS_SELECT_H
36 #include <sys/select.h>
37 #endif /* HAVE_SYS_SELECT_H */
43 static gint
g_execute (const gchar
*file
,
46 gboolean search_path
);
48 static gboolean
make_pipe (gint p
[2],
50 static gboolean
fork_exec_with_pipes (gboolean intermediate_child
,
51 const gchar
*working_directory
,
54 gboolean close_descriptors
,
56 gboolean stdout_to_null
,
57 gboolean stderr_to_null
,
58 gboolean child_inherits_stdin
,
59 gboolean file_and_argv_zero
,
60 GSpawnChildSetupFunc child_setup
,
64 gint
*standard_output
,
69 g_spawn_error_quark (void)
71 return g_quark_from_static_string ("g-exec-error-quark");
76 * @working_directory: child's current working directory, or %NULL to inherit parent's
77 * @argv: child's argument vector
78 * @envp: child's environment, or %NULL to inherit parent's
79 * @flags: flags from #GSpawnFlags
80 * @child_setup: function to run in the child just before exec()
81 * @user_data: user data for @child_setup
82 * @child_pid: return location for child process ID, or %NULL
83 * @error: return location for error
85 * See g_spawn_async_with_pipes() for a full description; this function
86 * simply calls the g_spawn_async_with_pipes() without any pipes.
89 * If you are writing a GTK+ application, and the program you
90 * are spawning is a graphical application, too, then you may
91 * want to use gdk_spawn_on_screen() instead to ensure that
92 * the spawned program opens its windows no the right screen.
95 * Return value: %TRUE on success, %FALSE if error is set
98 g_spawn_async (const gchar
*working_directory
,
102 GSpawnChildSetupFunc child_setup
,
107 g_return_val_if_fail (argv
!= NULL
, FALSE
);
109 return g_spawn_async_with_pipes (working_directory
,
119 /* Avoids a danger in threaded situations (calling close()
120 * on a file descriptor twice, and another thread has
121 * re-opened it since the first close)
124 close_and_invalidate (gint
*fd
)
139 /* Some versions of OS X define READ_OK in public headers */
144 READ_FAILED
= 0, /* FALSE */
150 read_data (GString
*str
,
159 bytes
= read (fd
, buf
, 4096);
165 g_string_append_len (str
, buf
, bytes
);
168 else if (bytes
< 0 && errno
== EINTR
)
175 _("Failed to read data from child process (%s)"),
186 * @working_directory: child's current working directory, or %NULL to inherit parent's
187 * @argv: child's argument vector
188 * @envp: child's environment, or %NULL to inherit parent's
189 * @flags: flags from #GSpawnFlags
190 * @child_setup: function to run in the child just before exec()
191 * @user_data: user data for @child_setup
192 * @standard_output: return location for child output
193 * @standard_error: return location for child error messages
194 * @exit_status: return location for child exit status, as returned by waitpid()
195 * @error: return location for error
197 * Executes a child synchronously (waits for the child to exit before returning).
198 * All output from the child is stored in @standard_output and @standard_error,
199 * if those parameters are non-%NULL. If @exit_status is non-%NULL, the exit
200 * status of the child is stored there as it would be returned by
201 * waitpid(); standard UNIX macros such as WIFEXITED() and WEXITSTATUS()
202 * must be used to evaluate the exit status. If an error occurs, no data is
203 * returned in @standard_output, @standard_error, or @exit_status.
205 * This function calls g_spawn_async_with_pipes() internally; see that
206 * function for full details on the other parameters and details on
207 * how these functions work on Windows.
209 * Return value: %TRUE on success, %FALSE if an error was set.
212 g_spawn_sync (const gchar
*working_directory
,
216 GSpawnChildSetupFunc child_setup
,
218 gchar
**standard_output
,
219 gchar
**standard_error
,
228 GString
*outstr
= NULL
;
229 GString
*errstr
= NULL
;
233 g_return_val_if_fail (argv
!= NULL
, FALSE
);
234 g_return_val_if_fail (!(flags
& G_SPAWN_DO_NOT_REAP_CHILD
), FALSE
);
235 g_return_val_if_fail (standard_output
== NULL
||
236 !(flags
& G_SPAWN_STDOUT_TO_DEV_NULL
), FALSE
);
237 g_return_val_if_fail (standard_error
== NULL
||
238 !(flags
& G_SPAWN_STDERR_TO_DEV_NULL
), FALSE
);
240 /* Just to ensure segfaults if callers try to use
241 * these when an error is reported.
244 *standard_output
= NULL
;
247 *standard_error
= NULL
;
249 if (!fork_exec_with_pipes (FALSE
,
253 !(flags
& G_SPAWN_LEAVE_DESCRIPTORS_OPEN
),
254 (flags
& G_SPAWN_SEARCH_PATH
) != 0,
255 (flags
& G_SPAWN_STDOUT_TO_DEV_NULL
) != 0,
256 (flags
& G_SPAWN_STDERR_TO_DEV_NULL
) != 0,
257 (flags
& G_SPAWN_CHILD_INHERITS_STDIN
) != 0,
258 (flags
& G_SPAWN_FILE_AND_ARGV_ZERO
) != 0,
263 standard_output
? &outpipe
: NULL
,
264 standard_error
? &errpipe
: NULL
,
268 /* Read data from child. */
274 outstr
= g_string_new (NULL
);
279 errstr
= g_string_new (NULL
);
282 /* Read data until we get EOF on both pipes. */
291 FD_SET (outpipe
, &fds
);
293 FD_SET (errpipe
, &fds
);
295 ret
= select (MAX (outpipe
, errpipe
) + 1,
298 NULL
/* no timeout */);
300 if (ret
< 0 && errno
!= EINTR
)
307 _("Unexpected error in select() reading data from a child process (%s)"),
313 if (outpipe
>= 0 && FD_ISSET (outpipe
, &fds
))
315 switch (read_data (outstr
, outpipe
, error
))
321 close_and_invalidate (&outpipe
);
332 if (errpipe
>= 0 && FD_ISSET (errpipe
, &fds
))
334 switch (read_data (errstr
, errpipe
, error
))
340 close_and_invalidate (&errpipe
);
352 /* These should only be open still if we had an error. */
355 close_and_invalidate (&outpipe
);
357 close_and_invalidate (&errpipe
);
359 /* Wait for child to exit, even if we have
364 ret
= waitpid (pid
, &status
, 0);
370 else if (errno
== ECHILD
)
374 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.");
378 /* We don't need the exit status. */
383 if (!failed
) /* avoid error pileups */
390 _("Unexpected error in waitpid() (%s)"),
399 g_string_free (outstr
, TRUE
);
401 g_string_free (errstr
, TRUE
);
408 *exit_status
= status
;
411 *standard_output
= g_string_free (outstr
, FALSE
);
414 *standard_error
= g_string_free (errstr
, FALSE
);
421 * g_spawn_async_with_pipes:
422 * @working_directory: child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
423 * @argv: child's argument vector, in the GLib file name encoding
424 * @envp: child's environment, or %NULL to inherit parent's, in the GLib file name encoding
425 * @flags: flags from #GSpawnFlags
426 * @child_setup: function to run in the child just before exec()
427 * @user_data: user data for @child_setup
428 * @child_pid: return location for child process ID, or %NULL
429 * @standard_input: return location for file descriptor to write to child's stdin, or %NULL
430 * @standard_output: return location for file descriptor to read child's stdout, or %NULL
431 * @standard_error: return location for file descriptor to read child's stderr, or %NULL
432 * @error: return location for error
434 * Executes a child program asynchronously (your program will not
435 * block waiting for the child to exit). The child program is
436 * specified by the only argument that must be provided, @argv. @argv
437 * should be a %NULL-terminated array of strings, to be passed as the
438 * argument vector for the child. The first string in @argv is of
439 * course the name of the program to execute. By default, the name of
440 * the program must be a full path; the <envar>PATH</envar> shell variable
441 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
443 * On Windows, note that all the string or string vector arguments to
444 * this function and the other g_spawn*() functions are in UTF-8, the
445 * GLib file name encoding. Unicode characters that are not part of
446 * the system codepage passed in argument vectors will be correctly
447 * available in the spawned program only if it uses wide character API
448 * to retrieve its command line. For C programs built with Microsoft's
449 * tools it is enough to make the program have a wmain() instead of
450 * main(). wmain() has a wide character argument vector as parameter.
452 * At least currently, mingw doesn't support wmain(), so if you use
453 * mingw to develop the spawned program, it will have to call the
454 * undocumented function __wgetmainargs() to get the wide character
455 * argument vector and environment. See gspawn-win32-helper.c in the
456 * GLib sources or init.c in the mingw runtime sources for a prototype
457 * for that function. Alternatively, you can retrieve the Win32 system
458 * level wide character command line passed to the spawned program
459 * using the GetCommandLineW() function.
461 * On Windows the low-level child process creation API
462 * <function>CreateProcess()</function> doesn't use argument vectors,
463 * but a command line. The C runtime library's
464 * <function>spawn*()</function> family of functions (which
465 * g_spawn_async_with_pipes() eventually calls) paste the argument
466 * vector elements together into a command line, and the C runtime startup code
467 * does a corresponding reconstruction of an argument vector from the
468 * command line, to be passed to main(). Complications arise when you have
469 * argument vector elements that contain spaces of double quotes. The
470 * <function>spawn*()</function> functions don't do any quoting or
471 * escaping, but on the other hand the startup code does do unquoting
472 * and unescaping in order to enable receiving arguments with embedded
473 * spaces or double quotes. To work around this asymmetry,
474 * g_spawn_async_with_pipes() will do quoting and escaping on argument
475 * vector elements that need it before calling the C runtime
478 * @envp is a %NULL-terminated array of strings, where each string
479 * has the form <literal>KEY=VALUE</literal>. This will become
480 * the child's environment. If @envp is %NULL, the child inherits its
481 * parent's environment.
483 * @flags should be the bitwise OR of any flags you want to affect the
484 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that
485 * the child will not automatically be reaped; you must use a
486 * #GChildWatch source to be notified about the death of the child
487 * process. Eventually you must call g_spawn_close_pid() on the
488 * @child_pid, in order to free resources which may be associated
489 * with the child process. (On Unix, using a #GChildWatch source is
490 * equivalent to calling waitpid() or handling the %SIGCHLD signal
491 * manually. On Windows, calling g_spawn_close_pid() is equivalent
492 * to calling CloseHandle() on the process handle returned in
495 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
496 * descriptors will be inherited by the child; otherwise all
497 * descriptors except stdin/stdout/stderr will be closed before
498 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
499 * means that <literal>argv[0]</literal> need not be an absolute path, it
500 * will be looked for in the user's <envar>PATH</envar>.
501 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
502 * be discarded, instead of going to the same location as the parent's
503 * standard output. If you use this flag, @standard_output must be %NULL.
504 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
505 * will be discarded, instead of going to the same location as the parent's
506 * standard error. If you use this flag, @standard_error must be %NULL.
507 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
508 * standard input (by default, the child's standard input is attached to
509 * /dev/null). If you use this flag, @standard_input must be %NULL.
510 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
511 * the file to execute, while the remaining elements are the
512 * actual argument vector to pass to the file. Normally
513 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
514 * passes all of @argv to the child.
516 * @child_setup and @user_data are a function and user data. On POSIX
517 * platforms, the function is called in the child after GLib has
518 * performed all the setup it plans to perform (including creating
519 * pipes, closing file descriptors, etc.) but before calling
520 * exec(). That is, @child_setup is called just
521 * before calling exec() in the child. Obviously
522 * actions taken in this function will only affect the child, not the
523 * parent. On Windows, there is no separate fork() and exec()
524 * functionality. Child processes are created and run with
525 * a single API call, CreateProcess(). @child_setup is
526 * called in the parent process just before creating the child
527 * process. You should carefully consider what you do in @child_setup
528 * if you intend your software to be portable to Windows.
530 * If non-%NULL, @child_pid will on Unix be filled with the child's
531 * process ID. You can use the process ID to send signals to the
532 * child, or to waitpid() if you specified the
533 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
534 * filled with a handle to the child process only if you specified the
535 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
536 * process using the Win32 API, for example wait for its termination
537 * with the <function>WaitFor*()</function> functions, or examine its
538 * exit code with GetExitCodeProcess(). You should close the handle
539 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
541 * If non-%NULL, the @standard_input, @standard_output, @standard_error
542 * locations will be filled with file descriptors for writing to the child's
543 * standard input or reading from its standard output or standard error.
544 * The caller of g_spawn_async_with_pipes() must close these file descriptors
545 * when they are no longer in use. If these parameters are %NULL, the corresponding
546 * pipe won't be created.
548 * If @standard_input is NULL, the child's standard input is attached to
549 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
551 * If @standard_error is NULL, the child's standard error goes to the same
552 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
555 * If @standard_output is NULL, the child's standard output goes to the same
556 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
559 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
560 * If an error is set, the function returns %FALSE. Errors
561 * are reported even if they occur in the child (for example if the
562 * executable in <literal>argv[0]</literal> is not found). Typically
563 * the <literal>message</literal> field of returned errors should be displayed
564 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
566 * If an error occurs, @child_pid, @standard_input, @standard_output,
567 * and @standard_error will not be filled with valid values.
569 * If @child_pid is not %NULL and an error does not occur then the returned
570 * pid must be closed using g_spawn_close_pid().
573 * If you are writing a GTK+ application, and the program you
574 * are spawning is a graphical application, too, then you may
575 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
576 * the spawned program opens its windows no the right screen.
579 * Return value: %TRUE on success, %FALSE if an error was set
582 g_spawn_async_with_pipes (const gchar
*working_directory
,
586 GSpawnChildSetupFunc child_setup
,
589 gint
*standard_input
,
590 gint
*standard_output
,
591 gint
*standard_error
,
594 g_return_val_if_fail (argv
!= NULL
, FALSE
);
595 g_return_val_if_fail (standard_output
== NULL
||
596 !(flags
& G_SPAWN_STDOUT_TO_DEV_NULL
), FALSE
);
597 g_return_val_if_fail (standard_error
== NULL
||
598 !(flags
& G_SPAWN_STDERR_TO_DEV_NULL
), FALSE
);
599 /* can't inherit stdin if we have an input pipe. */
600 g_return_val_if_fail (standard_input
== NULL
||
601 !(flags
& G_SPAWN_CHILD_INHERITS_STDIN
), FALSE
);
603 return fork_exec_with_pipes (!(flags
& G_SPAWN_DO_NOT_REAP_CHILD
),
607 !(flags
& G_SPAWN_LEAVE_DESCRIPTORS_OPEN
),
608 (flags
& G_SPAWN_SEARCH_PATH
) != 0,
609 (flags
& G_SPAWN_STDOUT_TO_DEV_NULL
) != 0,
610 (flags
& G_SPAWN_STDERR_TO_DEV_NULL
) != 0,
611 (flags
& G_SPAWN_CHILD_INHERITS_STDIN
) != 0,
612 (flags
& G_SPAWN_FILE_AND_ARGV_ZERO
) != 0,
623 * g_spawn_command_line_sync:
624 * @command_line: a command line
625 * @standard_output: return location for child output
626 * @standard_error: return location for child errors
627 * @exit_status: return location for child exit status, as returned by waitpid()
628 * @error: return location for errors
630 * A simple version of g_spawn_sync() with little-used parameters
631 * removed, taking a command line instead of an argument vector. See
632 * g_spawn_sync() for full details. @command_line will be parsed by
633 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
634 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
635 * implications, so consider using g_spawn_sync() directly if
636 * appropriate. Possible errors are those from g_spawn_sync() and those
637 * from g_shell_parse_argv().
639 * If @exit_status is non-%NULL, the exit status of the child is stored there as
640 * it would be returned by waitpid(); standard UNIX macros such as WIFEXITED()
641 * and WEXITSTATUS() must be used to evaluate the exit status.
643 * On Windows, please note the implications of g_shell_parse_argv()
644 * parsing @command_line. Parsing is done according to Unix shell rules, not
645 * Windows command interpreter rules.
646 * Space is a separator, and backslashes are
647 * special. Thus you cannot simply pass a @command_line containing
648 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
649 * the backslashes will be eaten, and the space will act as a
650 * separator. You need to enclose such paths with single quotes, like
651 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
653 * Return value: %TRUE on success, %FALSE if an error was set
656 g_spawn_command_line_sync (const gchar
*command_line
,
657 gchar
**standard_output
,
658 gchar
**standard_error
,
665 g_return_val_if_fail (command_line
!= NULL
, FALSE
);
667 if (!g_shell_parse_argv (command_line
,
672 retval
= g_spawn_sync (NULL
,
688 * g_spawn_command_line_async:
689 * @command_line: a command line
690 * @error: return location for errors
692 * A simple version of g_spawn_async() that parses a command line with
693 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
694 * command line in the background. Unlike g_spawn_async(), the
695 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
696 * that %G_SPAWN_SEARCH_PATH can have security implications, so
697 * consider using g_spawn_async() directly if appropriate. Possible
698 * errors are those from g_shell_parse_argv() and g_spawn_async().
700 * The same concerns on Windows apply as for g_spawn_command_line_sync().
702 * Return value: %TRUE on success, %FALSE if error is set.
705 g_spawn_command_line_async (const gchar
*command_line
,
711 g_return_val_if_fail (command_line
!= NULL
, FALSE
);
713 if (!g_shell_parse_argv (command_line
,
718 retval
= g_spawn_async (NULL
,
732 exec_err_to_g_error (gint en
)
738 return G_SPAWN_ERROR_ACCES
;
744 return G_SPAWN_ERROR_PERM
;
750 return G_SPAWN_ERROR_2BIG
;
756 return G_SPAWN_ERROR_NOEXEC
;
762 return G_SPAWN_ERROR_NAMETOOLONG
;
768 return G_SPAWN_ERROR_NOENT
;
774 return G_SPAWN_ERROR_NOMEM
;
780 return G_SPAWN_ERROR_NOTDIR
;
786 return G_SPAWN_ERROR_LOOP
;
792 return G_SPAWN_ERROR_TXTBUSY
;
798 return G_SPAWN_ERROR_IO
;
804 return G_SPAWN_ERROR_NFILE
;
810 return G_SPAWN_ERROR_MFILE
;
816 return G_SPAWN_ERROR_INVAL
;
822 return G_SPAWN_ERROR_ISDIR
;
828 return G_SPAWN_ERROR_LIBBAD
;
833 return G_SPAWN_ERROR_FAILED
;
839 write_all (gint fd
, gconstpointer vbuf
, gsize to_write
)
841 gchar
*buf
= (gchar
*) vbuf
;
845 gssize count
= write (fd
, buf
, to_write
);
862 write_err_and_exit (gint fd
, gint msg
)
866 write_all (fd
, &msg
, sizeof(msg
));
867 write_all (fd
, &en
, sizeof(en
));
873 set_cloexec (void *data
, gint fd
)
875 if (fd
>= GPOINTER_TO_INT (data
))
876 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
883 fdwalk (int (*cb
)(void *data
, int fd
), void *data
)
890 open_max
= sysconf (_SC_OPEN_MAX
);
891 for (fd
= 0; fd
< open_max
&& res
== 0; fd
++)
899 sane_dup2 (gint fd1
, gint fd2
)
904 ret
= dup2 (fd1
, fd2
);
905 if (ret
< 0 && errno
== EINTR
)
920 do_exec (gint child_err_report_fd
,
924 const gchar
*working_directory
,
927 gboolean close_descriptors
,
928 gboolean search_path
,
929 gboolean stdout_to_null
,
930 gboolean stderr_to_null
,
931 gboolean child_inherits_stdin
,
932 gboolean file_and_argv_zero
,
933 GSpawnChildSetupFunc child_setup
,
936 if (working_directory
&& chdir (working_directory
) < 0)
937 write_err_and_exit (child_err_report_fd
,
940 /* Close all file descriptors but stdin stdout and stderr as
941 * soon as we exec. Note that this includes
942 * child_err_report_fd, which keeps the parent from blocking
943 * forever on the other end of that pipe.
945 if (close_descriptors
)
947 fdwalk (set_cloexec
, GINT_TO_POINTER(3));
951 /* We need to do child_err_report_fd anyway */
952 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd
);
955 /* Redirect pipes as required */
959 /* dup2 can't actually fail here I don't think */
961 if (sane_dup2 (stdin_fd
, 0) < 0)
962 write_err_and_exit (child_err_report_fd
,
965 /* ignore this if it doesn't work */
966 close_and_invalidate (&stdin_fd
);
968 else if (!child_inherits_stdin
)
970 /* Keep process from blocking on a read of stdin */
971 gint read_null
= open ("/dev/null", O_RDONLY
);
972 sane_dup2 (read_null
, 0);
973 close_and_invalidate (&read_null
);
978 /* dup2 can't actually fail here I don't think */
980 if (sane_dup2 (stdout_fd
, 1) < 0)
981 write_err_and_exit (child_err_report_fd
,
984 /* ignore this if it doesn't work */
985 close_and_invalidate (&stdout_fd
);
987 else if (stdout_to_null
)
989 gint write_null
= open ("/dev/null", O_WRONLY
);
990 sane_dup2 (write_null
, 1);
991 close_and_invalidate (&write_null
);
996 /* dup2 can't actually fail here I don't think */
998 if (sane_dup2 (stderr_fd
, 2) < 0)
999 write_err_and_exit (child_err_report_fd
,
1002 /* ignore this if it doesn't work */
1003 close_and_invalidate (&stderr_fd
);
1005 else if (stderr_to_null
)
1007 gint write_null
= open ("/dev/null", O_WRONLY
);
1008 sane_dup2 (write_null
, 2);
1009 close_and_invalidate (&write_null
);
1012 /* Call user function just before we exec */
1015 (* child_setup
) (user_data
);
1019 file_and_argv_zero
? argv
+ 1 : argv
,
1023 write_err_and_exit (child_err_report_fd
,
1040 if (bytes
>= sizeof(gint
)*2)
1041 break; /* give up, who knows what happened, should not be
1047 ((gchar
*)buf
) + bytes
,
1048 sizeof(gint
) * n_ints_in_buf
- bytes
);
1049 if (chunk
< 0 && errno
== EINTR
)
1054 /* Some weird shit happened, bail out */
1058 G_SPAWN_ERROR_FAILED
,
1059 _("Failed to read from child pipe (%s)"),
1060 g_strerror (errno
));
1064 else if (chunk
== 0)
1066 else /* chunk > 0 */
1070 *n_ints_read
= (gint
)(bytes
/ sizeof(gint
));
1076 fork_exec_with_pipes (gboolean intermediate_child
,
1077 const gchar
*working_directory
,
1080 gboolean close_descriptors
,
1081 gboolean search_path
,
1082 gboolean stdout_to_null
,
1083 gboolean stderr_to_null
,
1084 gboolean child_inherits_stdin
,
1085 gboolean file_and_argv_zero
,
1086 GSpawnChildSetupFunc child_setup
,
1089 gint
*standard_input
,
1090 gint
*standard_output
,
1091 gint
*standard_error
,
1095 gint stdin_pipe
[2] = { -1, -1 };
1096 gint stdout_pipe
[2] = { -1, -1 };
1097 gint stderr_pipe
[2] = { -1, -1 };
1098 gint child_err_report_pipe
[2] = { -1, -1 };
1099 gint child_pid_report_pipe
[2] = { -1, -1 };
1102 if (!make_pipe (child_err_report_pipe
, error
))
1105 if (intermediate_child
&& !make_pipe (child_pid_report_pipe
, error
))
1106 goto cleanup_and_fail
;
1108 if (standard_input
&& !make_pipe (stdin_pipe
, error
))
1109 goto cleanup_and_fail
;
1111 if (standard_output
&& !make_pipe (stdout_pipe
, error
))
1112 goto cleanup_and_fail
;
1114 if (standard_error
&& !make_pipe (stderr_pipe
, error
))
1115 goto cleanup_and_fail
;
1124 _("Failed to fork (%s)"),
1125 g_strerror (errno
));
1127 goto cleanup_and_fail
;
1131 /* Immediate child. This may or may not be the child that
1132 * actually execs the new process.
1135 /* Be sure we crash if the parent exits
1136 * and we write to the err_report_pipe
1138 signal (SIGPIPE
, SIG_DFL
);
1140 /* Close the parent's end of the pipes;
1141 * not needed in the close_descriptors case,
1144 close_and_invalidate (&child_err_report_pipe
[0]);
1145 close_and_invalidate (&child_pid_report_pipe
[0]);
1146 close_and_invalidate (&stdin_pipe
[1]);
1147 close_and_invalidate (&stdout_pipe
[0]);
1148 close_and_invalidate (&stderr_pipe
[0]);
1150 if (intermediate_child
)
1152 /* We need to fork an intermediate child that launches the
1153 * final child. The purpose of the intermediate child
1154 * is to exit, so we can waitpid() it immediately.
1155 * Then the grandchild will not become a zombie.
1157 GPid grandchild_pid
;
1159 grandchild_pid
= fork ();
1161 if (grandchild_pid
< 0)
1163 /* report -1 as child PID */
1164 write_all (child_pid_report_pipe
[1], &grandchild_pid
,
1165 sizeof(grandchild_pid
));
1167 write_err_and_exit (child_err_report_pipe
[1],
1170 else if (grandchild_pid
== 0)
1172 do_exec (child_err_report_pipe
[1],
1183 child_inherits_stdin
,
1190 write_all (child_pid_report_pipe
[1], &grandchild_pid
, sizeof(grandchild_pid
));
1191 close_and_invalidate (&child_pid_report_pipe
[1]);
1198 /* Just run the child.
1201 do_exec (child_err_report_pipe
[1],
1212 child_inherits_stdin
,
1225 /* Close the uncared-about ends of the pipes */
1226 close_and_invalidate (&child_err_report_pipe
[1]);
1227 close_and_invalidate (&child_pid_report_pipe
[1]);
1228 close_and_invalidate (&stdin_pipe
[0]);
1229 close_and_invalidate (&stdout_pipe
[1]);
1230 close_and_invalidate (&stderr_pipe
[1]);
1232 /* If we had an intermediate child, reap it */
1233 if (intermediate_child
)
1236 if (waitpid (pid
, &status
, 0) < 0)
1240 else if (errno
== ECHILD
)
1241 ; /* do nothing, child already reaped */
1243 g_warning ("waitpid() should not fail in "
1244 "'fork_exec_with_pipes'");
1249 if (!read_ints (child_err_report_pipe
[0],
1252 goto cleanup_and_fail
;
1256 /* Error from the child. */
1260 case CHILD_CHDIR_FAILED
:
1263 G_SPAWN_ERROR_CHDIR
,
1264 _("Failed to change to directory '%s' (%s)"),
1266 g_strerror (buf
[1]));
1270 case CHILD_EXEC_FAILED
:
1273 exec_err_to_g_error (buf
[1]),
1274 _("Failed to execute child process \"%s\" (%s)"),
1276 g_strerror (buf
[1]));
1280 case CHILD_DUP2_FAILED
:
1283 G_SPAWN_ERROR_FAILED
,
1284 _("Failed to redirect output or input of child process (%s)"),
1285 g_strerror (buf
[1]));
1289 case CHILD_FORK_FAILED
:
1293 _("Failed to fork child process (%s)"),
1294 g_strerror (buf
[1]));
1300 G_SPAWN_ERROR_FAILED
,
1301 _("Unknown error executing child process \"%s\""),
1306 goto cleanup_and_fail
;
1309 /* Get child pid from intermediate child pipe. */
1310 if (intermediate_child
)
1314 if (!read_ints (child_pid_report_pipe
[0],
1315 buf
, 1, &n_ints
, error
))
1316 goto cleanup_and_fail
;
1322 G_SPAWN_ERROR_FAILED
,
1323 _("Failed to read enough data from child pid pipe (%s)"),
1324 g_strerror (errno
));
1325 goto cleanup_and_fail
;
1329 /* we have the child pid */
1334 /* Success against all odds! return the information */
1335 close_and_invalidate (&child_err_report_pipe
[0]);
1336 close_and_invalidate (&child_pid_report_pipe
[0]);
1342 *standard_input
= stdin_pipe
[1];
1343 if (standard_output
)
1344 *standard_output
= stdout_pipe
[0];
1346 *standard_error
= stderr_pipe
[0];
1353 /* There was an error from the Child, reap the child to avoid it being
1360 if (waitpid (pid
, NULL
, 0) < 0)
1364 else if (errno
== ECHILD
)
1365 ; /* do nothing, child already reaped */
1367 g_warning ("waitpid() should not fail in "
1368 "'fork_exec_with_pipes'");
1372 close_and_invalidate (&child_err_report_pipe
[0]);
1373 close_and_invalidate (&child_err_report_pipe
[1]);
1374 close_and_invalidate (&child_pid_report_pipe
[0]);
1375 close_and_invalidate (&child_pid_report_pipe
[1]);
1376 close_and_invalidate (&stdin_pipe
[0]);
1377 close_and_invalidate (&stdin_pipe
[1]);
1378 close_and_invalidate (&stdout_pipe
[0]);
1379 close_and_invalidate (&stdout_pipe
[1]);
1380 close_and_invalidate (&stderr_pipe
[0]);
1381 close_and_invalidate (&stderr_pipe
[1]);
1387 make_pipe (gint p
[2],
1394 G_SPAWN_ERROR_FAILED
,
1395 _("Failed to create pipe for communicating with child process (%s)"),
1396 g_strerror (errno
));
1403 /* Based on execvp from GNU C Library */
1406 script_execute (const gchar
*file
,
1409 gboolean search_path
)
1411 /* Count the arguments. */
1416 /* Construct an argument list for the shell. */
1420 new_argv
= g_new0 (gchar
*, argc
+ 2); /* /bin/sh and NULL */
1422 new_argv
[0] = (char *) "/bin/sh";
1423 new_argv
[1] = (char *) file
;
1426 new_argv
[argc
+ 1] = argv
[argc
];
1430 /* Execute the shell. */
1432 execve (new_argv
[0], new_argv
, envp
);
1434 execv (new_argv
[0], new_argv
);
1441 my_strchrnul (const gchar
*str
, gchar c
)
1443 gchar
*p
= (gchar
*) str
;
1444 while (*p
&& (*p
!= c
))
1451 g_execute (const gchar
*file
,
1454 gboolean search_path
)
1458 /* We check the simple case first. */
1463 if (!search_path
|| strchr (file
, '/') != NULL
)
1465 /* Don't search when it contains a slash. */
1467 execve (file
, argv
, envp
);
1471 if (errno
== ENOEXEC
)
1472 script_execute (file
, argv
, envp
, FALSE
);
1476 gboolean got_eacces
= 0;
1477 const gchar
*path
, *p
;
1478 gchar
*name
, *freeme
;
1482 path
= g_getenv ("PATH");
1485 /* There is no `PATH' in the environment. The default
1486 * search path in libc is the current directory followed by
1487 * the path `confstr' returns for `_CS_PATH'.
1490 /* In GLib we put . last, for security, and don't use the
1491 * unportable confstr(); UNIX98 does not actually specify
1492 * what to search if PATH is unset. POSIX may, dunno.
1495 path
= "/bin:/usr/bin:.";
1498 len
= strlen (file
) + 1;
1499 pathlen
= strlen (path
);
1500 freeme
= name
= g_malloc (pathlen
+ len
+ 1);
1502 /* Copy the file name at the top, including '\0' */
1503 memcpy (name
+ pathlen
+ 1, file
, len
);
1504 name
= name
+ pathlen
;
1505 /* And add the slash before the filename */
1514 p
= my_strchrnul (path
, ':');
1517 /* Two adjacent colons, or a colon at the beginning or the end
1518 * of `PATH' means to search the current directory.
1522 startp
= memcpy (name
- (p
- path
), path
, p
- path
);
1524 /* Try to execute this name. If it works, execv will not return. */
1526 execve (startp
, argv
, envp
);
1528 execv (startp
, argv
);
1530 if (errno
== ENOEXEC
)
1531 script_execute (startp
, argv
, envp
, search_path
);
1536 /* Record the we got a `Permission denied' error. If we end
1537 * up finding no executable we can use, we want to diagnose
1538 * that we did find one but were denied access.
1551 /* Those errors indicate the file is missing or not executable
1552 * by us, in which case we want to just try the next path
1558 /* Some other error means we found an executable file, but
1559 * something went wrong executing it; return the error to our
1566 while (*p
++ != '\0');
1568 /* We tried every element and none of them worked. */
1570 /* At least one failure was due to permissions, so report that
1578 /* Return the error from the last attempt (probably ENOENT). */
1583 * g_spawn_close_pid:
1584 * @pid: The process identifier to close
1586 * On some platforms, notably WIN32, the #GPid type represents a resource
1587 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1588 * is provided for this purpose. It should be used on all platforms, even
1589 * though it doesn't do anything under UNIX.
1592 g_spawn_close_pid (GPid pid
)
1596 #define __G_SPAWN_C__
1597 #include "galiasdef.c"