Move docs inline, and improve wording. (#372598, Behdad Esfahbod)
[glib.git] / glib / gspawn.c
blobea183a596be97328318be6557fe325832b35ec07
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.
23 #include "config.h"
25 #include <sys/time.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <string.h>
33 #include <stdlib.h> /* for fdwalk */
35 #ifdef HAVE_SYS_SELECT_H
36 #include <sys/select.h>
37 #endif /* HAVE_SYS_SELECT_H */
39 #include "glib.h"
40 #include "glibintl.h"
41 #include "galias.h"
43 static gint g_execute (const gchar *file,
44 gchar **argv,
45 gchar **envp,
46 gboolean search_path);
48 static gboolean make_pipe (gint p[2],
49 GError **error);
50 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
51 const gchar *working_directory,
52 gchar **argv,
53 gchar **envp,
54 gboolean close_descriptors,
55 gboolean search_path,
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,
61 gpointer user_data,
62 GPid *child_pid,
63 gint *standard_input,
64 gint *standard_output,
65 gint *standard_error,
66 GError **error);
68 GQuark
69 g_spawn_error_quark (void)
71 return g_quark_from_static_string ("g-exec-error-quark");
74 /**
75 * g_spawn_async:
76 * @working_directory: child's current working directory, or %NULL to inherit parent's
77 * @argv: child's argument vector
78 * @envp: child's environment, or %NULL to inherit parent's
79 * @flags: flags from #GSpawnFlags
80 * @child_setup: function to run in the child just before exec()
81 * @user_data: user data for @child_setup
82 * @child_pid: return location for child process ID, or %NULL
83 * @error: return location for error
85 * See g_spawn_async_with_pipes() for a full description; this function
86 * simply calls the g_spawn_async_with_pipes() without any pipes.
88 * <note><para>
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.
93 * </para></note>
95 * Return value: %TRUE on success, %FALSE if error is set
96 **/
97 gboolean
98 g_spawn_async (const gchar *working_directory,
99 gchar **argv,
100 gchar **envp,
101 GSpawnFlags flags,
102 GSpawnChildSetupFunc child_setup,
103 gpointer user_data,
104 GPid *child_pid,
105 GError **error)
107 g_return_val_if_fail (argv != NULL, FALSE);
109 return g_spawn_async_with_pipes (working_directory,
110 argv, envp,
111 flags,
112 child_setup,
113 user_data,
114 child_pid,
115 NULL, NULL, NULL,
116 error);
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)
123 static gint
124 close_and_invalidate (gint *fd)
126 gint ret;
128 if (*fd < 0)
129 return -1;
130 else
132 ret = close (*fd);
133 *fd = -1;
136 return ret;
139 /* Some versions of OS X define READ_OK in public headers */
140 #undef READ_OK
142 typedef enum
144 READ_FAILED = 0, /* FALSE */
145 READ_OK,
146 READ_EOF
147 } ReadResult;
149 static ReadResult
150 read_data (GString *str,
151 gint fd,
152 GError **error)
154 gssize bytes;
155 gchar buf[4096];
157 again:
159 bytes = read (fd, buf, 4096);
161 if (bytes == 0)
162 return READ_EOF;
163 else if (bytes > 0)
165 g_string_append_len (str, buf, bytes);
166 return READ_OK;
168 else if (bytes < 0 && errno == EINTR)
169 goto again;
170 else if (bytes < 0)
172 g_set_error (error,
173 G_SPAWN_ERROR,
174 G_SPAWN_ERROR_READ,
175 _("Failed to read data from child process (%s)"),
176 g_strerror (errno));
178 return READ_FAILED;
180 else
181 return READ_OK;
185 * g_spawn_sync:
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.
211 gboolean
212 g_spawn_sync (const gchar *working_directory,
213 gchar **argv,
214 gchar **envp,
215 GSpawnFlags flags,
216 GSpawnChildSetupFunc child_setup,
217 gpointer user_data,
218 gchar **standard_output,
219 gchar **standard_error,
220 gint *exit_status,
221 GError **error)
223 gint outpipe = -1;
224 gint errpipe = -1;
225 GPid pid;
226 fd_set fds;
227 gint ret;
228 GString *outstr = NULL;
229 GString *errstr = NULL;
230 gboolean failed;
231 gint status;
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.
243 if (standard_output)
244 *standard_output = NULL;
246 if (standard_error)
247 *standard_error = NULL;
249 if (!fork_exec_with_pipes (FALSE,
250 working_directory,
251 argv,
252 envp,
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,
259 child_setup,
260 user_data,
261 &pid,
262 NULL,
263 standard_output ? &outpipe : NULL,
264 standard_error ? &errpipe : NULL,
265 error))
266 return FALSE;
268 /* Read data from child. */
270 failed = FALSE;
272 if (outpipe >= 0)
274 outstr = g_string_new (NULL);
277 if (errpipe >= 0)
279 errstr = g_string_new (NULL);
282 /* Read data until we get EOF on both pipes. */
283 while (!failed &&
284 (outpipe >= 0 ||
285 errpipe >= 0))
287 ret = 0;
289 FD_ZERO (&fds);
290 if (outpipe >= 0)
291 FD_SET (outpipe, &fds);
292 if (errpipe >= 0)
293 FD_SET (errpipe, &fds);
295 ret = select (MAX (outpipe, errpipe) + 1,
296 &fds,
297 NULL, NULL,
298 NULL /* no timeout */);
300 if (ret < 0 && errno != EINTR)
302 failed = TRUE;
304 g_set_error (error,
305 G_SPAWN_ERROR,
306 G_SPAWN_ERROR_READ,
307 _("Unexpected error in select() reading data from a child process (%s)"),
308 g_strerror (errno));
310 break;
313 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
315 switch (read_data (outstr, outpipe, error))
317 case READ_FAILED:
318 failed = TRUE;
319 break;
320 case READ_EOF:
321 close_and_invalidate (&outpipe);
322 outpipe = -1;
323 break;
324 default:
325 break;
328 if (failed)
329 break;
332 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
334 switch (read_data (errstr, errpipe, error))
336 case READ_FAILED:
337 failed = TRUE;
338 break;
339 case READ_EOF:
340 close_and_invalidate (&errpipe);
341 errpipe = -1;
342 break;
343 default:
344 break;
347 if (failed)
348 break;
352 /* These should only be open still if we had an error. */
354 if (outpipe >= 0)
355 close_and_invalidate (&outpipe);
356 if (errpipe >= 0)
357 close_and_invalidate (&errpipe);
359 /* Wait for child to exit, even if we have
360 * an error pending.
362 again:
364 ret = waitpid (pid, &status, 0);
366 if (ret < 0)
368 if (errno == EINTR)
369 goto again;
370 else if (errno == ECHILD)
372 if (exit_status)
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.");
376 else
378 /* We don't need the exit status. */
381 else
383 if (!failed) /* avoid error pileups */
385 failed = TRUE;
387 g_set_error (error,
388 G_SPAWN_ERROR,
389 G_SPAWN_ERROR_READ,
390 _("Unexpected error in waitpid() (%s)"),
391 g_strerror (errno));
396 if (failed)
398 if (outstr)
399 g_string_free (outstr, TRUE);
400 if (errstr)
401 g_string_free (errstr, TRUE);
403 return FALSE;
405 else
407 if (exit_status)
408 *exit_status = status;
410 if (standard_output)
411 *standard_output = g_string_free (outstr, FALSE);
413 if (standard_error)
414 *standard_error = g_string_free (errstr, FALSE);
416 return TRUE;
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
476 * spawn() function.
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
493 * @child_pid).
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
553 * is set.
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
557 * is set.
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().
572 * <note><para>
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.
577 * </para></note>
579 * Return value: %TRUE on success, %FALSE if an error was set
581 gboolean
582 g_spawn_async_with_pipes (const gchar *working_directory,
583 gchar **argv,
584 gchar **envp,
585 GSpawnFlags flags,
586 GSpawnChildSetupFunc child_setup,
587 gpointer user_data,
588 GPid *child_pid,
589 gint *standard_input,
590 gint *standard_output,
591 gint *standard_error,
592 GError **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),
604 working_directory,
605 argv,
606 envp,
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,
613 child_setup,
614 user_data,
615 child_pid,
616 standard_input,
617 standard_output,
618 standard_error,
619 error);
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
655 gboolean
656 g_spawn_command_line_sync (const gchar *command_line,
657 gchar **standard_output,
658 gchar **standard_error,
659 gint *exit_status,
660 GError **error)
662 gboolean retval;
663 gchar **argv = NULL;
665 g_return_val_if_fail (command_line != NULL, FALSE);
667 if (!g_shell_parse_argv (command_line,
668 NULL, &argv,
669 error))
670 return FALSE;
672 retval = g_spawn_sync (NULL,
673 argv,
674 NULL,
675 G_SPAWN_SEARCH_PATH,
676 NULL,
677 NULL,
678 standard_output,
679 standard_error,
680 exit_status,
681 error);
682 g_strfreev (argv);
684 return retval;
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.
704 gboolean
705 g_spawn_command_line_async (const gchar *command_line,
706 GError **error)
708 gboolean retval;
709 gchar **argv = NULL;
711 g_return_val_if_fail (command_line != NULL, FALSE);
713 if (!g_shell_parse_argv (command_line,
714 NULL, &argv,
715 error))
716 return FALSE;
718 retval = g_spawn_async (NULL,
719 argv,
720 NULL,
721 G_SPAWN_SEARCH_PATH,
722 NULL,
723 NULL,
724 NULL,
725 error);
726 g_strfreev (argv);
728 return retval;
731 static gint
732 exec_err_to_g_error (gint en)
734 switch (en)
736 #ifdef EACCES
737 case EACCES:
738 return G_SPAWN_ERROR_ACCES;
739 break;
740 #endif
742 #ifdef EPERM
743 case EPERM:
744 return G_SPAWN_ERROR_PERM;
745 break;
746 #endif
748 #ifdef E2BIG
749 case E2BIG:
750 return G_SPAWN_ERROR_2BIG;
751 break;
752 #endif
754 #ifdef ENOEXEC
755 case ENOEXEC:
756 return G_SPAWN_ERROR_NOEXEC;
757 break;
758 #endif
760 #ifdef ENAMETOOLONG
761 case ENAMETOOLONG:
762 return G_SPAWN_ERROR_NAMETOOLONG;
763 break;
764 #endif
766 #ifdef ENOENT
767 case ENOENT:
768 return G_SPAWN_ERROR_NOENT;
769 break;
770 #endif
772 #ifdef ENOMEM
773 case ENOMEM:
774 return G_SPAWN_ERROR_NOMEM;
775 break;
776 #endif
778 #ifdef ENOTDIR
779 case ENOTDIR:
780 return G_SPAWN_ERROR_NOTDIR;
781 break;
782 #endif
784 #ifdef ELOOP
785 case ELOOP:
786 return G_SPAWN_ERROR_LOOP;
787 break;
788 #endif
790 #ifdef ETXTBUSY
791 case ETXTBUSY:
792 return G_SPAWN_ERROR_TXTBUSY;
793 break;
794 #endif
796 #ifdef EIO
797 case EIO:
798 return G_SPAWN_ERROR_IO;
799 break;
800 #endif
802 #ifdef ENFILE
803 case ENFILE:
804 return G_SPAWN_ERROR_NFILE;
805 break;
806 #endif
808 #ifdef EMFILE
809 case EMFILE:
810 return G_SPAWN_ERROR_MFILE;
811 break;
812 #endif
814 #ifdef EINVAL
815 case EINVAL:
816 return G_SPAWN_ERROR_INVAL;
817 break;
818 #endif
820 #ifdef EISDIR
821 case EISDIR:
822 return G_SPAWN_ERROR_ISDIR;
823 break;
824 #endif
826 #ifdef ELIBBAD
827 case ELIBBAD:
828 return G_SPAWN_ERROR_LIBBAD;
829 break;
830 #endif
832 default:
833 return G_SPAWN_ERROR_FAILED;
834 break;
838 static gssize
839 write_all (gint fd, gconstpointer vbuf, gsize to_write)
841 gchar *buf = (gchar *) vbuf;
843 while (to_write > 0)
845 gssize count = write (fd, buf, to_write);
846 if (count < 0)
848 if (errno != EINTR)
849 return FALSE;
851 else
853 to_write -= count;
854 buf += count;
858 return TRUE;
861 static void
862 write_err_and_exit (gint fd, gint msg)
864 gint en = errno;
866 write_all (fd, &msg, sizeof(msg));
867 write_all (fd, &en, sizeof(en));
869 _exit (1);
872 static int
873 set_cloexec (void *data, gint fd)
875 if (fd >= GPOINTER_TO_INT (data))
876 fcntl (fd, F_SETFD, FD_CLOEXEC);
878 return 0;
881 #ifndef HAVE_FDWALK
882 static int
883 fdwalk (int (*cb)(void *data, int fd), void *data)
885 gint open_max;
886 gint fd;
887 gint res;
889 res = 0;
890 open_max = sysconf (_SC_OPEN_MAX);
891 for (fd = 0; fd < open_max && res == 0; fd++)
892 res = cb (data, fd);
894 return res;
896 #endif
898 static gint
899 sane_dup2 (gint fd1, gint fd2)
901 gint ret;
903 retry:
904 ret = dup2 (fd1, fd2);
905 if (ret < 0 && errno == EINTR)
906 goto retry;
908 return ret;
911 enum
913 CHILD_CHDIR_FAILED,
914 CHILD_EXEC_FAILED,
915 CHILD_DUP2_FAILED,
916 CHILD_FORK_FAILED
919 static void
920 do_exec (gint child_err_report_fd,
921 gint stdin_fd,
922 gint stdout_fd,
923 gint stderr_fd,
924 const gchar *working_directory,
925 gchar **argv,
926 gchar **envp,
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,
934 gpointer user_data)
936 if (working_directory && chdir (working_directory) < 0)
937 write_err_and_exit (child_err_report_fd,
938 CHILD_CHDIR_FAILED);
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));
949 else
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 */
957 if (stdin_fd >= 0)
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,
963 CHILD_DUP2_FAILED);
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);
976 if (stdout_fd >= 0)
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,
982 CHILD_DUP2_FAILED);
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);
994 if (stderr_fd >= 0)
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,
1000 CHILD_DUP2_FAILED);
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 */
1013 if (child_setup)
1015 (* child_setup) (user_data);
1018 g_execute (argv[0],
1019 file_and_argv_zero ? argv + 1 : argv,
1020 envp, search_path);
1022 /* Exec failed */
1023 write_err_and_exit (child_err_report_fd,
1024 CHILD_EXEC_FAILED);
1027 static gboolean
1028 read_ints (int fd,
1029 gint* buf,
1030 gint n_ints_in_buf,
1031 gint *n_ints_read,
1032 GError **error)
1034 gsize bytes = 0;
1036 while (TRUE)
1038 gssize chunk;
1040 if (bytes >= sizeof(gint)*2)
1041 break; /* give up, who knows what happened, should not be
1042 * possible.
1045 again:
1046 chunk = read (fd,
1047 ((gchar*)buf) + bytes,
1048 sizeof(gint) * n_ints_in_buf - bytes);
1049 if (chunk < 0 && errno == EINTR)
1050 goto again;
1052 if (chunk < 0)
1054 /* Some weird shit happened, bail out */
1056 g_set_error (error,
1057 G_SPAWN_ERROR,
1058 G_SPAWN_ERROR_FAILED,
1059 _("Failed to read from child pipe (%s)"),
1060 g_strerror (errno));
1062 return FALSE;
1064 else if (chunk == 0)
1065 break; /* EOF */
1066 else /* chunk > 0 */
1067 bytes += chunk;
1070 *n_ints_read = (gint)(bytes / sizeof(gint));
1072 return TRUE;
1075 static gboolean
1076 fork_exec_with_pipes (gboolean intermediate_child,
1077 const gchar *working_directory,
1078 gchar **argv,
1079 gchar **envp,
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,
1087 gpointer user_data,
1088 GPid *child_pid,
1089 gint *standard_input,
1090 gint *standard_output,
1091 gint *standard_error,
1092 GError **error)
1094 GPid pid = -1;
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 };
1100 gint status;
1102 if (!make_pipe (child_err_report_pipe, error))
1103 return FALSE;
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;
1117 pid = fork ();
1119 if (pid < 0)
1121 g_set_error (error,
1122 G_SPAWN_ERROR,
1123 G_SPAWN_ERROR_FORK,
1124 _("Failed to fork (%s)"),
1125 g_strerror (errno));
1127 goto cleanup_and_fail;
1129 else if (pid == 0)
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,
1142 * though
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],
1168 CHILD_FORK_FAILED);
1170 else if (grandchild_pid == 0)
1172 do_exec (child_err_report_pipe[1],
1173 stdin_pipe[0],
1174 stdout_pipe[1],
1175 stderr_pipe[1],
1176 working_directory,
1177 argv,
1178 envp,
1179 close_descriptors,
1180 search_path,
1181 stdout_to_null,
1182 stderr_to_null,
1183 child_inherits_stdin,
1184 file_and_argv_zero,
1185 child_setup,
1186 user_data);
1188 else
1190 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1191 close_and_invalidate (&child_pid_report_pipe[1]);
1193 _exit (0);
1196 else
1198 /* Just run the child.
1201 do_exec (child_err_report_pipe[1],
1202 stdin_pipe[0],
1203 stdout_pipe[1],
1204 stderr_pipe[1],
1205 working_directory,
1206 argv,
1207 envp,
1208 close_descriptors,
1209 search_path,
1210 stdout_to_null,
1211 stderr_to_null,
1212 child_inherits_stdin,
1213 file_and_argv_zero,
1214 child_setup,
1215 user_data);
1218 else
1220 /* Parent */
1222 gint buf[2];
1223 gint n_ints = 0;
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)
1235 wait_again:
1236 if (waitpid (pid, &status, 0) < 0)
1238 if (errno == EINTR)
1239 goto wait_again;
1240 else if (errno == ECHILD)
1241 ; /* do nothing, child already reaped */
1242 else
1243 g_warning ("waitpid() should not fail in "
1244 "'fork_exec_with_pipes'");
1249 if (!read_ints (child_err_report_pipe[0],
1250 buf, 2, &n_ints,
1251 error))
1252 goto cleanup_and_fail;
1254 if (n_ints >= 2)
1256 /* Error from the child. */
1258 switch (buf[0])
1260 case CHILD_CHDIR_FAILED:
1261 g_set_error (error,
1262 G_SPAWN_ERROR,
1263 G_SPAWN_ERROR_CHDIR,
1264 _("Failed to change to directory '%s' (%s)"),
1265 working_directory,
1266 g_strerror (buf[1]));
1268 break;
1270 case CHILD_EXEC_FAILED:
1271 g_set_error (error,
1272 G_SPAWN_ERROR,
1273 exec_err_to_g_error (buf[1]),
1274 _("Failed to execute child process \"%s\" (%s)"),
1275 argv[0],
1276 g_strerror (buf[1]));
1278 break;
1280 case CHILD_DUP2_FAILED:
1281 g_set_error (error,
1282 G_SPAWN_ERROR,
1283 G_SPAWN_ERROR_FAILED,
1284 _("Failed to redirect output or input of child process (%s)"),
1285 g_strerror (buf[1]));
1287 break;
1289 case CHILD_FORK_FAILED:
1290 g_set_error (error,
1291 G_SPAWN_ERROR,
1292 G_SPAWN_ERROR_FORK,
1293 _("Failed to fork child process (%s)"),
1294 g_strerror (buf[1]));
1295 break;
1297 default:
1298 g_set_error (error,
1299 G_SPAWN_ERROR,
1300 G_SPAWN_ERROR_FAILED,
1301 _("Unknown error executing child process \"%s\""),
1302 argv[0]);
1303 break;
1306 goto cleanup_and_fail;
1309 /* Get child pid from intermediate child pipe. */
1310 if (intermediate_child)
1312 n_ints = 0;
1314 if (!read_ints (child_pid_report_pipe[0],
1315 buf, 1, &n_ints, error))
1316 goto cleanup_and_fail;
1318 if (n_ints < 1)
1320 g_set_error (error,
1321 G_SPAWN_ERROR,
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;
1327 else
1329 /* we have the child pid */
1330 pid = buf[0];
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]);
1338 if (child_pid)
1339 *child_pid = pid;
1341 if (standard_input)
1342 *standard_input = stdin_pipe[1];
1343 if (standard_output)
1344 *standard_output = stdout_pipe[0];
1345 if (standard_error)
1346 *standard_error = stderr_pipe[0];
1348 return TRUE;
1351 cleanup_and_fail:
1353 /* There was an error from the Child, reap the child to avoid it being
1354 a zombie.
1357 if (pid > 0)
1359 wait_failed:
1360 if (waitpid (pid, NULL, 0) < 0)
1362 if (errno == EINTR)
1363 goto wait_failed;
1364 else if (errno == ECHILD)
1365 ; /* do nothing, child already reaped */
1366 else
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]);
1383 return FALSE;
1386 static gboolean
1387 make_pipe (gint p[2],
1388 GError **error)
1390 if (pipe (p) < 0)
1392 g_set_error (error,
1393 G_SPAWN_ERROR,
1394 G_SPAWN_ERROR_FAILED,
1395 _("Failed to create pipe for communicating with child process (%s)"),
1396 g_strerror (errno));
1397 return FALSE;
1399 else
1400 return TRUE;
1403 /* Based on execvp from GNU C Library */
1405 static void
1406 script_execute (const gchar *file,
1407 gchar **argv,
1408 gchar **envp,
1409 gboolean search_path)
1411 /* Count the arguments. */
1412 int argc = 0;
1413 while (argv[argc])
1414 ++argc;
1416 /* Construct an argument list for the shell. */
1418 gchar **new_argv;
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;
1424 while (argc > 0)
1426 new_argv[argc + 1] = argv[argc];
1427 --argc;
1430 /* Execute the shell. */
1431 if (envp)
1432 execve (new_argv[0], new_argv, envp);
1433 else
1434 execv (new_argv[0], new_argv);
1436 g_free (new_argv);
1440 static gchar*
1441 my_strchrnul (const gchar *str, gchar c)
1443 gchar *p = (gchar*) str;
1444 while (*p && (*p != c))
1445 ++p;
1447 return p;
1450 static gint
1451 g_execute (const gchar *file,
1452 gchar **argv,
1453 gchar **envp,
1454 gboolean search_path)
1456 if (*file == '\0')
1458 /* We check the simple case first. */
1459 errno = ENOENT;
1460 return -1;
1463 if (!search_path || strchr (file, '/') != NULL)
1465 /* Don't search when it contains a slash. */
1466 if (envp)
1467 execve (file, argv, envp);
1468 else
1469 execv (file, argv);
1471 if (errno == ENOEXEC)
1472 script_execute (file, argv, envp, FALSE);
1474 else
1476 gboolean got_eacces = 0;
1477 const gchar *path, *p;
1478 gchar *name, *freeme;
1479 size_t len;
1480 size_t pathlen;
1482 path = g_getenv ("PATH");
1483 if (path == NULL)
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 */
1506 *name = '/';
1508 p = path;
1511 char *startp;
1513 path = p;
1514 p = my_strchrnul (path, ':');
1516 if (p == path)
1517 /* Two adjacent colons, or a colon at the beginning or the end
1518 * of `PATH' means to search the current directory.
1520 startp = name + 1;
1521 else
1522 startp = memcpy (name - (p - path), path, p - path);
1524 /* Try to execute this name. If it works, execv will not return. */
1525 if (envp)
1526 execve (startp, argv, envp);
1527 else
1528 execv (startp, argv);
1530 if (errno == ENOEXEC)
1531 script_execute (startp, argv, envp, search_path);
1533 switch (errno)
1535 case EACCES:
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.
1540 got_eacces = TRUE;
1542 /* FALL THRU */
1544 case ENOENT:
1545 #ifdef ESTALE
1546 case ESTALE:
1547 #endif
1548 #ifdef ENOTDIR
1549 case ENOTDIR:
1550 #endif
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
1553 * directory.
1555 break;
1557 default:
1558 /* Some other error means we found an executable file, but
1559 * something went wrong executing it; return the error to our
1560 * caller.
1562 g_free (freeme);
1563 return -1;
1566 while (*p++ != '\0');
1568 /* We tried every element and none of them worked. */
1569 if (got_eacces)
1570 /* At least one failure was due to permissions, so report that
1571 * error.
1573 errno = EACCES;
1575 g_free (freeme);
1578 /* Return the error from the last attempt (probably ENOENT). */
1579 return -1;
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.
1591 void
1592 g_spawn_close_pid (GPid pid)
1596 #define __G_SPAWN_C__
1597 #include "galiasdef.c"