tests/date.c: include config.h to expose Vista+ macros
[glib.git] / glib / gspawn.c
blob89824d17681068defe9cc324ded8f3faf1964d3a
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>
34 #ifdef HAVE_SYS_SELECT_H
35 #include <sys/select.h>
36 #endif /* HAVE_SYS_SELECT_H */
38 #ifdef HAVE_SYS_RESOURCE_H
39 #include <sys/resource.h>
40 #endif /* HAVE_SYS_RESOURCE_H */
42 #include "gspawn.h"
43 #include "gthread.h"
44 #include "glib/gstdio.h"
46 #include "genviron.h"
47 #include "gmem.h"
48 #include "gshell.h"
49 #include "gstring.h"
50 #include "gstrfuncs.h"
51 #include "gtestutils.h"
52 #include "gutils.h"
53 #include "glibintl.h"
54 #include "glib-unix.h"
56 /**
57 * SECTION:spawn
58 * @Short_description: process launching
59 * @Title: Spawning Processes
61 * GLib supports spawning of processes with an API that is more
62 * convenient than the bare UNIX fork() and exec().
64 * The g_spawn family of functions has synchronous (g_spawn_sync())
65 * and asynchronous variants (g_spawn_async(), g_spawn_async_with_pipes()),
66 * as well as convenience variants that take a complete shell-like
67 * commandline (g_spawn_command_line_sync(), g_spawn_command_line_async()).
69 * See #GSubprocess in GIO for a higher-level API that provides
70 * stream interfaces for communication with child processes.
72 * An example of using g_spawn_async_with_pipes():
73 * |[<!-- language="C" -->
74 * const gchar * const argv[] = { "my-favourite-program", "--args", NULL };
75 * gint child_stdout, child_stderr;
76 * GPid child_pid;
77 * g_autoptr(GError) error = NULL;
79 * // Spawn child process.
80 * g_spawn_async_with_pipes (NULL, argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL,
81 * NULL, &child_pid, NULL, &child_stdout,
82 * &child_stderr, &error);
83 * if (error != NULL)
84 * {
85 * g_error ("Spawning child failed: %s", error->message);
86 * return;
87 * }
89 * // Add a child watch function which will be called when the child process
90 * // exits.
91 * g_child_watch_add (child_pid, child_watch_cb, NULL);
93 * // You could watch for output on @child_stdout and @child_stderr using
94 * // #GUnixInputStream or #GIOChannel here.
96 * static void
97 * child_watch_cb (GPid pid,
98 * gint status,
99 * gpointer user_data)
101 * g_message ("Child %" G_PID_FORMAT " exited %s", pid,
102 * g_spawn_check_exit_status (status, NULL) ? "normally" : "abnormally");
104 * // Free any resources associated with the child here, such as I/O channels
105 * // on its stdout and stderr FDs. If you have no code to put in the
106 * // child_watch_cb() callback, you can remove it and the g_child_watch_add()
107 * // call, but you must also remove the G_SPAWN_DO_NOT_REAP_CHILD flag,
108 * // otherwise the child process will stay around as a zombie until this
109 * // process exits.
111 * g_spawn_close_pid (pid);
113 * ]|
118 static gint g_execute (const gchar *file,
119 gchar **argv,
120 gchar **envp,
121 gboolean search_path,
122 gboolean search_path_from_envp);
124 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
125 const gchar *working_directory,
126 gchar **argv,
127 gchar **envp,
128 gboolean close_descriptors,
129 gboolean search_path,
130 gboolean search_path_from_envp,
131 gboolean stdout_to_null,
132 gboolean stderr_to_null,
133 gboolean child_inherits_stdin,
134 gboolean file_and_argv_zero,
135 gboolean cloexec_pipes,
136 GSpawnChildSetupFunc child_setup,
137 gpointer user_data,
138 GPid *child_pid,
139 gint *standard_input,
140 gint *standard_output,
141 gint *standard_error,
142 GError **error);
144 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
145 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
148 * g_spawn_async:
149 * @working_directory: (type filename) (nullable): child's current working
150 * directory, or %NULL to inherit parent's
151 * @argv: (array zero-terminated=1) (element-type filename):
152 * child's argument vector
153 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
154 * child's environment, or %NULL to inherit parent's
155 * @flags: flags from #GSpawnFlags
156 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
157 * @user_data: (closure): user data for @child_setup
158 * @child_pid: (out) (optional): return location for child process reference, or %NULL
159 * @error: return location for error
161 * See g_spawn_async_with_pipes() for a full description; this function
162 * simply calls the g_spawn_async_with_pipes() without any pipes.
164 * You should call g_spawn_close_pid() on the returned child process
165 * reference when you don't need it any more.
167 * If you are writing a GTK+ application, and the program you are spawning is a
168 * graphical application too, then to ensure that the spawned program opens its
169 * windows on the right screen, you may want to use #GdkAppLaunchContext,
170 * #GAppLaunchContext, or set the %DISPLAY environment variable.
172 * Note that the returned @child_pid on Windows is a handle to the child
173 * process and not its identifier. Process handles and process identifiers
174 * are different concepts on Windows.
176 * Returns: %TRUE on success, %FALSE if error is set
178 gboolean
179 g_spawn_async (const gchar *working_directory,
180 gchar **argv,
181 gchar **envp,
182 GSpawnFlags flags,
183 GSpawnChildSetupFunc child_setup,
184 gpointer user_data,
185 GPid *child_pid,
186 GError **error)
188 g_return_val_if_fail (argv != NULL, FALSE);
190 return g_spawn_async_with_pipes (working_directory,
191 argv, envp,
192 flags,
193 child_setup,
194 user_data,
195 child_pid,
196 NULL, NULL, NULL,
197 error);
200 /* Avoids a danger in threaded situations (calling close()
201 * on a file descriptor twice, and another thread has
202 * re-opened it since the first close)
204 static void
205 close_and_invalidate (gint *fd)
207 if (*fd < 0)
208 return;
209 else
211 (void) g_close (*fd, NULL);
212 *fd = -1;
216 /* Some versions of OS X define READ_OK in public headers */
217 #undef READ_OK
219 typedef enum
221 READ_FAILED = 0, /* FALSE */
222 READ_OK,
223 READ_EOF
224 } ReadResult;
226 static ReadResult
227 read_data (GString *str,
228 gint fd,
229 GError **error)
231 gssize bytes;
232 gchar buf[4096];
234 again:
235 bytes = read (fd, buf, 4096);
237 if (bytes == 0)
238 return READ_EOF;
239 else if (bytes > 0)
241 g_string_append_len (str, buf, bytes);
242 return READ_OK;
244 else if (errno == EINTR)
245 goto again;
246 else
248 int errsv = errno;
250 g_set_error (error,
251 G_SPAWN_ERROR,
252 G_SPAWN_ERROR_READ,
253 _("Failed to read data from child process (%s)"),
254 g_strerror (errsv));
256 return READ_FAILED;
261 * g_spawn_sync:
262 * @working_directory: (type filename) (nullable): child's current working
263 * directory, or %NULL to inherit parent's
264 * @argv: (array zero-terminated=1) (element-type filename):
265 * child's argument vector
266 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
267 * child's environment, or %NULL to inherit parent's
268 * @flags: flags from #GSpawnFlags
269 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
270 * @user_data: (closure): user data for @child_setup
271 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output, or %NULL
272 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child error messages, or %NULL
273 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid(), or %NULL
274 * @error: return location for error, or %NULL
276 * Executes a child synchronously (waits for the child to exit before returning).
277 * All output from the child is stored in @standard_output and @standard_error,
278 * if those parameters are non-%NULL. Note that you must set the
279 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
280 * passing %NULL for @standard_output and @standard_error.
282 * If @exit_status is non-%NULL, the platform-specific exit status of
283 * the child is stored there; see the documentation of
284 * g_spawn_check_exit_status() for how to use and interpret this.
285 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
286 * @flags, and on POSIX platforms, the same restrictions as for
287 * g_child_watch_source_new() apply.
289 * If an error occurs, no data is returned in @standard_output,
290 * @standard_error, or @exit_status.
292 * This function calls g_spawn_async_with_pipes() internally; see that
293 * function for full details on the other parameters and details on
294 * how these functions work on Windows.
296 * Returns: %TRUE on success, %FALSE if an error was set
298 gboolean
299 g_spawn_sync (const gchar *working_directory,
300 gchar **argv,
301 gchar **envp,
302 GSpawnFlags flags,
303 GSpawnChildSetupFunc child_setup,
304 gpointer user_data,
305 gchar **standard_output,
306 gchar **standard_error,
307 gint *exit_status,
308 GError **error)
310 gint outpipe = -1;
311 gint errpipe = -1;
312 GPid pid;
313 fd_set fds;
314 gint ret;
315 GString *outstr = NULL;
316 GString *errstr = NULL;
317 gboolean failed;
318 gint status;
320 g_return_val_if_fail (argv != NULL, FALSE);
321 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
322 g_return_val_if_fail (standard_output == NULL ||
323 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
324 g_return_val_if_fail (standard_error == NULL ||
325 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
327 /* Just to ensure segfaults if callers try to use
328 * these when an error is reported.
330 if (standard_output)
331 *standard_output = NULL;
333 if (standard_error)
334 *standard_error = NULL;
336 if (!fork_exec_with_pipes (FALSE,
337 working_directory,
338 argv,
339 envp,
340 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
341 (flags & G_SPAWN_SEARCH_PATH) != 0,
342 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
343 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
344 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
345 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
346 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
347 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
348 child_setup,
349 user_data,
350 &pid,
351 NULL,
352 standard_output ? &outpipe : NULL,
353 standard_error ? &errpipe : NULL,
354 error))
355 return FALSE;
357 /* Read data from child. */
359 failed = FALSE;
361 if (outpipe >= 0)
363 outstr = g_string_new (NULL);
366 if (errpipe >= 0)
368 errstr = g_string_new (NULL);
371 /* Read data until we get EOF on both pipes. */
372 while (!failed &&
373 (outpipe >= 0 ||
374 errpipe >= 0))
376 ret = 0;
378 FD_ZERO (&fds);
379 if (outpipe >= 0)
380 FD_SET (outpipe, &fds);
381 if (errpipe >= 0)
382 FD_SET (errpipe, &fds);
384 ret = select (MAX (outpipe, errpipe) + 1,
385 &fds,
386 NULL, NULL,
387 NULL /* no timeout */);
389 if (ret < 0)
391 int errsv = errno;
393 if (errno == EINTR)
394 continue;
396 failed = TRUE;
398 g_set_error (error,
399 G_SPAWN_ERROR,
400 G_SPAWN_ERROR_READ,
401 _("Unexpected error in select() reading data from a child process (%s)"),
402 g_strerror (errsv));
404 break;
407 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
409 switch (read_data (outstr, outpipe, error))
411 case READ_FAILED:
412 failed = TRUE;
413 break;
414 case READ_EOF:
415 close_and_invalidate (&outpipe);
416 outpipe = -1;
417 break;
418 default:
419 break;
422 if (failed)
423 break;
426 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
428 switch (read_data (errstr, errpipe, error))
430 case READ_FAILED:
431 failed = TRUE;
432 break;
433 case READ_EOF:
434 close_and_invalidate (&errpipe);
435 errpipe = -1;
436 break;
437 default:
438 break;
441 if (failed)
442 break;
446 /* These should only be open still if we had an error. */
448 if (outpipe >= 0)
449 close_and_invalidate (&outpipe);
450 if (errpipe >= 0)
451 close_and_invalidate (&errpipe);
453 /* Wait for child to exit, even if we have
454 * an error pending.
456 again:
458 ret = waitpid (pid, &status, 0);
460 if (ret < 0)
462 if (errno == EINTR)
463 goto again;
464 else if (errno == ECHILD)
466 if (exit_status)
468 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.");
470 else
472 /* We don't need the exit status. */
475 else
477 if (!failed) /* avoid error pileups */
479 int errsv = errno;
481 failed = TRUE;
483 g_set_error (error,
484 G_SPAWN_ERROR,
485 G_SPAWN_ERROR_READ,
486 _("Unexpected error in waitpid() (%s)"),
487 g_strerror (errsv));
492 if (failed)
494 if (outstr)
495 g_string_free (outstr, TRUE);
496 if (errstr)
497 g_string_free (errstr, TRUE);
499 return FALSE;
501 else
503 if (exit_status)
504 *exit_status = status;
506 if (standard_output)
507 *standard_output = g_string_free (outstr, FALSE);
509 if (standard_error)
510 *standard_error = g_string_free (errstr, FALSE);
512 return TRUE;
517 * g_spawn_async_with_pipes:
518 * @working_directory: (type filename) (nullable): child's current working
519 * directory, or %NULL to inherit parent's, in the GLib file name encoding
520 * @argv: (array zero-terminated=1) (element-type filename): child's argument
521 * vector, in the GLib file name encoding
522 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
523 * child's environment, or %NULL to inherit parent's, in the GLib file
524 * name encoding
525 * @flags: flags from #GSpawnFlags
526 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
527 * @user_data: (closure): user data for @child_setup
528 * @child_pid: (out) (optional): return location for child process ID, or %NULL
529 * @standard_input: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
530 * @standard_output: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
531 * @standard_error: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
532 * @error: return location for error
534 * Executes a child program asynchronously (your program will not
535 * block waiting for the child to exit). The child program is
536 * specified by the only argument that must be provided, @argv.
537 * @argv should be a %NULL-terminated array of strings, to be passed
538 * as the argument vector for the child. The first string in @argv
539 * is of course the name of the program to execute. By default, the
540 * name of the program must be a full path. If @flags contains the
541 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is
542 * used to search for the executable. If @flags contains the
543 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from
544 * @envp is used to search for the executable. If both the
545 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags
546 * are set, the `PATH` variable from @envp takes precedence over
547 * the environment variable.
549 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
550 * used, then the program will be run from the current directory (or
551 * @working_directory, if specified); this might be unexpected or even
552 * dangerous in some cases when the current directory is world-writable.
554 * On Windows, note that all the string or string vector arguments to
555 * this function and the other g_spawn*() functions are in UTF-8, the
556 * GLib file name encoding. Unicode characters that are not part of
557 * the system codepage passed in these arguments will be correctly
558 * available in the spawned program only if it uses wide character API
559 * to retrieve its command line. For C programs built with Microsoft's
560 * tools it is enough to make the program have a wmain() instead of
561 * main(). wmain() has a wide character argument vector as parameter.
563 * At least currently, mingw doesn't support wmain(), so if you use
564 * mingw to develop the spawned program, it should call
565 * g_win32_get_command_line() to get arguments in UTF-8.
567 * On Windows the low-level child process creation API CreateProcess()
568 * doesn't use argument vectors, but a command line. The C runtime
569 * library's spawn*() family of functions (which g_spawn_async_with_pipes()
570 * eventually calls) paste the argument vector elements together into
571 * a command line, and the C runtime startup code does a corresponding
572 * reconstruction of an argument vector from the command line, to be
573 * passed to main(). Complications arise when you have argument vector
574 * elements that contain spaces of double quotes. The spawn*() functions
575 * don't do any quoting or escaping, but on the other hand the startup
576 * code does do unquoting and unescaping in order to enable receiving
577 * arguments with embedded spaces or double quotes. To work around this
578 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
579 * argument vector elements that need it before calling the C runtime
580 * spawn() function.
582 * The returned @child_pid on Windows is a handle to the child
583 * process, not its identifier. Process handles and process
584 * identifiers are different concepts on Windows.
586 * @envp is a %NULL-terminated array of strings, where each string
587 * has the form `KEY=VALUE`. This will become the child's environment.
588 * If @envp is %NULL, the child inherits its parent's environment.
590 * @flags should be the bitwise OR of any flags you want to affect the
591 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
592 * child will not automatically be reaped; you must use a child watch
593 * (g_child_watch_add()) to be notified about the death of the child process,
594 * otherwise it will stay around as a zombie process until this process exits.
595 * Eventually you must call g_spawn_close_pid() on the @child_pid, in order to
596 * free resources which may be associated with the child process. (On Unix,
597 * using a child watch is equivalent to calling waitpid() or handling
598 * the %SIGCHLD signal manually. On Windows, calling g_spawn_close_pid()
599 * is equivalent to calling CloseHandle() on the process handle returned
600 * in @child_pid). See g_child_watch_add().
602 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
603 * descriptors will be inherited by the child; otherwise all descriptors
604 * except stdin/stdout/stderr will be closed before calling exec() in
605 * the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
606 * absolute path, it will be looked for in the `PATH` environment
607 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
608 * absolute path, it will be looked for in the `PATH` variable from
609 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
610 * are used, the value from @envp takes precedence over the environment.
611 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
612 * will be discarded, instead of going to the same location as the parent's
613 * standard output. If you use this flag, @standard_output must be %NULL.
614 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
615 * will be discarded, instead of going to the same location as the parent's
616 * standard error. If you use this flag, @standard_error must be %NULL.
617 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
618 * standard input (by default, the child's standard input is attached to
619 * `/dev/null`). If you use this flag, @standard_input must be %NULL.
620 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
621 * the file to execute, while the remaining elements are the actual
622 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
623 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
625 * @child_setup and @user_data are a function and user data. On POSIX
626 * platforms, the function is called in the child after GLib has
627 * performed all the setup it plans to perform (including creating
628 * pipes, closing file descriptors, etc.) but before calling exec().
629 * That is, @child_setup is called just before calling exec() in the
630 * child. Obviously actions taken in this function will only affect
631 * the child, not the parent.
633 * On Windows, there is no separate fork() and exec() functionality.
634 * Child processes are created and run with a single API call,
635 * CreateProcess(). There is no sensible thing @child_setup
636 * could be used for on Windows so it is ignored and not called.
638 * If non-%NULL, @child_pid will on Unix be filled with the child's
639 * process ID. You can use the process ID to send signals to the child,
640 * or to use g_child_watch_add() (or waitpid()) if you specified the
641 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
642 * filled with a handle to the child process only if you specified the
643 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
644 * process using the Win32 API, for example wait for its termination
645 * with the WaitFor*() functions, or examine its exit code with
646 * GetExitCodeProcess(). You should close the handle with CloseHandle()
647 * or g_spawn_close_pid() when you no longer need it.
649 * If non-%NULL, the @standard_input, @standard_output, @standard_error
650 * locations will be filled with file descriptors for writing to the child's
651 * standard input or reading from its standard output or standard error.
652 * The caller of g_spawn_async_with_pipes() must close these file descriptors
653 * when they are no longer in use. If these parameters are %NULL, the
654 * corresponding pipe won't be created.
656 * If @standard_input is %NULL, the child's standard input is attached to
657 * `/dev/null` unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
659 * If @standard_error is NULL, the child's standard error goes to the same
660 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
661 * is set.
663 * If @standard_output is NULL, the child's standard output goes to the same
664 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
665 * is set.
667 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
668 * If an error is set, the function returns %FALSE. Errors are reported
669 * even if they occur in the child (for example if the executable in
670 * @argv[0] is not found). Typically the `message` field of returned
671 * errors should be displayed to users. Possible errors are those from
672 * the #G_SPAWN_ERROR domain.
674 * If an error occurs, @child_pid, @standard_input, @standard_output,
675 * and @standard_error will not be filled with valid values.
677 * If @child_pid is not %NULL and an error does not occur then the returned
678 * process reference must be closed using g_spawn_close_pid().
680 * If you are writing a GTK+ application, and the program you are spawning is a
681 * graphical application too, then to ensure that the spawned program opens its
682 * windows on the right screen, you may want to use #GdkAppLaunchContext,
683 * #GAppLaunchContext, or set the %DISPLAY environment variable.
685 * Returns: %TRUE on success, %FALSE if an error was set
687 gboolean
688 g_spawn_async_with_pipes (const gchar *working_directory,
689 gchar **argv,
690 gchar **envp,
691 GSpawnFlags flags,
692 GSpawnChildSetupFunc child_setup,
693 gpointer user_data,
694 GPid *child_pid,
695 gint *standard_input,
696 gint *standard_output,
697 gint *standard_error,
698 GError **error)
700 g_return_val_if_fail (argv != NULL, FALSE);
701 g_return_val_if_fail (standard_output == NULL ||
702 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
703 g_return_val_if_fail (standard_error == NULL ||
704 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
705 /* can't inherit stdin if we have an input pipe. */
706 g_return_val_if_fail (standard_input == NULL ||
707 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
709 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
710 working_directory,
711 argv,
712 envp,
713 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
714 (flags & G_SPAWN_SEARCH_PATH) != 0,
715 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
716 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
717 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
718 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
719 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
720 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
721 child_setup,
722 user_data,
723 child_pid,
724 standard_input,
725 standard_output,
726 standard_error,
727 error);
731 * g_spawn_command_line_sync:
732 * @command_line: (type filename): a command line
733 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output
734 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child errors
735 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid()
736 * @error: return location for errors
738 * A simple version of g_spawn_sync() with little-used parameters
739 * removed, taking a command line instead of an argument vector. See
740 * g_spawn_sync() for full details. @command_line will be parsed by
741 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
742 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
743 * implications, so consider using g_spawn_sync() directly if
744 * appropriate. Possible errors are those from g_spawn_sync() and those
745 * from g_shell_parse_argv().
747 * If @exit_status is non-%NULL, the platform-specific exit status of
748 * the child is stored there; see the documentation of
749 * g_spawn_check_exit_status() for how to use and interpret this.
751 * On Windows, please note the implications of g_shell_parse_argv()
752 * parsing @command_line. Parsing is done according to Unix shell rules, not
753 * Windows command interpreter rules.
754 * Space is a separator, and backslashes are
755 * special. Thus you cannot simply pass a @command_line containing
756 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
757 * the backslashes will be eaten, and the space will act as a
758 * separator. You need to enclose such paths with single quotes, like
759 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
761 * Returns: %TRUE on success, %FALSE if an error was set
763 gboolean
764 g_spawn_command_line_sync (const gchar *command_line,
765 gchar **standard_output,
766 gchar **standard_error,
767 gint *exit_status,
768 GError **error)
770 gboolean retval;
771 gchar **argv = NULL;
773 g_return_val_if_fail (command_line != NULL, FALSE);
775 if (!g_shell_parse_argv (command_line,
776 NULL, &argv,
777 error))
778 return FALSE;
780 retval = g_spawn_sync (NULL,
781 argv,
782 NULL,
783 G_SPAWN_SEARCH_PATH,
784 NULL,
785 NULL,
786 standard_output,
787 standard_error,
788 exit_status,
789 error);
790 g_strfreev (argv);
792 return retval;
796 * g_spawn_command_line_async:
797 * @command_line: (type filename): a command line
798 * @error: return location for errors
800 * A simple version of g_spawn_async() that parses a command line with
801 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
802 * command line in the background. Unlike g_spawn_async(), the
803 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
804 * that %G_SPAWN_SEARCH_PATH can have security implications, so
805 * consider using g_spawn_async() directly if appropriate. Possible
806 * errors are those from g_shell_parse_argv() and g_spawn_async().
808 * The same concerns on Windows apply as for g_spawn_command_line_sync().
810 * Returns: %TRUE on success, %FALSE if error is set
812 gboolean
813 g_spawn_command_line_async (const gchar *command_line,
814 GError **error)
816 gboolean retval;
817 gchar **argv = NULL;
819 g_return_val_if_fail (command_line != NULL, FALSE);
821 if (!g_shell_parse_argv (command_line,
822 NULL, &argv,
823 error))
824 return FALSE;
826 retval = g_spawn_async (NULL,
827 argv,
828 NULL,
829 G_SPAWN_SEARCH_PATH,
830 NULL,
831 NULL,
832 NULL,
833 error);
834 g_strfreev (argv);
836 return retval;
840 * g_spawn_check_exit_status:
841 * @exit_status: An exit code as returned from g_spawn_sync()
842 * @error: a #GError
844 * Set @error if @exit_status indicates the child exited abnormally
845 * (e.g. with a nonzero exit code, or via a fatal signal).
847 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
848 * exit status for subprocesses encoded in a platform-specific way.
849 * On Unix, this is guaranteed to be in the same format waitpid() returns,
850 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
852 * Prior to the introduction of this function in GLib 2.34, interpreting
853 * @exit_status required use of platform-specific APIs, which is problematic
854 * for software using GLib as a cross-platform layer.
856 * Additionally, many programs simply want to determine whether or not
857 * the child exited successfully, and either propagate a #GError or
858 * print a message to standard error. In that common case, this function
859 * can be used. Note that the error message in @error will contain
860 * human-readable information about the exit status.
862 * The @domain and @code of @error have special semantics in the case
863 * where the process has an "exit code", as opposed to being killed by
864 * a signal. On Unix, this happens if WIFEXITED() would be true of
865 * @exit_status. On Windows, it is always the case.
867 * The special semantics are that the actual exit code will be the
868 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
869 * This allows you to differentiate between different exit codes.
871 * If the process was terminated by some means other than an exit
872 * status, the domain will be %G_SPAWN_ERROR, and the code will be
873 * %G_SPAWN_ERROR_FAILED.
875 * This function just offers convenience; you can of course also check
876 * the available platform via a macro such as %G_OS_UNIX, and use
877 * WIFEXITED() and WEXITSTATUS() on @exit_status directly. Do not attempt
878 * to scan or parse the error message string; it may be translated and/or
879 * change in future versions of GLib.
881 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
882 * @error will be set)
884 * Since: 2.34
886 gboolean
887 g_spawn_check_exit_status (gint exit_status,
888 GError **error)
890 gboolean ret = FALSE;
892 if (WIFEXITED (exit_status))
894 if (WEXITSTATUS (exit_status) != 0)
896 g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (exit_status),
897 _("Child process exited with code %ld"),
898 (long) WEXITSTATUS (exit_status));
899 goto out;
902 else if (WIFSIGNALED (exit_status))
904 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
905 _("Child process killed by signal %ld"),
906 (long) WTERMSIG (exit_status));
907 goto out;
909 else if (WIFSTOPPED (exit_status))
911 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
912 _("Child process stopped by signal %ld"),
913 (long) WSTOPSIG (exit_status));
914 goto out;
916 else
918 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
919 _("Child process exited abnormally"));
920 goto out;
923 ret = TRUE;
924 out:
925 return ret;
928 static gint
929 exec_err_to_g_error (gint en)
931 switch (en)
933 #ifdef EACCES
934 case EACCES:
935 return G_SPAWN_ERROR_ACCES;
936 break;
937 #endif
939 #ifdef EPERM
940 case EPERM:
941 return G_SPAWN_ERROR_PERM;
942 break;
943 #endif
945 #ifdef E2BIG
946 case E2BIG:
947 return G_SPAWN_ERROR_TOO_BIG;
948 break;
949 #endif
951 #ifdef ENOEXEC
952 case ENOEXEC:
953 return G_SPAWN_ERROR_NOEXEC;
954 break;
955 #endif
957 #ifdef ENAMETOOLONG
958 case ENAMETOOLONG:
959 return G_SPAWN_ERROR_NAMETOOLONG;
960 break;
961 #endif
963 #ifdef ENOENT
964 case ENOENT:
965 return G_SPAWN_ERROR_NOENT;
966 break;
967 #endif
969 #ifdef ENOMEM
970 case ENOMEM:
971 return G_SPAWN_ERROR_NOMEM;
972 break;
973 #endif
975 #ifdef ENOTDIR
976 case ENOTDIR:
977 return G_SPAWN_ERROR_NOTDIR;
978 break;
979 #endif
981 #ifdef ELOOP
982 case ELOOP:
983 return G_SPAWN_ERROR_LOOP;
984 break;
985 #endif
987 #ifdef ETXTBUSY
988 case ETXTBUSY:
989 return G_SPAWN_ERROR_TXTBUSY;
990 break;
991 #endif
993 #ifdef EIO
994 case EIO:
995 return G_SPAWN_ERROR_IO;
996 break;
997 #endif
999 #ifdef ENFILE
1000 case ENFILE:
1001 return G_SPAWN_ERROR_NFILE;
1002 break;
1003 #endif
1005 #ifdef EMFILE
1006 case EMFILE:
1007 return G_SPAWN_ERROR_MFILE;
1008 break;
1009 #endif
1011 #ifdef EINVAL
1012 case EINVAL:
1013 return G_SPAWN_ERROR_INVAL;
1014 break;
1015 #endif
1017 #ifdef EISDIR
1018 case EISDIR:
1019 return G_SPAWN_ERROR_ISDIR;
1020 break;
1021 #endif
1023 #ifdef ELIBBAD
1024 case ELIBBAD:
1025 return G_SPAWN_ERROR_LIBBAD;
1026 break;
1027 #endif
1029 default:
1030 return G_SPAWN_ERROR_FAILED;
1031 break;
1035 static gssize
1036 write_all (gint fd, gconstpointer vbuf, gsize to_write)
1038 gchar *buf = (gchar *) vbuf;
1040 while (to_write > 0)
1042 gssize count = write (fd, buf, to_write);
1043 if (count < 0)
1045 if (errno != EINTR)
1046 return FALSE;
1048 else
1050 to_write -= count;
1051 buf += count;
1055 return TRUE;
1058 G_GNUC_NORETURN
1059 static void
1060 write_err_and_exit (gint fd, gint msg)
1062 gint en = errno;
1064 write_all (fd, &msg, sizeof(msg));
1065 write_all (fd, &en, sizeof(en));
1067 _exit (1);
1070 static int
1071 set_cloexec (void *data, gint fd)
1073 if (fd >= GPOINTER_TO_INT (data))
1074 fcntl (fd, F_SETFD, FD_CLOEXEC);
1076 return 0;
1079 #ifndef HAVE_FDWALK
1080 static int
1081 fdwalk (int (*cb)(void *data, int fd), void *data)
1083 gint open_max;
1084 gint fd;
1085 gint res = 0;
1087 #ifdef HAVE_SYS_RESOURCE_H
1088 struct rlimit rl;
1089 #endif
1091 #ifdef __linux__
1092 DIR *d;
1094 if ((d = opendir("/proc/self/fd"))) {
1095 struct dirent *de;
1097 while ((de = readdir(d))) {
1098 glong l;
1099 gchar *e = NULL;
1101 if (de->d_name[0] == '.')
1102 continue;
1104 errno = 0;
1105 l = strtol(de->d_name, &e, 10);
1106 if (errno != 0 || !e || *e)
1107 continue;
1109 fd = (gint) l;
1111 if ((glong) fd != l)
1112 continue;
1114 if (fd == dirfd(d))
1115 continue;
1117 if ((res = cb (data, fd)) != 0)
1118 break;
1121 closedir(d);
1122 return res;
1125 /* If /proc is not mounted or not accessible we fall back to the old
1126 * rlimit trick */
1128 #endif
1130 #ifdef HAVE_SYS_RESOURCE_H
1132 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1133 open_max = rl.rlim_max;
1134 else
1135 #endif
1136 open_max = sysconf (_SC_OPEN_MAX);
1138 for (fd = 0; fd < open_max; fd++)
1139 if ((res = cb (data, fd)) != 0)
1140 break;
1142 return res;
1144 #endif
1146 static gint
1147 sane_dup2 (gint fd1, gint fd2)
1149 gint ret;
1151 retry:
1152 ret = dup2 (fd1, fd2);
1153 if (ret < 0 && errno == EINTR)
1154 goto retry;
1156 return ret;
1159 static gint
1160 sane_open (const char *path, gint mode)
1162 gint ret;
1164 retry:
1165 ret = open (path, mode);
1166 if (ret < 0 && errno == EINTR)
1167 goto retry;
1169 return ret;
1172 enum
1174 CHILD_CHDIR_FAILED,
1175 CHILD_EXEC_FAILED,
1176 CHILD_DUP2_FAILED,
1177 CHILD_FORK_FAILED
1180 static void
1181 do_exec (gint child_err_report_fd,
1182 gint stdin_fd,
1183 gint stdout_fd,
1184 gint stderr_fd,
1185 const gchar *working_directory,
1186 gchar **argv,
1187 gchar **envp,
1188 gboolean close_descriptors,
1189 gboolean search_path,
1190 gboolean search_path_from_envp,
1191 gboolean stdout_to_null,
1192 gboolean stderr_to_null,
1193 gboolean child_inherits_stdin,
1194 gboolean file_and_argv_zero,
1195 GSpawnChildSetupFunc child_setup,
1196 gpointer user_data)
1198 if (working_directory && chdir (working_directory) < 0)
1199 write_err_and_exit (child_err_report_fd,
1200 CHILD_CHDIR_FAILED);
1202 /* Close all file descriptors but stdin stdout and stderr as
1203 * soon as we exec. Note that this includes
1204 * child_err_report_fd, which keeps the parent from blocking
1205 * forever on the other end of that pipe.
1207 if (close_descriptors)
1209 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1211 else
1213 /* We need to do child_err_report_fd anyway */
1214 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1217 /* Redirect pipes as required */
1219 if (stdin_fd >= 0)
1221 /* dup2 can't actually fail here I don't think */
1223 if (sane_dup2 (stdin_fd, 0) < 0)
1224 write_err_and_exit (child_err_report_fd,
1225 CHILD_DUP2_FAILED);
1227 /* ignore this if it doesn't work */
1228 close_and_invalidate (&stdin_fd);
1230 else if (!child_inherits_stdin)
1232 /* Keep process from blocking on a read of stdin */
1233 gint read_null = open ("/dev/null", O_RDONLY);
1234 g_assert (read_null != -1);
1235 sane_dup2 (read_null, 0);
1236 close_and_invalidate (&read_null);
1239 if (stdout_fd >= 0)
1241 /* dup2 can't actually fail here I don't think */
1243 if (sane_dup2 (stdout_fd, 1) < 0)
1244 write_err_and_exit (child_err_report_fd,
1245 CHILD_DUP2_FAILED);
1247 /* ignore this if it doesn't work */
1248 close_and_invalidate (&stdout_fd);
1250 else if (stdout_to_null)
1252 gint write_null = sane_open ("/dev/null", O_WRONLY);
1253 g_assert (write_null != -1);
1254 sane_dup2 (write_null, 1);
1255 close_and_invalidate (&write_null);
1258 if (stderr_fd >= 0)
1260 /* dup2 can't actually fail here I don't think */
1262 if (sane_dup2 (stderr_fd, 2) < 0)
1263 write_err_and_exit (child_err_report_fd,
1264 CHILD_DUP2_FAILED);
1266 /* ignore this if it doesn't work */
1267 close_and_invalidate (&stderr_fd);
1269 else if (stderr_to_null)
1271 gint write_null = sane_open ("/dev/null", O_WRONLY);
1272 sane_dup2 (write_null, 2);
1273 close_and_invalidate (&write_null);
1276 /* Call user function just before we exec */
1277 if (child_setup)
1279 (* child_setup) (user_data);
1282 g_execute (argv[0],
1283 file_and_argv_zero ? argv + 1 : argv,
1284 envp, search_path, search_path_from_envp);
1286 /* Exec failed */
1287 write_err_and_exit (child_err_report_fd,
1288 CHILD_EXEC_FAILED);
1291 static gboolean
1292 read_ints (int fd,
1293 gint* buf,
1294 gint n_ints_in_buf,
1295 gint *n_ints_read,
1296 GError **error)
1298 gsize bytes = 0;
1300 while (TRUE)
1302 gssize chunk;
1304 if (bytes >= sizeof(gint)*2)
1305 break; /* give up, who knows what happened, should not be
1306 * possible.
1309 again:
1310 chunk = read (fd,
1311 ((gchar*)buf) + bytes,
1312 sizeof(gint) * n_ints_in_buf - bytes);
1313 if (chunk < 0 && errno == EINTR)
1314 goto again;
1316 if (chunk < 0)
1318 int errsv = errno;
1320 /* Some weird shit happened, bail out */
1321 g_set_error (error,
1322 G_SPAWN_ERROR,
1323 G_SPAWN_ERROR_FAILED,
1324 _("Failed to read from child pipe (%s)"),
1325 g_strerror (errsv));
1327 return FALSE;
1329 else if (chunk == 0)
1330 break; /* EOF */
1331 else /* chunk > 0 */
1332 bytes += chunk;
1335 *n_ints_read = (gint)(bytes / sizeof(gint));
1337 return TRUE;
1340 static gboolean
1341 fork_exec_with_pipes (gboolean intermediate_child,
1342 const gchar *working_directory,
1343 gchar **argv,
1344 gchar **envp,
1345 gboolean close_descriptors,
1346 gboolean search_path,
1347 gboolean search_path_from_envp,
1348 gboolean stdout_to_null,
1349 gboolean stderr_to_null,
1350 gboolean child_inherits_stdin,
1351 gboolean file_and_argv_zero,
1352 gboolean cloexec_pipes,
1353 GSpawnChildSetupFunc child_setup,
1354 gpointer user_data,
1355 GPid *child_pid,
1356 gint *standard_input,
1357 gint *standard_output,
1358 gint *standard_error,
1359 GError **error)
1361 GPid pid = -1;
1362 gint stdin_pipe[2] = { -1, -1 };
1363 gint stdout_pipe[2] = { -1, -1 };
1364 gint stderr_pipe[2] = { -1, -1 };
1365 gint child_err_report_pipe[2] = { -1, -1 };
1366 gint child_pid_report_pipe[2] = { -1, -1 };
1367 guint pipe_flags = cloexec_pipes ? FD_CLOEXEC : 0;
1368 gint status;
1370 if (!g_unix_open_pipe (child_err_report_pipe, pipe_flags, error))
1371 return FALSE;
1373 if (intermediate_child && !g_unix_open_pipe (child_pid_report_pipe, pipe_flags, error))
1374 goto cleanup_and_fail;
1376 if (standard_input && !g_unix_open_pipe (stdin_pipe, pipe_flags, error))
1377 goto cleanup_and_fail;
1379 if (standard_output && !g_unix_open_pipe (stdout_pipe, pipe_flags, error))
1380 goto cleanup_and_fail;
1382 if (standard_error && !g_unix_open_pipe (stderr_pipe, FD_CLOEXEC, error))
1383 goto cleanup_and_fail;
1385 pid = fork ();
1387 if (pid < 0)
1389 int errsv = errno;
1391 g_set_error (error,
1392 G_SPAWN_ERROR,
1393 G_SPAWN_ERROR_FORK,
1394 _("Failed to fork (%s)"),
1395 g_strerror (errsv));
1397 goto cleanup_and_fail;
1399 else if (pid == 0)
1401 /* Immediate child. This may or may not be the child that
1402 * actually execs the new process.
1405 /* Reset some signal handlers that we may use */
1406 signal (SIGCHLD, SIG_DFL);
1407 signal (SIGINT, SIG_DFL);
1408 signal (SIGTERM, SIG_DFL);
1409 signal (SIGHUP, SIG_DFL);
1411 /* Be sure we crash if the parent exits
1412 * and we write to the err_report_pipe
1414 signal (SIGPIPE, SIG_DFL);
1416 /* Close the parent's end of the pipes;
1417 * not needed in the close_descriptors case,
1418 * though
1420 close_and_invalidate (&child_err_report_pipe[0]);
1421 close_and_invalidate (&child_pid_report_pipe[0]);
1422 close_and_invalidate (&stdin_pipe[1]);
1423 close_and_invalidate (&stdout_pipe[0]);
1424 close_and_invalidate (&stderr_pipe[0]);
1426 if (intermediate_child)
1428 /* We need to fork an intermediate child that launches the
1429 * final child. The purpose of the intermediate child
1430 * is to exit, so we can waitpid() it immediately.
1431 * Then the grandchild will not become a zombie.
1433 GPid grandchild_pid;
1435 grandchild_pid = fork ();
1437 if (grandchild_pid < 0)
1439 /* report -1 as child PID */
1440 write_all (child_pid_report_pipe[1], &grandchild_pid,
1441 sizeof(grandchild_pid));
1443 write_err_and_exit (child_err_report_pipe[1],
1444 CHILD_FORK_FAILED);
1446 else if (grandchild_pid == 0)
1448 close_and_invalidate (&child_pid_report_pipe[1]);
1449 do_exec (child_err_report_pipe[1],
1450 stdin_pipe[0],
1451 stdout_pipe[1],
1452 stderr_pipe[1],
1453 working_directory,
1454 argv,
1455 envp,
1456 close_descriptors,
1457 search_path,
1458 search_path_from_envp,
1459 stdout_to_null,
1460 stderr_to_null,
1461 child_inherits_stdin,
1462 file_and_argv_zero,
1463 child_setup,
1464 user_data);
1466 else
1468 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1469 close_and_invalidate (&child_pid_report_pipe[1]);
1471 _exit (0);
1474 else
1476 /* Just run the child.
1479 do_exec (child_err_report_pipe[1],
1480 stdin_pipe[0],
1481 stdout_pipe[1],
1482 stderr_pipe[1],
1483 working_directory,
1484 argv,
1485 envp,
1486 close_descriptors,
1487 search_path,
1488 search_path_from_envp,
1489 stdout_to_null,
1490 stderr_to_null,
1491 child_inherits_stdin,
1492 file_and_argv_zero,
1493 child_setup,
1494 user_data);
1497 else
1499 /* Parent */
1501 gint buf[2];
1502 gint n_ints = 0;
1504 /* Close the uncared-about ends of the pipes */
1505 close_and_invalidate (&child_err_report_pipe[1]);
1506 close_and_invalidate (&child_pid_report_pipe[1]);
1507 close_and_invalidate (&stdin_pipe[0]);
1508 close_and_invalidate (&stdout_pipe[1]);
1509 close_and_invalidate (&stderr_pipe[1]);
1511 /* If we had an intermediate child, reap it */
1512 if (intermediate_child)
1514 wait_again:
1515 if (waitpid (pid, &status, 0) < 0)
1517 if (errno == EINTR)
1518 goto wait_again;
1519 else if (errno == ECHILD)
1520 ; /* do nothing, child already reaped */
1521 else
1522 g_warning ("waitpid() should not fail in "
1523 "'fork_exec_with_pipes'");
1528 if (!read_ints (child_err_report_pipe[0],
1529 buf, 2, &n_ints,
1530 error))
1531 goto cleanup_and_fail;
1533 if (n_ints >= 2)
1535 /* Error from the child. */
1537 switch (buf[0])
1539 case CHILD_CHDIR_FAILED:
1540 g_set_error (error,
1541 G_SPAWN_ERROR,
1542 G_SPAWN_ERROR_CHDIR,
1543 _("Failed to change to directory “%s” (%s)"),
1544 working_directory,
1545 g_strerror (buf[1]));
1547 break;
1549 case CHILD_EXEC_FAILED:
1550 g_set_error (error,
1551 G_SPAWN_ERROR,
1552 exec_err_to_g_error (buf[1]),
1553 _("Failed to execute child process “%s” (%s)"),
1554 argv[0],
1555 g_strerror (buf[1]));
1557 break;
1559 case CHILD_DUP2_FAILED:
1560 g_set_error (error,
1561 G_SPAWN_ERROR,
1562 G_SPAWN_ERROR_FAILED,
1563 _("Failed to redirect output or input of child process (%s)"),
1564 g_strerror (buf[1]));
1566 break;
1568 case CHILD_FORK_FAILED:
1569 g_set_error (error,
1570 G_SPAWN_ERROR,
1571 G_SPAWN_ERROR_FORK,
1572 _("Failed to fork child process (%s)"),
1573 g_strerror (buf[1]));
1574 break;
1576 default:
1577 g_set_error (error,
1578 G_SPAWN_ERROR,
1579 G_SPAWN_ERROR_FAILED,
1580 _("Unknown error executing child process “%s”"),
1581 argv[0]);
1582 break;
1585 goto cleanup_and_fail;
1588 /* Get child pid from intermediate child pipe. */
1589 if (intermediate_child)
1591 n_ints = 0;
1593 if (!read_ints (child_pid_report_pipe[0],
1594 buf, 1, &n_ints, error))
1595 goto cleanup_and_fail;
1597 if (n_ints < 1)
1599 int errsv = errno;
1601 g_set_error (error,
1602 G_SPAWN_ERROR,
1603 G_SPAWN_ERROR_FAILED,
1604 _("Failed to read enough data from child pid pipe (%s)"),
1605 g_strerror (errsv));
1606 goto cleanup_and_fail;
1608 else
1610 /* we have the child pid */
1611 pid = buf[0];
1615 /* Success against all odds! return the information */
1616 close_and_invalidate (&child_err_report_pipe[0]);
1617 close_and_invalidate (&child_pid_report_pipe[0]);
1619 if (child_pid)
1620 *child_pid = pid;
1622 if (standard_input)
1623 *standard_input = stdin_pipe[1];
1624 if (standard_output)
1625 *standard_output = stdout_pipe[0];
1626 if (standard_error)
1627 *standard_error = stderr_pipe[0];
1629 return TRUE;
1632 cleanup_and_fail:
1634 /* There was an error from the Child, reap the child to avoid it being
1635 a zombie.
1638 if (pid > 0)
1640 wait_failed:
1641 if (waitpid (pid, NULL, 0) < 0)
1643 if (errno == EINTR)
1644 goto wait_failed;
1645 else if (errno == ECHILD)
1646 ; /* do nothing, child already reaped */
1647 else
1648 g_warning ("waitpid() should not fail in "
1649 "'fork_exec_with_pipes'");
1653 close_and_invalidate (&child_err_report_pipe[0]);
1654 close_and_invalidate (&child_err_report_pipe[1]);
1655 close_and_invalidate (&child_pid_report_pipe[0]);
1656 close_and_invalidate (&child_pid_report_pipe[1]);
1657 close_and_invalidate (&stdin_pipe[0]);
1658 close_and_invalidate (&stdin_pipe[1]);
1659 close_and_invalidate (&stdout_pipe[0]);
1660 close_and_invalidate (&stdout_pipe[1]);
1661 close_and_invalidate (&stderr_pipe[0]);
1662 close_and_invalidate (&stderr_pipe[1]);
1664 return FALSE;
1667 /* Based on execvp from GNU C Library */
1669 static void
1670 script_execute (const gchar *file,
1671 gchar **argv,
1672 gchar **envp)
1674 /* Count the arguments. */
1675 int argc = 0;
1676 while (argv[argc])
1677 ++argc;
1679 /* Construct an argument list for the shell. */
1681 gchar **new_argv;
1683 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1685 new_argv[0] = (char *) "/bin/sh";
1686 new_argv[1] = (char *) file;
1687 while (argc > 0)
1689 new_argv[argc + 1] = argv[argc];
1690 --argc;
1693 /* Execute the shell. */
1694 if (envp)
1695 execve (new_argv[0], new_argv, envp);
1696 else
1697 execv (new_argv[0], new_argv);
1699 g_free (new_argv);
1703 static gchar*
1704 my_strchrnul (const gchar *str, gchar c)
1706 gchar *p = (gchar*) str;
1707 while (*p && (*p != c))
1708 ++p;
1710 return p;
1713 static gint
1714 g_execute (const gchar *file,
1715 gchar **argv,
1716 gchar **envp,
1717 gboolean search_path,
1718 gboolean search_path_from_envp)
1720 if (*file == '\0')
1722 /* We check the simple case first. */
1723 errno = ENOENT;
1724 return -1;
1727 if (!(search_path || search_path_from_envp) || strchr (file, '/') != NULL)
1729 /* Don't search when it contains a slash. */
1730 if (envp)
1731 execve (file, argv, envp);
1732 else
1733 execv (file, argv);
1735 if (errno == ENOEXEC)
1736 script_execute (file, argv, envp);
1738 else
1740 gboolean got_eacces = 0;
1741 const gchar *path, *p;
1742 gchar *name, *freeme;
1743 gsize len;
1744 gsize pathlen;
1746 path = NULL;
1747 if (search_path_from_envp)
1748 path = g_environ_getenv (envp, "PATH");
1749 if (search_path && path == NULL)
1750 path = g_getenv ("PATH");
1752 if (path == NULL)
1754 /* There is no 'PATH' in the environment. The default
1755 * search path in libc is the current directory followed by
1756 * the path 'confstr' returns for '_CS_PATH'.
1759 /* In GLib we put . last, for security, and don't use the
1760 * unportable confstr(); UNIX98 does not actually specify
1761 * what to search if PATH is unset. POSIX may, dunno.
1764 path = "/bin:/usr/bin:.";
1767 len = strlen (file) + 1;
1768 pathlen = strlen (path);
1769 freeme = name = g_malloc (pathlen + len + 1);
1771 /* Copy the file name at the top, including '\0' */
1772 memcpy (name + pathlen + 1, file, len);
1773 name = name + pathlen;
1774 /* And add the slash before the filename */
1775 *name = '/';
1777 p = path;
1780 char *startp;
1782 path = p;
1783 p = my_strchrnul (path, ':');
1785 if (p == path)
1786 /* Two adjacent colons, or a colon at the beginning or the end
1787 * of 'PATH' means to search the current directory.
1789 startp = name + 1;
1790 else
1791 startp = memcpy (name - (p - path), path, p - path);
1793 /* Try to execute this name. If it works, execv will not return. */
1794 if (envp)
1795 execve (startp, argv, envp);
1796 else
1797 execv (startp, argv);
1799 if (errno == ENOEXEC)
1800 script_execute (startp, argv, envp);
1802 switch (errno)
1804 case EACCES:
1805 /* Record the we got a 'Permission denied' error. If we end
1806 * up finding no executable we can use, we want to diagnose
1807 * that we did find one but were denied access.
1809 got_eacces = TRUE;
1811 /* FALL THRU */
1813 case ENOENT:
1814 #ifdef ESTALE
1815 case ESTALE:
1816 #endif
1817 #ifdef ENOTDIR
1818 case ENOTDIR:
1819 #endif
1820 /* Those errors indicate the file is missing or not executable
1821 * by us, in which case we want to just try the next path
1822 * directory.
1824 break;
1826 case ENODEV:
1827 case ETIMEDOUT:
1828 /* Some strange filesystems like AFS return even
1829 * stranger error numbers. They cannot reasonably mean anything
1830 * else so ignore those, too.
1832 break;
1834 default:
1835 /* Some other error means we found an executable file, but
1836 * something went wrong executing it; return the error to our
1837 * caller.
1839 g_free (freeme);
1840 return -1;
1843 while (*p++ != '\0');
1845 /* We tried every element and none of them worked. */
1846 if (got_eacces)
1847 /* At least one failure was due to permissions, so report that
1848 * error.
1850 errno = EACCES;
1852 g_free (freeme);
1855 /* Return the error from the last attempt (probably ENOENT). */
1856 return -1;
1860 * g_spawn_close_pid:
1861 * @pid: The process reference to close
1863 * On some platforms, notably Windows, the #GPid type represents a resource
1864 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1865 * is provided for this purpose. It should be used on all platforms, even
1866 * though it doesn't do anything under UNIX.
1868 void
1869 g_spawn_close_pid (GPid pid)