Merge branch '1175-source-names' into 'master'
[glib.git] / glib / gspawn.c
blobd84433497a75a9f06d81b70c9f9012ec1625e561
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 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library 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 License
18 * along with this library; if not, see <http://www.gnu.org/licenses/>.
21 #include "config.h"
23 #include <sys/time.h>
24 #include <sys/types.h>
25 #include <sys/wait.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <string.h>
31 #include <stdlib.h> /* for fdwalk */
32 #include <dirent.h>
33 #include <spawn.h>
35 #ifdef HAVE_CRT_EXTERNS_H
36 #include <crt_externs.h> /* for _NSGetEnviron */
37 #endif
39 #ifdef HAVE_SYS_SELECT_H
40 #include <sys/select.h>
41 #endif /* HAVE_SYS_SELECT_H */
43 #ifdef HAVE_SYS_RESOURCE_H
44 #include <sys/resource.h>
45 #endif /* HAVE_SYS_RESOURCE_H */
47 #include "gspawn.h"
48 #include "gspawn-private.h"
49 #include "gthread.h"
50 #include "glib/gstdio.h"
52 #include "genviron.h"
53 #include "gmem.h"
54 #include "gshell.h"
55 #include "gstring.h"
56 #include "gstrfuncs.h"
57 #include "gtestutils.h"
58 #include "gutils.h"
59 #include "glibintl.h"
60 #include "glib-unix.h"
62 /* posix_spawn() is assumed the fastest way to spawn, but glibc's
63 * implementation was buggy before glibc 2.24, so avoid it on old versions.
65 #ifdef HAVE_POSIX_SPAWN
66 #ifdef __GLIBC__
68 #if __GLIBC_PREREQ(2,24)
69 #define POSIX_SPAWN_AVAILABLE
70 #endif
72 #else /* !__GLIBC__ */
73 /* Assume that all non-glibc posix_spawn implementations are fine. */
74 #define POSIX_SPAWN_AVAILABLE
75 #endif /* __GLIBC__ */
76 #endif /* HAVE_POSIX_SPAWN */
78 #ifdef HAVE__NSGETENVIRON
79 #define environ (*_NSGetEnviron())
80 #else
81 extern char **environ;
82 #endif
84 /**
85 * SECTION:spawn
86 * @Short_description: process launching
87 * @Title: Spawning Processes
89 * GLib supports spawning of processes with an API that is more
90 * convenient than the bare UNIX fork() and exec().
92 * The g_spawn family of functions has synchronous (g_spawn_sync())
93 * and asynchronous variants (g_spawn_async(), g_spawn_async_with_pipes()),
94 * as well as convenience variants that take a complete shell-like
95 * commandline (g_spawn_command_line_sync(), g_spawn_command_line_async()).
97 * See #GSubprocess in GIO for a higher-level API that provides
98 * stream interfaces for communication with child processes.
100 * An example of using g_spawn_async_with_pipes():
101 * |[<!-- language="C" -->
102 * const gchar * const argv[] = { "my-favourite-program", "--args", NULL };
103 * gint child_stdout, child_stderr;
104 * GPid child_pid;
105 * g_autoptr(GError) error = NULL;
107 * // Spawn child process.
108 * g_spawn_async_with_pipes (NULL, argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL,
109 * NULL, &child_pid, NULL, &child_stdout,
110 * &child_stderr, &error);
111 * if (error != NULL)
113 * g_error ("Spawning child failed: %s", error->message);
114 * return;
117 * // Add a child watch function which will be called when the child process
118 * // exits.
119 * g_child_watch_add (child_pid, child_watch_cb, NULL);
121 * // You could watch for output on @child_stdout and @child_stderr using
122 * // #GUnixInputStream or #GIOChannel here.
124 * static void
125 * child_watch_cb (GPid pid,
126 * gint status,
127 * gpointer user_data)
129 * g_message ("Child %" G_PID_FORMAT " exited %s", pid,
130 * g_spawn_check_exit_status (status, NULL) ? "normally" : "abnormally");
132 * // Free any resources associated with the child here, such as I/O channels
133 * // on its stdout and stderr FDs. If you have no code to put in the
134 * // child_watch_cb() callback, you can remove it and the g_child_watch_add()
135 * // call, but you must also remove the G_SPAWN_DO_NOT_REAP_CHILD flag,
136 * // otherwise the child process will stay around as a zombie until this
137 * // process exits.
139 * g_spawn_close_pid (pid);
141 * ]|
146 static gint g_execute (const gchar *file,
147 gchar **argv,
148 gchar **envp,
149 gboolean search_path,
150 gboolean search_path_from_envp);
152 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
153 const gchar *working_directory,
154 gchar **argv,
155 gchar **envp,
156 gboolean close_descriptors,
157 gboolean search_path,
158 gboolean search_path_from_envp,
159 gboolean stdout_to_null,
160 gboolean stderr_to_null,
161 gboolean child_inherits_stdin,
162 gboolean file_and_argv_zero,
163 gboolean cloexec_pipes,
164 GSpawnChildSetupFunc child_setup,
165 gpointer user_data,
166 GPid *child_pid,
167 gint *standard_input,
168 gint *standard_output,
169 gint *standard_error,
170 GError **error);
172 static gboolean fork_exec_with_fds (gboolean intermediate_child,
173 const gchar *working_directory,
174 gchar **argv,
175 gchar **envp,
176 gboolean close_descriptors,
177 gboolean search_path,
178 gboolean search_path_from_envp,
179 gboolean stdout_to_null,
180 gboolean stderr_to_null,
181 gboolean child_inherits_stdin,
182 gboolean file_and_argv_zero,
183 gboolean cloexec_pipes,
184 GSpawnChildSetupFunc child_setup,
185 gpointer user_data,
186 GPid *child_pid,
187 gint *child_close_fds,
188 gint stdin_fd,
189 gint stdout_fd,
190 gint stderr_fd,
191 GError **error);
193 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
194 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
197 * g_spawn_async:
198 * @working_directory: (type filename) (nullable): child's current working
199 * directory, or %NULL to inherit parent's
200 * @argv: (array zero-terminated=1) (element-type filename):
201 * child's argument vector
202 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
203 * child's environment, or %NULL to inherit parent's
204 * @flags: flags from #GSpawnFlags
205 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
206 * @user_data: (closure): user data for @child_setup
207 * @child_pid: (out) (optional): return location for child process reference, or %NULL
208 * @error: return location for error
210 * See g_spawn_async_with_pipes() for a full description; this function
211 * simply calls the g_spawn_async_with_pipes() without any pipes.
213 * You should call g_spawn_close_pid() on the returned child process
214 * reference when you don't need it any more.
216 * If you are writing a GTK+ application, and the program you are spawning is a
217 * graphical application too, then to ensure that the spawned program opens its
218 * windows on the right screen, you may want to use #GdkAppLaunchContext,
219 * #GAppLaunchContext, or set the %DISPLAY environment variable.
221 * Note that the returned @child_pid on Windows is a handle to the child
222 * process and not its identifier. Process handles and process identifiers
223 * are different concepts on Windows.
225 * Returns: %TRUE on success, %FALSE if error is set
227 gboolean
228 g_spawn_async (const gchar *working_directory,
229 gchar **argv,
230 gchar **envp,
231 GSpawnFlags flags,
232 GSpawnChildSetupFunc child_setup,
233 gpointer user_data,
234 GPid *child_pid,
235 GError **error)
237 g_return_val_if_fail (argv != NULL, FALSE);
239 return g_spawn_async_with_pipes (working_directory,
240 argv, envp,
241 flags,
242 child_setup,
243 user_data,
244 child_pid,
245 NULL, NULL, NULL,
246 error);
249 /* Avoids a danger in threaded situations (calling close()
250 * on a file descriptor twice, and another thread has
251 * re-opened it since the first close)
253 static void
254 close_and_invalidate (gint *fd)
256 if (*fd < 0)
257 return;
258 else
260 (void) g_close (*fd, NULL);
261 *fd = -1;
265 /* Some versions of OS X define READ_OK in public headers */
266 #undef READ_OK
268 typedef enum
270 READ_FAILED = 0, /* FALSE */
271 READ_OK,
272 READ_EOF
273 } ReadResult;
275 static ReadResult
276 read_data (GString *str,
277 gint fd,
278 GError **error)
280 gssize bytes;
281 gchar buf[4096];
283 again:
284 bytes = read (fd, buf, 4096);
286 if (bytes == 0)
287 return READ_EOF;
288 else if (bytes > 0)
290 g_string_append_len (str, buf, bytes);
291 return READ_OK;
293 else if (errno == EINTR)
294 goto again;
295 else
297 int errsv = errno;
299 g_set_error (error,
300 G_SPAWN_ERROR,
301 G_SPAWN_ERROR_READ,
302 _("Failed to read data from child process (%s)"),
303 g_strerror (errsv));
305 return READ_FAILED;
310 * g_spawn_sync:
311 * @working_directory: (type filename) (nullable): child's current working
312 * directory, or %NULL to inherit parent's
313 * @argv: (array zero-terminated=1) (element-type filename):
314 * child's argument vector
315 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
316 * child's environment, or %NULL to inherit parent's
317 * @flags: flags from #GSpawnFlags
318 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
319 * @user_data: (closure): user data for @child_setup
320 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output, or %NULL
321 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child error messages, or %NULL
322 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid(), or %NULL
323 * @error: return location for error, or %NULL
325 * Executes a child synchronously (waits for the child to exit before returning).
326 * All output from the child is stored in @standard_output and @standard_error,
327 * if those parameters are non-%NULL. Note that you must set the
328 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
329 * passing %NULL for @standard_output and @standard_error.
331 * If @exit_status is non-%NULL, the platform-specific exit status of
332 * the child is stored there; see the documentation of
333 * g_spawn_check_exit_status() for how to use and interpret this.
334 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
335 * @flags, and on POSIX platforms, the same restrictions as for
336 * g_child_watch_source_new() apply.
338 * If an error occurs, no data is returned in @standard_output,
339 * @standard_error, or @exit_status.
341 * This function calls g_spawn_async_with_pipes() internally; see that
342 * function for full details on the other parameters and details on
343 * how these functions work on Windows.
345 * Returns: %TRUE on success, %FALSE if an error was set
347 gboolean
348 g_spawn_sync (const gchar *working_directory,
349 gchar **argv,
350 gchar **envp,
351 GSpawnFlags flags,
352 GSpawnChildSetupFunc child_setup,
353 gpointer user_data,
354 gchar **standard_output,
355 gchar **standard_error,
356 gint *exit_status,
357 GError **error)
359 gint outpipe = -1;
360 gint errpipe = -1;
361 GPid pid;
362 fd_set fds;
363 gint ret;
364 GString *outstr = NULL;
365 GString *errstr = NULL;
366 gboolean failed;
367 gint status;
369 g_return_val_if_fail (argv != NULL, FALSE);
370 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
371 g_return_val_if_fail (standard_output == NULL ||
372 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
373 g_return_val_if_fail (standard_error == NULL ||
374 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
376 /* Just to ensure segfaults if callers try to use
377 * these when an error is reported.
379 if (standard_output)
380 *standard_output = NULL;
382 if (standard_error)
383 *standard_error = NULL;
385 if (!fork_exec_with_pipes (FALSE,
386 working_directory,
387 argv,
388 envp,
389 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
390 (flags & G_SPAWN_SEARCH_PATH) != 0,
391 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
392 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
393 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
394 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
395 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
396 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
397 child_setup,
398 user_data,
399 &pid,
400 NULL,
401 standard_output ? &outpipe : NULL,
402 standard_error ? &errpipe : NULL,
403 error))
404 return FALSE;
406 /* Read data from child. */
408 failed = FALSE;
410 if (outpipe >= 0)
412 outstr = g_string_new (NULL);
415 if (errpipe >= 0)
417 errstr = g_string_new (NULL);
420 /* Read data until we get EOF on both pipes. */
421 while (!failed &&
422 (outpipe >= 0 ||
423 errpipe >= 0))
425 ret = 0;
427 FD_ZERO (&fds);
428 if (outpipe >= 0)
429 FD_SET (outpipe, &fds);
430 if (errpipe >= 0)
431 FD_SET (errpipe, &fds);
433 ret = select (MAX (outpipe, errpipe) + 1,
434 &fds,
435 NULL, NULL,
436 NULL /* no timeout */);
438 if (ret < 0)
440 int errsv = errno;
442 if (errno == EINTR)
443 continue;
445 failed = TRUE;
447 g_set_error (error,
448 G_SPAWN_ERROR,
449 G_SPAWN_ERROR_READ,
450 _("Unexpected error in select() reading data from a child process (%s)"),
451 g_strerror (errsv));
453 break;
456 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
458 switch (read_data (outstr, outpipe, error))
460 case READ_FAILED:
461 failed = TRUE;
462 break;
463 case READ_EOF:
464 close_and_invalidate (&outpipe);
465 outpipe = -1;
466 break;
467 default:
468 break;
471 if (failed)
472 break;
475 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
477 switch (read_data (errstr, errpipe, error))
479 case READ_FAILED:
480 failed = TRUE;
481 break;
482 case READ_EOF:
483 close_and_invalidate (&errpipe);
484 errpipe = -1;
485 break;
486 default:
487 break;
490 if (failed)
491 break;
495 /* These should only be open still if we had an error. */
497 if (outpipe >= 0)
498 close_and_invalidate (&outpipe);
499 if (errpipe >= 0)
500 close_and_invalidate (&errpipe);
502 /* Wait for child to exit, even if we have
503 * an error pending.
505 again:
507 ret = waitpid (pid, &status, 0);
509 if (ret < 0)
511 if (errno == EINTR)
512 goto again;
513 else if (errno == ECHILD)
515 if (exit_status)
517 g_warning ("In call to g_spawn_sync(), exit status of a child process was requested but ECHILD was received by waitpid(). See the documentation of g_child_watch_source_new() for possible causes.");
519 else
521 /* We don't need the exit status. */
524 else
526 if (!failed) /* avoid error pileups */
528 int errsv = errno;
530 failed = TRUE;
532 g_set_error (error,
533 G_SPAWN_ERROR,
534 G_SPAWN_ERROR_READ,
535 _("Unexpected error in waitpid() (%s)"),
536 g_strerror (errsv));
541 if (failed)
543 if (outstr)
544 g_string_free (outstr, TRUE);
545 if (errstr)
546 g_string_free (errstr, TRUE);
548 return FALSE;
550 else
552 if (exit_status)
553 *exit_status = status;
555 if (standard_output)
556 *standard_output = g_string_free (outstr, FALSE);
558 if (standard_error)
559 *standard_error = g_string_free (errstr, FALSE);
561 return TRUE;
566 * g_spawn_async_with_pipes:
567 * @working_directory: (type filename) (nullable): child's current working
568 * directory, or %NULL to inherit parent's, in the GLib file name encoding
569 * @argv: (array zero-terminated=1) (element-type filename): child's argument
570 * vector, in the GLib file name encoding
571 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
572 * child's environment, or %NULL to inherit parent's, in the GLib file
573 * name encoding
574 * @flags: flags from #GSpawnFlags
575 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
576 * @user_data: (closure): user data for @child_setup
577 * @child_pid: (out) (optional): return location for child process ID, or %NULL
578 * @standard_input: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
579 * @standard_output: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
580 * @standard_error: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
581 * @error: return location for error
583 * Executes a child program asynchronously (your program will not
584 * block waiting for the child to exit). The child program is
585 * specified by the only argument that must be provided, @argv.
586 * @argv should be a %NULL-terminated array of strings, to be passed
587 * as the argument vector for the child. The first string in @argv
588 * is of course the name of the program to execute. By default, the
589 * name of the program must be a full path. If @flags contains the
590 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is
591 * used to search for the executable. If @flags contains the
592 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from
593 * @envp is used to search for the executable. If both the
594 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags
595 * are set, the `PATH` variable from @envp takes precedence over
596 * the environment variable.
598 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
599 * used, then the program will be run from the current directory (or
600 * @working_directory, if specified); this might be unexpected or even
601 * dangerous in some cases when the current directory is world-writable.
603 * On Windows, note that all the string or string vector arguments to
604 * this function and the other g_spawn*() functions are in UTF-8, the
605 * GLib file name encoding. Unicode characters that are not part of
606 * the system codepage passed in these arguments will be correctly
607 * available in the spawned program only if it uses wide character API
608 * to retrieve its command line. For C programs built with Microsoft's
609 * tools it is enough to make the program have a wmain() instead of
610 * main(). wmain() has a wide character argument vector as parameter.
612 * At least currently, mingw doesn't support wmain(), so if you use
613 * mingw to develop the spawned program, it should call
614 * g_win32_get_command_line() to get arguments in UTF-8.
616 * On Windows the low-level child process creation API CreateProcess()
617 * doesn't use argument vectors, but a command line. The C runtime
618 * library's spawn*() family of functions (which g_spawn_async_with_pipes()
619 * eventually calls) paste the argument vector elements together into
620 * a command line, and the C runtime startup code does a corresponding
621 * reconstruction of an argument vector from the command line, to be
622 * passed to main(). Complications arise when you have argument vector
623 * elements that contain spaces of double quotes. The spawn*() functions
624 * don't do any quoting or escaping, but on the other hand the startup
625 * code does do unquoting and unescaping in order to enable receiving
626 * arguments with embedded spaces or double quotes. To work around this
627 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
628 * argument vector elements that need it before calling the C runtime
629 * spawn() function.
631 * The returned @child_pid on Windows is a handle to the child
632 * process, not its identifier. Process handles and process
633 * identifiers are different concepts on Windows.
635 * @envp is a %NULL-terminated array of strings, where each string
636 * has the form `KEY=VALUE`. This will become the child's environment.
637 * If @envp is %NULL, the child inherits its parent's environment.
639 * @flags should be the bitwise OR of any flags you want to affect the
640 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
641 * child will not automatically be reaped; you must use a child watch
642 * (g_child_watch_add()) to be notified about the death of the child process,
643 * otherwise it will stay around as a zombie process until this process exits.
644 * Eventually you must call g_spawn_close_pid() on the @child_pid, in order to
645 * free resources which may be associated with the child process. (On Unix,
646 * using a child watch is equivalent to calling waitpid() or handling
647 * the %SIGCHLD signal manually. On Windows, calling g_spawn_close_pid()
648 * is equivalent to calling CloseHandle() on the process handle returned
649 * in @child_pid). See g_child_watch_add().
651 * Open UNIX file descriptors marked as `FD_CLOEXEC` will be automatically
652 * closed in the child process. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that
653 * other open file descriptors will be inherited by the child; otherwise all
654 * descriptors except stdin/stdout/stderr will be closed before calling exec()
655 * in the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
656 * absolute path, it will be looked for in the `PATH` environment
657 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
658 * absolute path, it will be looked for in the `PATH` variable from
659 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
660 * are used, the value from @envp takes precedence over the environment.
661 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
662 * will be discarded, instead of going to the same location as the parent's
663 * standard output. If you use this flag, @standard_output must be %NULL.
664 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
665 * will be discarded, instead of going to the same location as the parent's
666 * standard error. If you use this flag, @standard_error must be %NULL.
667 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
668 * standard input (by default, the child's standard input is attached to
669 * `/dev/null`). If you use this flag, @standard_input must be %NULL.
670 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
671 * the file to execute, while the remaining elements are the actual
672 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
673 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
675 * @child_setup and @user_data are a function and user data. On POSIX
676 * platforms, the function is called in the child after GLib has
677 * performed all the setup it plans to perform (including creating
678 * pipes, closing file descriptors, etc.) but before calling exec().
679 * That is, @child_setup is called just before calling exec() in the
680 * child. Obviously actions taken in this function will only affect
681 * the child, not the parent.
683 * On Windows, there is no separate fork() and exec() functionality.
684 * Child processes are created and run with a single API call,
685 * CreateProcess(). There is no sensible thing @child_setup
686 * could be used for on Windows so it is ignored and not called.
688 * If non-%NULL, @child_pid will on Unix be filled with the child's
689 * process ID. You can use the process ID to send signals to the child,
690 * or to use g_child_watch_add() (or waitpid()) if you specified the
691 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
692 * filled with a handle to the child process only if you specified the
693 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
694 * process using the Win32 API, for example wait for its termination
695 * with the WaitFor*() functions, or examine its exit code with
696 * GetExitCodeProcess(). You should close the handle with CloseHandle()
697 * or g_spawn_close_pid() when you no longer need it.
699 * If non-%NULL, the @standard_input, @standard_output, @standard_error
700 * locations will be filled with file descriptors for writing to the child's
701 * standard input or reading from its standard output or standard error.
702 * The caller of g_spawn_async_with_pipes() must close these file descriptors
703 * when they are no longer in use. If these parameters are %NULL, the
704 * corresponding pipe won't be created.
706 * If @standard_input is %NULL, the child's standard input is attached to
707 * `/dev/null` unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
709 * If @standard_error is NULL, the child's standard error goes to the same
710 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
711 * is set.
713 * If @standard_output is NULL, the child's standard output goes to the same
714 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
715 * is set.
717 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
718 * If an error is set, the function returns %FALSE. Errors are reported
719 * even if they occur in the child (for example if the executable in
720 * @argv[0] is not found). Typically the `message` field of returned
721 * errors should be displayed to users. Possible errors are those from
722 * the #G_SPAWN_ERROR domain.
724 * If an error occurs, @child_pid, @standard_input, @standard_output,
725 * and @standard_error will not be filled with valid values.
727 * If @child_pid is not %NULL and an error does not occur then the returned
728 * process reference must be closed using g_spawn_close_pid().
730 * On modern UNIX platforms, GLib can use an efficient process launching
731 * codepath driven internally by posix_spawn(). This has the advantage of
732 * avoiding the fork-time performance costs of cloning the parent process
733 * address space, and avoiding associated memory overcommit checks that are
734 * not relevant in the context of immediately executing a distinct process.
735 * This optimized codepath will be used provided that the following conditions
736 * are met:
738 * 1. %G_SPAWN_DO_NOT_REAP_CHILD is set
739 * 2. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN is set
740 * 3. %G_SPAWN_SEARCH_PATH_FROM_ENVP is not set
741 * 4. @working_directory is %NULL
742 * 5. @child_setup is %NULL
743 * 6. The program is of a recognised binary format, or has a shebang. Otherwise, GLib will have to execute the program through the shell, which is not done using the optimized codepath.
745 * If you are writing a GTK+ application, and the program you are spawning is a
746 * graphical application too, then to ensure that the spawned program opens its
747 * windows on the right screen, you may want to use #GdkAppLaunchContext,
748 * #GAppLaunchContext, or set the %DISPLAY environment variable.
750 * Returns: %TRUE on success, %FALSE if an error was set
752 gboolean
753 g_spawn_async_with_pipes (const gchar *working_directory,
754 gchar **argv,
755 gchar **envp,
756 GSpawnFlags flags,
757 GSpawnChildSetupFunc child_setup,
758 gpointer user_data,
759 GPid *child_pid,
760 gint *standard_input,
761 gint *standard_output,
762 gint *standard_error,
763 GError **error)
765 g_return_val_if_fail (argv != NULL, FALSE);
766 g_return_val_if_fail (standard_output == NULL ||
767 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
768 g_return_val_if_fail (standard_error == NULL ||
769 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
770 /* can't inherit stdin if we have an input pipe. */
771 g_return_val_if_fail (standard_input == NULL ||
772 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
774 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
775 working_directory,
776 argv,
777 envp,
778 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
779 (flags & G_SPAWN_SEARCH_PATH) != 0,
780 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
781 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
782 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
783 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
784 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
785 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
786 child_setup,
787 user_data,
788 child_pid,
789 standard_input,
790 standard_output,
791 standard_error,
792 error);
796 * g_spawn_async_with_fds:
797 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
798 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
799 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
800 * @flags: flags from #GSpawnFlags
801 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
802 * @user_data: (closure): user data for @child_setup
803 * @child_pid: (out) (optional): return location for child process ID, or %NULL
804 * @stdin_fd: file descriptor to use for child's stdin, or -1
805 * @stdout_fd: file descriptor to use for child's stdout, or -1
806 * @stderr_fd: file descriptor to use for child's stderr, or -1
807 * @error: return location for error
809 * Identical to g_spawn_async_with_pipes() but instead of
810 * creating pipes for the stdin/stdout/stderr, you can pass existing
811 * file descriptors into this function through the @stdin_fd,
812 * @stdout_fd and @stderr_fd parameters. The following @flags
813 * also have their behaviour slightly tweaked as a result:
815 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
816 * will be discarded, instead of going to the same location as the parent's
817 * standard output. If you use this flag, @standard_output must be -1.
818 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
819 * will be discarded, instead of going to the same location as the parent's
820 * standard error. If you use this flag, @standard_error must be -1.
821 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
822 * standard input (by default, the child's standard input is attached to
823 * /dev/null). If you use this flag, @standard_input must be -1.
825 * It is valid to pass the same fd in multiple parameters (e.g. you can pass
826 * a single fd for both stdout and stderr).
828 * Returns: %TRUE on success, %FALSE if an error was set
830 * Since: 2.58
832 gboolean
833 g_spawn_async_with_fds (const gchar *working_directory,
834 gchar **argv,
835 gchar **envp,
836 GSpawnFlags flags,
837 GSpawnChildSetupFunc child_setup,
838 gpointer user_data,
839 GPid *child_pid,
840 gint stdin_fd,
841 gint stdout_fd,
842 gint stderr_fd,
843 GError **error)
845 g_return_val_if_fail (argv != NULL, FALSE);
846 g_return_val_if_fail (stdout_fd == -1 ||
847 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
848 g_return_val_if_fail (stderr_fd == -1 ||
849 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
850 /* can't inherit stdin if we have an input pipe. */
851 g_return_val_if_fail (stdin_fd == -1 ||
852 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
854 return fork_exec_with_fds (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
855 working_directory,
856 argv,
857 envp,
858 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
859 (flags & G_SPAWN_SEARCH_PATH) != 0,
860 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
861 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
862 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
863 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
864 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
865 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
866 child_setup,
867 user_data,
868 child_pid,
869 NULL,
870 stdin_fd,
871 stdout_fd,
872 stderr_fd,
873 error);
877 * g_spawn_command_line_sync:
878 * @command_line: (type filename): a command line
879 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output
880 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child errors
881 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid()
882 * @error: return location for errors
884 * A simple version of g_spawn_sync() with little-used parameters
885 * removed, taking a command line instead of an argument vector. See
886 * g_spawn_sync() for full details. @command_line will be parsed by
887 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
888 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
889 * implications, so consider using g_spawn_sync() directly if
890 * appropriate. Possible errors are those from g_spawn_sync() and those
891 * from g_shell_parse_argv().
893 * If @exit_status is non-%NULL, the platform-specific exit status of
894 * the child is stored there; see the documentation of
895 * g_spawn_check_exit_status() for how to use and interpret this.
897 * On Windows, please note the implications of g_shell_parse_argv()
898 * parsing @command_line. Parsing is done according to Unix shell rules, not
899 * Windows command interpreter rules.
900 * Space is a separator, and backslashes are
901 * special. Thus you cannot simply pass a @command_line containing
902 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
903 * the backslashes will be eaten, and the space will act as a
904 * separator. You need to enclose such paths with single quotes, like
905 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
907 * Returns: %TRUE on success, %FALSE if an error was set
909 gboolean
910 g_spawn_command_line_sync (const gchar *command_line,
911 gchar **standard_output,
912 gchar **standard_error,
913 gint *exit_status,
914 GError **error)
916 gboolean retval;
917 gchar **argv = NULL;
919 g_return_val_if_fail (command_line != NULL, FALSE);
921 if (!g_shell_parse_argv (command_line,
922 NULL, &argv,
923 error))
924 return FALSE;
926 retval = g_spawn_sync (NULL,
927 argv,
928 NULL,
929 G_SPAWN_SEARCH_PATH,
930 NULL,
931 NULL,
932 standard_output,
933 standard_error,
934 exit_status,
935 error);
936 g_strfreev (argv);
938 return retval;
942 * g_spawn_command_line_async:
943 * @command_line: (type filename): a command line
944 * @error: return location for errors
946 * A simple version of g_spawn_async() that parses a command line with
947 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
948 * command line in the background. Unlike g_spawn_async(), the
949 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
950 * that %G_SPAWN_SEARCH_PATH can have security implications, so
951 * consider using g_spawn_async() directly if appropriate. Possible
952 * errors are those from g_shell_parse_argv() and g_spawn_async().
954 * The same concerns on Windows apply as for g_spawn_command_line_sync().
956 * Returns: %TRUE on success, %FALSE if error is set
958 gboolean
959 g_spawn_command_line_async (const gchar *command_line,
960 GError **error)
962 gboolean retval;
963 gchar **argv = NULL;
965 g_return_val_if_fail (command_line != NULL, FALSE);
967 if (!g_shell_parse_argv (command_line,
968 NULL, &argv,
969 error))
970 return FALSE;
972 retval = g_spawn_async (NULL,
973 argv,
974 NULL,
975 G_SPAWN_SEARCH_PATH,
976 NULL,
977 NULL,
978 NULL,
979 error);
980 g_strfreev (argv);
982 return retval;
986 * g_spawn_check_exit_status:
987 * @exit_status: An exit code as returned from g_spawn_sync()
988 * @error: a #GError
990 * Set @error if @exit_status indicates the child exited abnormally
991 * (e.g. with a nonzero exit code, or via a fatal signal).
993 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
994 * exit status for subprocesses encoded in a platform-specific way.
995 * On Unix, this is guaranteed to be in the same format waitpid() returns,
996 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
998 * Prior to the introduction of this function in GLib 2.34, interpreting
999 * @exit_status required use of platform-specific APIs, which is problematic
1000 * for software using GLib as a cross-platform layer.
1002 * Additionally, many programs simply want to determine whether or not
1003 * the child exited successfully, and either propagate a #GError or
1004 * print a message to standard error. In that common case, this function
1005 * can be used. Note that the error message in @error will contain
1006 * human-readable information about the exit status.
1008 * The @domain and @code of @error have special semantics in the case
1009 * where the process has an "exit code", as opposed to being killed by
1010 * a signal. On Unix, this happens if WIFEXITED() would be true of
1011 * @exit_status. On Windows, it is always the case.
1013 * The special semantics are that the actual exit code will be the
1014 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
1015 * This allows you to differentiate between different exit codes.
1017 * If the process was terminated by some means other than an exit
1018 * status, the domain will be %G_SPAWN_ERROR, and the code will be
1019 * %G_SPAWN_ERROR_FAILED.
1021 * This function just offers convenience; you can of course also check
1022 * the available platform via a macro such as %G_OS_UNIX, and use
1023 * WIFEXITED() and WEXITSTATUS() on @exit_status directly. Do not attempt
1024 * to scan or parse the error message string; it may be translated and/or
1025 * change in future versions of GLib.
1027 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
1028 * @error will be set)
1030 * Since: 2.34
1032 gboolean
1033 g_spawn_check_exit_status (gint exit_status,
1034 GError **error)
1036 gboolean ret = FALSE;
1038 if (WIFEXITED (exit_status))
1040 if (WEXITSTATUS (exit_status) != 0)
1042 g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (exit_status),
1043 _("Child process exited with code %ld"),
1044 (long) WEXITSTATUS (exit_status));
1045 goto out;
1048 else if (WIFSIGNALED (exit_status))
1050 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1051 _("Child process killed by signal %ld"),
1052 (long) WTERMSIG (exit_status));
1053 goto out;
1055 else if (WIFSTOPPED (exit_status))
1057 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1058 _("Child process stopped by signal %ld"),
1059 (long) WSTOPSIG (exit_status));
1060 goto out;
1062 else
1064 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1065 _("Child process exited abnormally"));
1066 goto out;
1069 ret = TRUE;
1070 out:
1071 return ret;
1074 static gssize
1075 write_all (gint fd, gconstpointer vbuf, gsize to_write)
1077 gchar *buf = (gchar *) vbuf;
1079 while (to_write > 0)
1081 gssize count = write (fd, buf, to_write);
1082 if (count < 0)
1084 if (errno != EINTR)
1085 return FALSE;
1087 else
1089 to_write -= count;
1090 buf += count;
1094 return TRUE;
1097 G_GNUC_NORETURN
1098 static void
1099 write_err_and_exit (gint fd, gint msg)
1101 gint en = errno;
1103 write_all (fd, &msg, sizeof(msg));
1104 write_all (fd, &en, sizeof(en));
1106 _exit (1);
1109 static int
1110 set_cloexec (void *data, gint fd)
1112 if (fd >= GPOINTER_TO_INT (data))
1113 fcntl (fd, F_SETFD, FD_CLOEXEC);
1115 return 0;
1118 #ifndef HAVE_FDWALK
1119 static int
1120 fdwalk (int (*cb)(void *data, int fd), void *data)
1122 gint open_max;
1123 gint fd;
1124 gint res = 0;
1126 #ifdef HAVE_SYS_RESOURCE_H
1127 struct rlimit rl;
1128 #endif
1130 #ifdef __linux__
1131 DIR *d;
1133 if ((d = opendir("/proc/self/fd"))) {
1134 struct dirent *de;
1136 while ((de = readdir(d))) {
1137 glong l;
1138 gchar *e = NULL;
1140 if (de->d_name[0] == '.')
1141 continue;
1143 errno = 0;
1144 l = strtol(de->d_name, &e, 10);
1145 if (errno != 0 || !e || *e)
1146 continue;
1148 fd = (gint) l;
1150 if ((glong) fd != l)
1151 continue;
1153 if (fd == dirfd(d))
1154 continue;
1156 if ((res = cb (data, fd)) != 0)
1157 break;
1160 closedir(d);
1161 return res;
1164 /* If /proc is not mounted or not accessible we fall back to the old
1165 * rlimit trick */
1167 #endif
1169 #ifdef HAVE_SYS_RESOURCE_H
1171 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1172 open_max = rl.rlim_max;
1173 else
1174 #endif
1175 open_max = sysconf (_SC_OPEN_MAX);
1177 for (fd = 0; fd < open_max; fd++)
1178 if ((res = cb (data, fd)) != 0)
1179 break;
1181 return res;
1183 #endif
1185 static gint
1186 sane_dup2 (gint fd1, gint fd2)
1188 gint ret;
1190 retry:
1191 ret = dup2 (fd1, fd2);
1192 if (ret < 0 && errno == EINTR)
1193 goto retry;
1195 return ret;
1198 static gint
1199 sane_open (const char *path, gint mode)
1201 gint ret;
1203 retry:
1204 ret = open (path, mode);
1205 if (ret < 0 && errno == EINTR)
1206 goto retry;
1208 return ret;
1211 enum
1213 CHILD_CHDIR_FAILED,
1214 CHILD_EXEC_FAILED,
1215 CHILD_DUP2_FAILED,
1216 CHILD_FORK_FAILED
1219 static void
1220 do_exec (gint child_err_report_fd,
1221 gint stdin_fd,
1222 gint stdout_fd,
1223 gint stderr_fd,
1224 const gchar *working_directory,
1225 gchar **argv,
1226 gchar **envp,
1227 gboolean close_descriptors,
1228 gboolean search_path,
1229 gboolean search_path_from_envp,
1230 gboolean stdout_to_null,
1231 gboolean stderr_to_null,
1232 gboolean child_inherits_stdin,
1233 gboolean file_and_argv_zero,
1234 GSpawnChildSetupFunc child_setup,
1235 gpointer user_data)
1237 if (working_directory && chdir (working_directory) < 0)
1238 write_err_and_exit (child_err_report_fd,
1239 CHILD_CHDIR_FAILED);
1241 /* Close all file descriptors but stdin stdout and stderr as
1242 * soon as we exec. Note that this includes
1243 * child_err_report_fd, which keeps the parent from blocking
1244 * forever on the other end of that pipe.
1246 if (close_descriptors)
1248 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1250 else
1252 /* We need to do child_err_report_fd anyway */
1253 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1256 /* Redirect pipes as required */
1258 if (stdin_fd >= 0)
1260 /* dup2 can't actually fail here I don't think */
1262 if (sane_dup2 (stdin_fd, 0) < 0)
1263 write_err_and_exit (child_err_report_fd,
1264 CHILD_DUP2_FAILED);
1266 set_cloexec (GINT_TO_POINTER(0), stdin_fd);
1268 else if (!child_inherits_stdin)
1270 /* Keep process from blocking on a read of stdin */
1271 gint read_null = sane_open ("/dev/null", O_RDONLY);
1272 g_assert (read_null != -1);
1273 sane_dup2 (read_null, 0);
1274 close_and_invalidate (&read_null);
1277 if (stdout_fd >= 0)
1279 /* dup2 can't actually fail here I don't think */
1281 if (sane_dup2 (stdout_fd, 1) < 0)
1282 write_err_and_exit (child_err_report_fd,
1283 CHILD_DUP2_FAILED);
1285 set_cloexec (GINT_TO_POINTER(0), stdout_fd);
1287 else if (stdout_to_null)
1289 gint write_null = sane_open ("/dev/null", O_WRONLY);
1290 g_assert (write_null != -1);
1291 sane_dup2 (write_null, 1);
1292 close_and_invalidate (&write_null);
1295 if (stderr_fd >= 0)
1297 /* dup2 can't actually fail here I don't think */
1299 if (sane_dup2 (stderr_fd, 2) < 0)
1300 write_err_and_exit (child_err_report_fd,
1301 CHILD_DUP2_FAILED);
1303 set_cloexec (GINT_TO_POINTER(0), stderr_fd);
1305 else if (stderr_to_null)
1307 gint write_null = sane_open ("/dev/null", O_WRONLY);
1308 sane_dup2 (write_null, 2);
1309 close_and_invalidate (&write_null);
1312 /* Call user function just before we exec */
1313 if (child_setup)
1315 (* child_setup) (user_data);
1318 g_execute (argv[0],
1319 file_and_argv_zero ? argv + 1 : argv,
1320 envp, search_path, search_path_from_envp);
1322 /* Exec failed */
1323 write_err_and_exit (child_err_report_fd,
1324 CHILD_EXEC_FAILED);
1327 static gboolean
1328 read_ints (int fd,
1329 gint* buf,
1330 gint n_ints_in_buf,
1331 gint *n_ints_read,
1332 GError **error)
1334 gsize bytes = 0;
1336 while (TRUE)
1338 gssize chunk;
1340 if (bytes >= sizeof(gint)*2)
1341 break; /* give up, who knows what happened, should not be
1342 * possible.
1345 again:
1346 chunk = read (fd,
1347 ((gchar*)buf) + bytes,
1348 sizeof(gint) * n_ints_in_buf - bytes);
1349 if (chunk < 0 && errno == EINTR)
1350 goto again;
1352 if (chunk < 0)
1354 int errsv = errno;
1356 /* Some weird shit happened, bail out */
1357 g_set_error (error,
1358 G_SPAWN_ERROR,
1359 G_SPAWN_ERROR_FAILED,
1360 _("Failed to read from child pipe (%s)"),
1361 g_strerror (errsv));
1363 return FALSE;
1365 else if (chunk == 0)
1366 break; /* EOF */
1367 else /* chunk > 0 */
1368 bytes += chunk;
1371 *n_ints_read = (gint)(bytes / sizeof(gint));
1373 return TRUE;
1376 #ifdef POSIX_SPAWN_AVAILABLE
1377 static gboolean
1378 do_posix_spawn (gchar **argv,
1379 gchar **envp,
1380 gboolean search_path,
1381 gboolean stdout_to_null,
1382 gboolean stderr_to_null,
1383 gboolean child_inherits_stdin,
1384 gboolean file_and_argv_zero,
1385 GPid *child_pid,
1386 gint *child_close_fds,
1387 gint stdin_fd,
1388 gint stdout_fd,
1389 gint stderr_fd)
1391 pid_t pid;
1392 gchar **argv_pass;
1393 posix_spawnattr_t attr;
1394 posix_spawn_file_actions_t file_actions;
1395 gint parent_close_fds[3];
1396 gint num_parent_close_fds = 0;
1397 GSList *child_close = NULL;
1398 GSList *elem;
1399 sigset_t mask;
1400 int i, r;
1402 if (*argv[0] == '\0')
1404 /* We check the simple case first. */
1405 return ENOENT;
1408 r = posix_spawnattr_init (&attr);
1409 if (r != 0)
1410 return r;
1412 if (child_close_fds)
1414 int i = -1;
1415 while (child_close_fds[++i] != -1)
1416 child_close = g_slist_prepend (child_close,
1417 GINT_TO_POINTER (child_close_fds[i]));
1420 r = posix_spawnattr_setflags (&attr, POSIX_SPAWN_SETSIGDEF);
1421 if (r != 0)
1422 goto out_free_spawnattr;
1424 /* Reset some signal handlers that we may use */
1425 sigemptyset (&mask);
1426 sigaddset (&mask, SIGCHLD);
1427 sigaddset (&mask, SIGINT);
1428 sigaddset (&mask, SIGTERM);
1429 sigaddset (&mask, SIGHUP);
1431 r = posix_spawnattr_setsigdefault (&attr, &mask);
1432 if (r != 0)
1433 goto out_free_spawnattr;
1435 r = posix_spawn_file_actions_init (&file_actions);
1436 if (r != 0)
1437 goto out_free_spawnattr;
1439 /* Redirect pipes as required */
1441 if (stdin_fd >= 0)
1443 r = posix_spawn_file_actions_adddup2 (&file_actions, stdin_fd, 0);
1444 if (r != 0)
1445 goto out_close_fds;
1447 if (!g_slist_find (child_close, GINT_TO_POINTER (stdin_fd)))
1448 child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stdin_fd));
1450 else if (!child_inherits_stdin)
1452 /* Keep process from blocking on a read of stdin */
1453 gint read_null = sane_open ("/dev/null", O_RDONLY | O_CLOEXEC);
1454 g_assert (read_null != -1);
1455 parent_close_fds[num_parent_close_fds++] = read_null;
1457 r = posix_spawn_file_actions_adddup2 (&file_actions, read_null, 0);
1458 if (r != 0)
1459 goto out_close_fds;
1462 if (stdout_fd >= 0)
1464 r = posix_spawn_file_actions_adddup2 (&file_actions, stdout_fd, 1);
1465 if (r != 0)
1466 goto out_close_fds;
1468 if (!g_slist_find (child_close, GINT_TO_POINTER (stdout_fd)))
1469 child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stdout_fd));
1471 else if (stdout_to_null)
1473 gint write_null = sane_open ("/dev/null", O_WRONLY | O_CLOEXEC);
1474 g_assert (write_null != -1);
1475 parent_close_fds[num_parent_close_fds++] = write_null;
1477 r = posix_spawn_file_actions_adddup2 (&file_actions, write_null, 1);
1478 if (r != 0)
1479 goto out_close_fds;
1482 if (stderr_fd >= 0)
1484 r = posix_spawn_file_actions_adddup2 (&file_actions, stderr_fd, 2);
1485 if (r != 0)
1486 goto out_close_fds;
1488 if (!g_slist_find (child_close, GINT_TO_POINTER (stderr_fd)))
1489 child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stderr_fd));
1491 else if (stderr_to_null)
1493 gint write_null = sane_open ("/dev/null", O_WRONLY | O_CLOEXEC);
1494 g_assert (write_null != -1);
1495 parent_close_fds[num_parent_close_fds++] = write_null;
1497 r = posix_spawn_file_actions_adddup2 (&file_actions, write_null, 2);
1498 if (r != 0)
1499 goto out_close_fds;
1502 /* Intentionally close the fds in the child as the last file action,
1503 * having been careful not to add the same fd to this list twice.
1505 * This is important to allow (e.g.) for the same fd to be passed as stdout
1506 * and stderr (we must not close it before we have dupped it in both places,
1507 * and we must not attempt to close it twice).
1509 for (elem = child_close; elem != NULL; elem = elem->next)
1511 r = posix_spawn_file_actions_addclose (&file_actions,
1512 GPOINTER_TO_INT (elem->data));
1513 if (r != 0)
1514 goto out_close_fds;
1517 argv_pass = file_and_argv_zero ? argv + 1 : argv;
1518 if (envp == NULL)
1519 envp = environ;
1521 /* Don't search when it contains a slash. */
1522 if (!search_path || strchr (argv[0], '/') != NULL)
1523 r = posix_spawn (&pid, argv[0], &file_actions, &attr, argv_pass, envp);
1524 else
1525 r = posix_spawnp (&pid, argv[0], &file_actions, &attr, argv_pass, envp);
1527 if (r == 0 && child_pid != NULL)
1528 *child_pid = pid;
1530 out_close_fds:
1531 for (i = 0; i < num_parent_close_fds; i++)
1532 close_and_invalidate (&parent_close_fds [i]);
1534 posix_spawn_file_actions_destroy (&file_actions);
1535 out_free_spawnattr:
1536 posix_spawnattr_destroy (&attr);
1537 g_slist_free (child_close);
1539 return r;
1541 #endif /* POSIX_SPAWN_AVAILABLE */
1543 static gboolean
1544 fork_exec_with_fds (gboolean intermediate_child,
1545 const gchar *working_directory,
1546 gchar **argv,
1547 gchar **envp,
1548 gboolean close_descriptors,
1549 gboolean search_path,
1550 gboolean search_path_from_envp,
1551 gboolean stdout_to_null,
1552 gboolean stderr_to_null,
1553 gboolean child_inherits_stdin,
1554 gboolean file_and_argv_zero,
1555 gboolean cloexec_pipes,
1556 GSpawnChildSetupFunc child_setup,
1557 gpointer user_data,
1558 GPid *child_pid,
1559 gint *child_close_fds,
1560 gint stdin_fd,
1561 gint stdout_fd,
1562 gint stderr_fd,
1563 GError **error)
1565 GPid pid = -1;
1566 gint child_err_report_pipe[2] = { -1, -1 };
1567 gint child_pid_report_pipe[2] = { -1, -1 };
1568 guint pipe_flags = cloexec_pipes ? FD_CLOEXEC : 0;
1569 gint status;
1571 #ifdef POSIX_SPAWN_AVAILABLE
1572 if (!intermediate_child && working_directory == NULL && !close_descriptors &&
1573 !search_path_from_envp && child_setup == NULL)
1575 g_debug ("Launching with posix_spawn");
1576 status = do_posix_spawn (argv,
1577 envp,
1578 search_path,
1579 stdout_to_null,
1580 stderr_to_null,
1581 child_inherits_stdin,
1582 file_and_argv_zero,
1583 child_pid,
1584 child_close_fds,
1585 stdin_fd,
1586 stdout_fd,
1587 stderr_fd);
1588 if (status == 0)
1589 return TRUE;
1591 if (status != ENOEXEC)
1593 g_set_error (error,
1594 G_SPAWN_ERROR,
1595 G_SPAWN_ERROR_FAILED,
1596 _("Failed to spawn child process “%s” (%s)"),
1597 argv[0],
1598 g_strerror (status));
1599 return FALSE;
1602 /* posix_spawn is not intended to support script execution. It does in
1603 * some situations on some glibc versions, but that will be fixed.
1604 * So if it fails with ENOEXEC, we fall through to the regular
1605 * gspawn codepath so that script execution can be attempted,
1606 * per standard gspawn behaviour. */
1607 g_debug ("posix_spawn failed (ENOEXEC), fall back to regular gspawn");
1609 else
1611 g_debug ("posix_spawn avoided %s%s%s%s%s",
1612 !intermediate_child ? "" : "(automatic reaping requested) ",
1613 working_directory == NULL ? "" : "(workdir specified) ",
1614 !close_descriptors ? "" : "(fd close requested) ",
1615 !search_path_from_envp ? "" : "(using envp for search path) ",
1616 child_setup == NULL ? "" : "(child_setup specified) ");
1618 #endif /* POSIX_SPAWN_AVAILABLE */
1620 if (!g_unix_open_pipe (child_err_report_pipe, pipe_flags, error))
1621 return FALSE;
1623 if (intermediate_child && !g_unix_open_pipe (child_pid_report_pipe, pipe_flags, error))
1624 goto cleanup_and_fail;
1626 pid = fork ();
1628 if (pid < 0)
1630 int errsv = errno;
1632 g_set_error (error,
1633 G_SPAWN_ERROR,
1634 G_SPAWN_ERROR_FORK,
1635 _("Failed to fork (%s)"),
1636 g_strerror (errsv));
1638 goto cleanup_and_fail;
1640 else if (pid == 0)
1642 /* Immediate child. This may or may not be the child that
1643 * actually execs the new process.
1646 /* Reset some signal handlers that we may use */
1647 signal (SIGCHLD, SIG_DFL);
1648 signal (SIGINT, SIG_DFL);
1649 signal (SIGTERM, SIG_DFL);
1650 signal (SIGHUP, SIG_DFL);
1652 /* Be sure we crash if the parent exits
1653 * and we write to the err_report_pipe
1655 signal (SIGPIPE, SIG_DFL);
1657 /* Close the parent's end of the pipes;
1658 * not needed in the close_descriptors case,
1659 * though
1661 close_and_invalidate (&child_err_report_pipe[0]);
1662 close_and_invalidate (&child_pid_report_pipe[0]);
1663 if (child_close_fds != NULL)
1665 int i = -1;
1666 while (child_close_fds[++i] != -1)
1667 close_and_invalidate (&child_close_fds[i]);
1670 if (intermediate_child)
1672 /* We need to fork an intermediate child that launches the
1673 * final child. The purpose of the intermediate child
1674 * is to exit, so we can waitpid() it immediately.
1675 * Then the grandchild will not become a zombie.
1677 GPid grandchild_pid;
1679 grandchild_pid = fork ();
1681 if (grandchild_pid < 0)
1683 /* report -1 as child PID */
1684 write_all (child_pid_report_pipe[1], &grandchild_pid,
1685 sizeof(grandchild_pid));
1687 write_err_and_exit (child_err_report_pipe[1],
1688 CHILD_FORK_FAILED);
1690 else if (grandchild_pid == 0)
1692 close_and_invalidate (&child_pid_report_pipe[1]);
1693 do_exec (child_err_report_pipe[1],
1694 stdin_fd,
1695 stdout_fd,
1696 stderr_fd,
1697 working_directory,
1698 argv,
1699 envp,
1700 close_descriptors,
1701 search_path,
1702 search_path_from_envp,
1703 stdout_to_null,
1704 stderr_to_null,
1705 child_inherits_stdin,
1706 file_and_argv_zero,
1707 child_setup,
1708 user_data);
1710 else
1712 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1713 close_and_invalidate (&child_pid_report_pipe[1]);
1715 _exit (0);
1718 else
1720 /* Just run the child.
1723 do_exec (child_err_report_pipe[1],
1724 stdin_fd,
1725 stdout_fd,
1726 stderr_fd,
1727 working_directory,
1728 argv,
1729 envp,
1730 close_descriptors,
1731 search_path,
1732 search_path_from_envp,
1733 stdout_to_null,
1734 stderr_to_null,
1735 child_inherits_stdin,
1736 file_and_argv_zero,
1737 child_setup,
1738 user_data);
1741 else
1743 /* Parent */
1745 gint buf[2];
1746 gint n_ints = 0;
1748 /* Close the uncared-about ends of the pipes */
1749 close_and_invalidate (&child_err_report_pipe[1]);
1750 close_and_invalidate (&child_pid_report_pipe[1]);
1752 /* If we had an intermediate child, reap it */
1753 if (intermediate_child)
1755 wait_again:
1756 if (waitpid (pid, &status, 0) < 0)
1758 if (errno == EINTR)
1759 goto wait_again;
1760 else if (errno == ECHILD)
1761 ; /* do nothing, child already reaped */
1762 else
1763 g_warning ("waitpid() should not fail in "
1764 "'fork_exec_with_pipes'");
1769 if (!read_ints (child_err_report_pipe[0],
1770 buf, 2, &n_ints,
1771 error))
1772 goto cleanup_and_fail;
1774 if (n_ints >= 2)
1776 /* Error from the child. */
1778 switch (buf[0])
1780 case CHILD_CHDIR_FAILED:
1781 g_set_error (error,
1782 G_SPAWN_ERROR,
1783 G_SPAWN_ERROR_CHDIR,
1784 _("Failed to change to directory “%s” (%s)"),
1785 working_directory,
1786 g_strerror (buf[1]));
1788 break;
1790 case CHILD_EXEC_FAILED:
1791 g_set_error (error,
1792 G_SPAWN_ERROR,
1793 _g_spawn_exec_err_to_g_error (buf[1]),
1794 _("Failed to execute child process “%s” (%s)"),
1795 argv[0],
1796 g_strerror (buf[1]));
1798 break;
1800 case CHILD_DUP2_FAILED:
1801 g_set_error (error,
1802 G_SPAWN_ERROR,
1803 G_SPAWN_ERROR_FAILED,
1804 _("Failed to redirect output or input of child process (%s)"),
1805 g_strerror (buf[1]));
1807 break;
1809 case CHILD_FORK_FAILED:
1810 g_set_error (error,
1811 G_SPAWN_ERROR,
1812 G_SPAWN_ERROR_FORK,
1813 _("Failed to fork child process (%s)"),
1814 g_strerror (buf[1]));
1815 break;
1817 default:
1818 g_set_error (error,
1819 G_SPAWN_ERROR,
1820 G_SPAWN_ERROR_FAILED,
1821 _("Unknown error executing child process “%s”"),
1822 argv[0]);
1823 break;
1826 goto cleanup_and_fail;
1829 /* Get child pid from intermediate child pipe. */
1830 if (intermediate_child)
1832 n_ints = 0;
1834 if (!read_ints (child_pid_report_pipe[0],
1835 buf, 1, &n_ints, error))
1836 goto cleanup_and_fail;
1838 if (n_ints < 1)
1840 int errsv = errno;
1842 g_set_error (error,
1843 G_SPAWN_ERROR,
1844 G_SPAWN_ERROR_FAILED,
1845 _("Failed to read enough data from child pid pipe (%s)"),
1846 g_strerror (errsv));
1847 goto cleanup_and_fail;
1849 else
1851 /* we have the child pid */
1852 pid = buf[0];
1856 /* Success against all odds! return the information */
1857 close_and_invalidate (&child_err_report_pipe[0]);
1858 close_and_invalidate (&child_pid_report_pipe[0]);
1860 if (child_pid)
1861 *child_pid = pid;
1863 return TRUE;
1866 cleanup_and_fail:
1868 /* There was an error from the Child, reap the child to avoid it being
1869 a zombie.
1872 if (pid > 0)
1874 wait_failed:
1875 if (waitpid (pid, NULL, 0) < 0)
1877 if (errno == EINTR)
1878 goto wait_failed;
1879 else if (errno == ECHILD)
1880 ; /* do nothing, child already reaped */
1881 else
1882 g_warning ("waitpid() should not fail in "
1883 "'fork_exec_with_pipes'");
1887 close_and_invalidate (&child_err_report_pipe[0]);
1888 close_and_invalidate (&child_err_report_pipe[1]);
1889 close_and_invalidate (&child_pid_report_pipe[0]);
1890 close_and_invalidate (&child_pid_report_pipe[1]);
1892 return FALSE;
1895 static gboolean
1896 fork_exec_with_pipes (gboolean intermediate_child,
1897 const gchar *working_directory,
1898 gchar **argv,
1899 gchar **envp,
1900 gboolean close_descriptors,
1901 gboolean search_path,
1902 gboolean search_path_from_envp,
1903 gboolean stdout_to_null,
1904 gboolean stderr_to_null,
1905 gboolean child_inherits_stdin,
1906 gboolean file_and_argv_zero,
1907 gboolean cloexec_pipes,
1908 GSpawnChildSetupFunc child_setup,
1909 gpointer user_data,
1910 GPid *child_pid,
1911 gint *standard_input,
1912 gint *standard_output,
1913 gint *standard_error,
1914 GError **error)
1916 guint pipe_flags = cloexec_pipes ? FD_CLOEXEC : 0;
1917 gint stdin_pipe[2] = { -1, -1 };
1918 gint stdout_pipe[2] = { -1, -1 };
1919 gint stderr_pipe[2] = { -1, -1 };
1920 gint child_close_fds[4];
1921 gboolean ret;
1923 if (standard_input && !g_unix_open_pipe (stdin_pipe, pipe_flags, error))
1924 goto cleanup_and_fail;
1926 if (standard_output && !g_unix_open_pipe (stdout_pipe, pipe_flags, error))
1927 goto cleanup_and_fail;
1929 if (standard_error && !g_unix_open_pipe (stderr_pipe, FD_CLOEXEC, error))
1930 goto cleanup_and_fail;
1932 child_close_fds[0] = stdin_pipe[1];
1933 child_close_fds[1] = stdout_pipe[0];
1934 child_close_fds[2] = stderr_pipe[0];
1935 child_close_fds[3] = -1;
1937 ret = fork_exec_with_fds (intermediate_child,
1938 working_directory,
1939 argv,
1940 envp,
1941 close_descriptors,
1942 search_path,
1943 search_path_from_envp,
1944 stdout_to_null,
1945 stderr_to_null,
1946 child_inherits_stdin,
1947 file_and_argv_zero,
1948 pipe_flags,
1949 child_setup,
1950 user_data,
1951 child_pid,
1952 child_close_fds,
1953 stdin_pipe[0],
1954 stdout_pipe[1],
1955 stderr_pipe[1],
1956 error);
1957 if (!ret)
1958 goto cleanup_and_fail;
1960 /* Close the uncared-about ends of the pipes */
1961 close_and_invalidate (&stdin_pipe[0]);
1962 close_and_invalidate (&stdout_pipe[1]);
1963 close_and_invalidate (&stderr_pipe[1]);
1965 if (standard_input)
1966 *standard_input = stdin_pipe[1];
1968 if (standard_output)
1969 *standard_output = stdout_pipe[0];
1971 if (standard_error)
1972 *standard_error = stderr_pipe[0];
1974 return TRUE;
1976 cleanup_and_fail:
1977 close_and_invalidate (&stdin_pipe[0]);
1978 close_and_invalidate (&stdin_pipe[1]);
1979 close_and_invalidate (&stdout_pipe[0]);
1980 close_and_invalidate (&stdout_pipe[1]);
1981 close_and_invalidate (&stderr_pipe[0]);
1982 close_and_invalidate (&stderr_pipe[1]);
1984 return FALSE;
1987 /* Based on execvp from GNU C Library */
1989 static void
1990 script_execute (const gchar *file,
1991 gchar **argv,
1992 gchar **envp)
1994 /* Count the arguments. */
1995 int argc = 0;
1996 while (argv[argc])
1997 ++argc;
1999 /* Construct an argument list for the shell. */
2001 gchar **new_argv;
2003 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
2005 new_argv[0] = (char *) "/bin/sh";
2006 new_argv[1] = (char *) file;
2007 while (argc > 0)
2009 new_argv[argc + 1] = argv[argc];
2010 --argc;
2013 /* Execute the shell. */
2014 if (envp)
2015 execve (new_argv[0], new_argv, envp);
2016 else
2017 execv (new_argv[0], new_argv);
2019 g_free (new_argv);
2023 static gchar*
2024 my_strchrnul (const gchar *str, gchar c)
2026 gchar *p = (gchar*) str;
2027 while (*p && (*p != c))
2028 ++p;
2030 return p;
2033 static gint
2034 g_execute (const gchar *file,
2035 gchar **argv,
2036 gchar **envp,
2037 gboolean search_path,
2038 gboolean search_path_from_envp)
2040 if (*file == '\0')
2042 /* We check the simple case first. */
2043 errno = ENOENT;
2044 return -1;
2047 if (!(search_path || search_path_from_envp) || strchr (file, '/') != NULL)
2049 /* Don't search when it contains a slash. */
2050 if (envp)
2051 execve (file, argv, envp);
2052 else
2053 execv (file, argv);
2055 if (errno == ENOEXEC)
2056 script_execute (file, argv, envp);
2058 else
2060 gboolean got_eacces = 0;
2061 const gchar *path, *p;
2062 gchar *name, *freeme;
2063 gsize len;
2064 gsize pathlen;
2066 path = NULL;
2067 if (search_path_from_envp)
2068 path = g_environ_getenv (envp, "PATH");
2069 if (search_path && path == NULL)
2070 path = g_getenv ("PATH");
2072 if (path == NULL)
2074 /* There is no 'PATH' in the environment. The default
2075 * search path in libc is the current directory followed by
2076 * the path 'confstr' returns for '_CS_PATH'.
2079 /* In GLib we put . last, for security, and don't use the
2080 * unportable confstr(); UNIX98 does not actually specify
2081 * what to search if PATH is unset. POSIX may, dunno.
2084 path = "/bin:/usr/bin:.";
2087 len = strlen (file) + 1;
2088 pathlen = strlen (path);
2089 freeme = name = g_malloc (pathlen + len + 1);
2091 /* Copy the file name at the top, including '\0' */
2092 memcpy (name + pathlen + 1, file, len);
2093 name = name + pathlen;
2094 /* And add the slash before the filename */
2095 *name = '/';
2097 p = path;
2100 char *startp;
2102 path = p;
2103 p = my_strchrnul (path, ':');
2105 if (p == path)
2106 /* Two adjacent colons, or a colon at the beginning or the end
2107 * of 'PATH' means to search the current directory.
2109 startp = name + 1;
2110 else
2111 startp = memcpy (name - (p - path), path, p - path);
2113 /* Try to execute this name. If it works, execv will not return. */
2114 if (envp)
2115 execve (startp, argv, envp);
2116 else
2117 execv (startp, argv);
2119 if (errno == ENOEXEC)
2120 script_execute (startp, argv, envp);
2122 switch (errno)
2124 case EACCES:
2125 /* Record the we got a 'Permission denied' error. If we end
2126 * up finding no executable we can use, we want to diagnose
2127 * that we did find one but were denied access.
2129 got_eacces = TRUE;
2131 /* FALL THRU */
2133 case ENOENT:
2134 #ifdef ESTALE
2135 case ESTALE:
2136 #endif
2137 #ifdef ENOTDIR
2138 case ENOTDIR:
2139 #endif
2140 /* Those errors indicate the file is missing or not executable
2141 * by us, in which case we want to just try the next path
2142 * directory.
2144 break;
2146 case ENODEV:
2147 case ETIMEDOUT:
2148 /* Some strange filesystems like AFS return even
2149 * stranger error numbers. They cannot reasonably mean anything
2150 * else so ignore those, too.
2152 break;
2154 default:
2155 /* Some other error means we found an executable file, but
2156 * something went wrong executing it; return the error to our
2157 * caller.
2159 g_free (freeme);
2160 return -1;
2163 while (*p++ != '\0');
2165 /* We tried every element and none of them worked. */
2166 if (got_eacces)
2167 /* At least one failure was due to permissions, so report that
2168 * error.
2170 errno = EACCES;
2172 g_free (freeme);
2175 /* Return the error from the last attempt (probably ENOENT). */
2176 return -1;
2180 * g_spawn_close_pid:
2181 * @pid: The process reference to close
2183 * On some platforms, notably Windows, the #GPid type represents a resource
2184 * which must be closed to prevent resource leaking. g_spawn_close_pid()
2185 * is provided for this purpose. It should be used on all platforms, even
2186 * though it doesn't do anything under UNIX.
2188 void
2189 g_spawn_close_pid (GPid pid)