Update German translation
[glib.git] / glib / gspawn.c
blob6f78f5cd14fe7510f4f19b74a21ae30132fafd55
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 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.
75 static gint g_execute (const gchar *file,
76 gchar **argv,
77 gchar **envp,
78 gboolean search_path,
79 gboolean search_path_from_envp);
81 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
82 const gchar *working_directory,
83 gchar **argv,
84 gchar **envp,
85 gboolean close_descriptors,
86 gboolean search_path,
87 gboolean search_path_from_envp,
88 gboolean stdout_to_null,
89 gboolean stderr_to_null,
90 gboolean child_inherits_stdin,
91 gboolean file_and_argv_zero,
92 gboolean cloexec_pipes,
93 GSpawnChildSetupFunc child_setup,
94 gpointer user_data,
95 GPid *child_pid,
96 gint *standard_input,
97 gint *standard_output,
98 gint *standard_error,
99 GError **error);
101 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
102 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
105 * g_spawn_async:
106 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's
107 * @argv: (array zero-terminated=1): child's argument vector
108 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's
109 * @flags: flags from #GSpawnFlags
110 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
111 * @user_data: (closure): user data for @child_setup
112 * @child_pid: (out) (optional): return location for child process reference, or %NULL
113 * @error: return location for error
115 * See g_spawn_async_with_pipes() for a full description; this function
116 * simply calls the g_spawn_async_with_pipes() without any pipes.
118 * You should call g_spawn_close_pid() on the returned child process
119 * reference when you don't need it any more.
121 * If you are writing a GTK+ application, and the program you are
122 * spawning is a graphical application, too, then you may want to
123 * use gdk_spawn_on_screen() instead to ensure that the spawned program
124 * opens its windows on the right screen.
126 * Note that the returned @child_pid on Windows is a handle to the child
127 * process and not its identifier. Process handles and process identifiers
128 * are different concepts on Windows.
130 * Returns: %TRUE on success, %FALSE if error is set
132 gboolean
133 g_spawn_async (const gchar *working_directory,
134 gchar **argv,
135 gchar **envp,
136 GSpawnFlags flags,
137 GSpawnChildSetupFunc child_setup,
138 gpointer user_data,
139 GPid *child_pid,
140 GError **error)
142 g_return_val_if_fail (argv != NULL, FALSE);
144 return g_spawn_async_with_pipes (working_directory,
145 argv, envp,
146 flags,
147 child_setup,
148 user_data,
149 child_pid,
150 NULL, NULL, NULL,
151 error);
154 /* Avoids a danger in threaded situations (calling close()
155 * on a file descriptor twice, and another thread has
156 * re-opened it since the first close)
158 static void
159 close_and_invalidate (gint *fd)
161 if (*fd < 0)
162 return;
163 else
165 (void) g_close (*fd, NULL);
166 *fd = -1;
170 /* Some versions of OS X define READ_OK in public headers */
171 #undef READ_OK
173 typedef enum
175 READ_FAILED = 0, /* FALSE */
176 READ_OK,
177 READ_EOF
178 } ReadResult;
180 static ReadResult
181 read_data (GString *str,
182 gint fd,
183 GError **error)
185 gssize bytes;
186 gchar buf[4096];
188 again:
189 bytes = read (fd, buf, 4096);
191 if (bytes == 0)
192 return READ_EOF;
193 else if (bytes > 0)
195 g_string_append_len (str, buf, bytes);
196 return READ_OK;
198 else if (errno == EINTR)
199 goto again;
200 else
202 int errsv = errno;
204 g_set_error (error,
205 G_SPAWN_ERROR,
206 G_SPAWN_ERROR_READ,
207 _("Failed to read data from child process (%s)"),
208 g_strerror (errsv));
210 return READ_FAILED;
215 * g_spawn_sync:
216 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's
217 * @argv: (array zero-terminated=1): child's argument vector
218 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's
219 * @flags: flags from #GSpawnFlags
220 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
221 * @user_data: (closure): user data for @child_setup
222 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output, or %NULL
223 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child error messages, or %NULL
224 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid(), or %NULL
225 * @error: return location for error, or %NULL
227 * Executes a child synchronously (waits for the child to exit before returning).
228 * All output from the child is stored in @standard_output and @standard_error,
229 * if those parameters are non-%NULL. Note that you must set the
230 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
231 * passing %NULL for @standard_output and @standard_error.
233 * If @exit_status is non-%NULL, the platform-specific exit status of
234 * the child is stored there; see the documentation of
235 * g_spawn_check_exit_status() for how to use and interpret this.
236 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
237 * @flags.
239 * If an error occurs, no data is returned in @standard_output,
240 * @standard_error, or @exit_status.
242 * This function calls g_spawn_async_with_pipes() internally; see that
243 * function for full details on the other parameters and details on
244 * how these functions work on Windows.
246 * Returns: %TRUE on success, %FALSE if an error was set
248 gboolean
249 g_spawn_sync (const gchar *working_directory,
250 gchar **argv,
251 gchar **envp,
252 GSpawnFlags flags,
253 GSpawnChildSetupFunc child_setup,
254 gpointer user_data,
255 gchar **standard_output,
256 gchar **standard_error,
257 gint *exit_status,
258 GError **error)
260 gint outpipe = -1;
261 gint errpipe = -1;
262 GPid pid;
263 fd_set fds;
264 gint ret;
265 GString *outstr = NULL;
266 GString *errstr = NULL;
267 gboolean failed;
268 gint status;
270 g_return_val_if_fail (argv != NULL, FALSE);
271 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
272 g_return_val_if_fail (standard_output == NULL ||
273 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
274 g_return_val_if_fail (standard_error == NULL ||
275 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
277 /* Just to ensure segfaults if callers try to use
278 * these when an error is reported.
280 if (standard_output)
281 *standard_output = NULL;
283 if (standard_error)
284 *standard_error = NULL;
286 if (!fork_exec_with_pipes (FALSE,
287 working_directory,
288 argv,
289 envp,
290 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
291 (flags & G_SPAWN_SEARCH_PATH) != 0,
292 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
293 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
294 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
295 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
296 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
297 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
298 child_setup,
299 user_data,
300 &pid,
301 NULL,
302 standard_output ? &outpipe : NULL,
303 standard_error ? &errpipe : NULL,
304 error))
305 return FALSE;
307 /* Read data from child. */
309 failed = FALSE;
311 if (outpipe >= 0)
313 outstr = g_string_new (NULL);
316 if (errpipe >= 0)
318 errstr = g_string_new (NULL);
321 /* Read data until we get EOF on both pipes. */
322 while (!failed &&
323 (outpipe >= 0 ||
324 errpipe >= 0))
326 ret = 0;
328 FD_ZERO (&fds);
329 if (outpipe >= 0)
330 FD_SET (outpipe, &fds);
331 if (errpipe >= 0)
332 FD_SET (errpipe, &fds);
334 ret = select (MAX (outpipe, errpipe) + 1,
335 &fds,
336 NULL, NULL,
337 NULL /* no timeout */);
339 if (ret < 0)
341 int errsv = errno;
343 if (errno == EINTR)
344 continue;
346 failed = TRUE;
348 g_set_error (error,
349 G_SPAWN_ERROR,
350 G_SPAWN_ERROR_READ,
351 _("Unexpected error in select() reading data from a child process (%s)"),
352 g_strerror (errsv));
354 break;
357 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
359 switch (read_data (outstr, outpipe, error))
361 case READ_FAILED:
362 failed = TRUE;
363 break;
364 case READ_EOF:
365 close_and_invalidate (&outpipe);
366 outpipe = -1;
367 break;
368 default:
369 break;
372 if (failed)
373 break;
376 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
378 switch (read_data (errstr, errpipe, error))
380 case READ_FAILED:
381 failed = TRUE;
382 break;
383 case READ_EOF:
384 close_and_invalidate (&errpipe);
385 errpipe = -1;
386 break;
387 default:
388 break;
391 if (failed)
392 break;
396 /* These should only be open still if we had an error. */
398 if (outpipe >= 0)
399 close_and_invalidate (&outpipe);
400 if (errpipe >= 0)
401 close_and_invalidate (&errpipe);
403 /* Wait for child to exit, even if we have
404 * an error pending.
406 again:
408 ret = waitpid (pid, &status, 0);
410 if (ret < 0)
412 if (errno == EINTR)
413 goto again;
414 else if (errno == ECHILD)
416 if (exit_status)
418 g_warning ("In call to g_spawn_sync(), exit status of a child process was requested but ECHILD was received by waitpid(). Most likely the process is ignoring SIGCHLD, or some other thread is invoking waitpid() with a nonpositive first argument; either behavior can break applications that use g_spawn_sync either directly or indirectly.");
420 else
422 /* We don't need the exit status. */
425 else
427 if (!failed) /* avoid error pileups */
429 int errsv = errno;
431 failed = TRUE;
433 g_set_error (error,
434 G_SPAWN_ERROR,
435 G_SPAWN_ERROR_READ,
436 _("Unexpected error in waitpid() (%s)"),
437 g_strerror (errsv));
442 if (failed)
444 if (outstr)
445 g_string_free (outstr, TRUE);
446 if (errstr)
447 g_string_free (errstr, TRUE);
449 return FALSE;
451 else
453 if (exit_status)
454 *exit_status = status;
456 if (standard_output)
457 *standard_output = g_string_free (outstr, FALSE);
459 if (standard_error)
460 *standard_error = g_string_free (errstr, FALSE);
462 return TRUE;
467 * g_spawn_async_with_pipes:
468 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
469 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
470 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
471 * @flags: flags from #GSpawnFlags
472 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
473 * @user_data: (closure): user data for @child_setup
474 * @child_pid: (out) (optional): return location for child process ID, or %NULL
475 * @standard_input: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
476 * @standard_output: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
477 * @standard_error: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
478 * @error: return location for error
480 * Executes a child program asynchronously (your program will not
481 * block waiting for the child to exit). The child program is
482 * specified by the only argument that must be provided, @argv.
483 * @argv should be a %NULL-terminated array of strings, to be passed
484 * as the argument vector for the child. The first string in @argv
485 * is of course the name of the program to execute. By default, the
486 * name of the program must be a full path. If @flags contains the
487 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is
488 * used to search for the executable. If @flags contains the
489 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from
490 * @envp is used to search for the executable. If both the
491 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags
492 * are set, the `PATH` variable from @envp takes precedence over
493 * the environment variable.
495 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
496 * used, then the program will be run from the current directory (or
497 * @working_directory, if specified); this might be unexpected or even
498 * dangerous in some cases when the current directory is world-writable.
500 * On Windows, note that all the string or string vector arguments to
501 * this function and the other g_spawn*() functions are in UTF-8, the
502 * GLib file name encoding. Unicode characters that are not part of
503 * the system codepage passed in these arguments will be correctly
504 * available in the spawned program only if it uses wide character API
505 * to retrieve its command line. For C programs built with Microsoft's
506 * tools it is enough to make the program have a wmain() instead of
507 * main(). wmain() has a wide character argument vector as parameter.
509 * At least currently, mingw doesn't support wmain(), so if you use
510 * mingw to develop the spawned program, it should call
511 * g_win32_get_command_line() to get arguments in UTF-8.
513 * On Windows the low-level child process creation API CreateProcess()
514 * doesn't use argument vectors, but a command line. The C runtime
515 * library's spawn*() family of functions (which g_spawn_async_with_pipes()
516 * eventually calls) paste the argument vector elements together into
517 * a command line, and the C runtime startup code does a corresponding
518 * reconstruction of an argument vector from the command line, to be
519 * passed to main(). Complications arise when you have argument vector
520 * elements that contain spaces of double quotes. The spawn*() functions
521 * don't do any quoting or escaping, but on the other hand the startup
522 * code does do unquoting and unescaping in order to enable receiving
523 * arguments with embedded spaces or double quotes. To work around this
524 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
525 * argument vector elements that need it before calling the C runtime
526 * spawn() function.
528 * The returned @child_pid on Windows is a handle to the child
529 * process, not its identifier. Process handles and process
530 * identifiers are different concepts on Windows.
532 * @envp is a %NULL-terminated array of strings, where each string
533 * has the form `KEY=VALUE`. This will become the child's environment.
534 * If @envp is %NULL, the child inherits its parent's environment.
536 * @flags should be the bitwise OR of any flags you want to affect the
537 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
538 * child will not automatically be reaped; you must use a child watch to
539 * be notified about the death of the child process. Eventually you must
540 * call g_spawn_close_pid() on the @child_pid, in order to free
541 * resources which may be associated with the child process. (On Unix,
542 * using a child watch is equivalent to calling waitpid() or handling
543 * the %SIGCHLD signal manually. On Windows, calling g_spawn_close_pid()
544 * is equivalent to calling CloseHandle() on the process handle returned
545 * in @child_pid). See g_child_watch_add().
547 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
548 * descriptors will be inherited by the child; otherwise all descriptors
549 * except stdin/stdout/stderr will be closed before calling exec() in
550 * the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
551 * absolute path, it will be looked for in the `PATH` environment
552 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
553 * absolute path, it will be looked for in the `PATH` variable from
554 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
555 * are used, the value from @envp takes precedence over the environment.
556 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
557 * will be discarded, instead of going to the same location as the parent's
558 * standard output. If you use this flag, @standard_output must be %NULL.
559 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
560 * will be discarded, instead of going to the same location as the parent's
561 * standard error. If you use this flag, @standard_error must be %NULL.
562 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
563 * standard input (by default, the child's standard input is attached to
564 * /dev/null). If you use this flag, @standard_input must be %NULL.
565 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
566 * the file to execute, while the remaining elements are the actual
567 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
568 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
570 * @child_setup and @user_data are a function and user data. On POSIX
571 * platforms, the function is called in the child after GLib has
572 * performed all the setup it plans to perform (including creating
573 * pipes, closing file descriptors, etc.) but before calling exec().
574 * That is, @child_setup is called just before calling exec() in the
575 * child. Obviously actions taken in this function will only affect
576 * the child, not the parent.
578 * On Windows, there is no separate fork() and exec() functionality.
579 * Child processes are created and run with a single API call,
580 * CreateProcess(). There is no sensible thing @child_setup
581 * could be used for on Windows so it is ignored and not called.
583 * If non-%NULL, @child_pid will on Unix be filled with the child's
584 * process ID. You can use the process ID to send signals to the child,
585 * or to use g_child_watch_add() (or waitpid()) if you specified the
586 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
587 * filled with a handle to the child process only if you specified the
588 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
589 * process using the Win32 API, for example wait for its termination
590 * with the WaitFor*() functions, or examine its exit code with
591 * GetExitCodeProcess(). You should close the handle with CloseHandle()
592 * or g_spawn_close_pid() when you no longer need it.
594 * If non-%NULL, the @standard_input, @standard_output, @standard_error
595 * locations will be filled with file descriptors for writing to the child's
596 * standard input or reading from its standard output or standard error.
597 * The caller of g_spawn_async_with_pipes() must close these file descriptors
598 * when they are no longer in use. If these parameters are %NULL, the
599 * corresponding pipe won't be created.
601 * If @standard_input is NULL, the child's standard input is attached to
602 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
604 * If @standard_error is NULL, the child's standard error goes to the same
605 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
606 * is set.
608 * If @standard_output is NULL, the child's standard output goes to the same
609 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
610 * is set.
612 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
613 * If an error is set, the function returns %FALSE. Errors are reported
614 * even if they occur in the child (for example if the executable in
615 * @argv[0] is not found). Typically the `message` field of returned
616 * errors should be displayed to users. Possible errors are those from
617 * the #G_SPAWN_ERROR domain.
619 * If an error occurs, @child_pid, @standard_input, @standard_output,
620 * and @standard_error will not be filled with valid values.
622 * If @child_pid is not %NULL and an error does not occur then the returned
623 * process reference must be closed using g_spawn_close_pid().
625 * If you are writing a GTK+ application, and the program you
626 * are spawning is a graphical application, too, then you may
627 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
628 * the spawned program opens its windows on the right screen.
630 * Returns: %TRUE on success, %FALSE if an error was set
632 gboolean
633 g_spawn_async_with_pipes (const gchar *working_directory,
634 gchar **argv,
635 gchar **envp,
636 GSpawnFlags flags,
637 GSpawnChildSetupFunc child_setup,
638 gpointer user_data,
639 GPid *child_pid,
640 gint *standard_input,
641 gint *standard_output,
642 gint *standard_error,
643 GError **error)
645 g_return_val_if_fail (argv != NULL, FALSE);
646 g_return_val_if_fail (standard_output == NULL ||
647 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
648 g_return_val_if_fail (standard_error == NULL ||
649 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
650 /* can't inherit stdin if we have an input pipe. */
651 g_return_val_if_fail (standard_input == NULL ||
652 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
654 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
655 working_directory,
656 argv,
657 envp,
658 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
659 (flags & G_SPAWN_SEARCH_PATH) != 0,
660 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
661 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
662 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
663 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
664 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
665 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
666 child_setup,
667 user_data,
668 child_pid,
669 standard_input,
670 standard_output,
671 standard_error,
672 error);
676 * g_spawn_command_line_sync:
677 * @command_line: a command line
678 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output
679 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child errors
680 * @exit_status: (out) (optional): return location for child exit status, as returned by waitpid()
681 * @error: return location for errors
683 * A simple version of g_spawn_sync() with little-used parameters
684 * removed, taking a command line instead of an argument vector. See
685 * g_spawn_sync() for full details. @command_line will be parsed by
686 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
687 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
688 * implications, so consider using g_spawn_sync() directly if
689 * appropriate. Possible errors are those from g_spawn_sync() and those
690 * from g_shell_parse_argv().
692 * If @exit_status is non-%NULL, the platform-specific exit status of
693 * the child is stored there; see the documentation of
694 * g_spawn_check_exit_status() for how to use and interpret this.
696 * On Windows, please note the implications of g_shell_parse_argv()
697 * parsing @command_line. Parsing is done according to Unix shell rules, not
698 * Windows command interpreter rules.
699 * Space is a separator, and backslashes are
700 * special. Thus you cannot simply pass a @command_line containing
701 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
702 * the backslashes will be eaten, and the space will act as a
703 * separator. You need to enclose such paths with single quotes, like
704 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
706 * Returns: %TRUE on success, %FALSE if an error was set
708 gboolean
709 g_spawn_command_line_sync (const gchar *command_line,
710 gchar **standard_output,
711 gchar **standard_error,
712 gint *exit_status,
713 GError **error)
715 gboolean retval;
716 gchar **argv = NULL;
718 g_return_val_if_fail (command_line != NULL, FALSE);
720 if (!g_shell_parse_argv (command_line,
721 NULL, &argv,
722 error))
723 return FALSE;
725 retval = g_spawn_sync (NULL,
726 argv,
727 NULL,
728 G_SPAWN_SEARCH_PATH,
729 NULL,
730 NULL,
731 standard_output,
732 standard_error,
733 exit_status,
734 error);
735 g_strfreev (argv);
737 return retval;
741 * g_spawn_command_line_async:
742 * @command_line: a command line
743 * @error: return location for errors
745 * A simple version of g_spawn_async() that parses a command line with
746 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
747 * command line in the background. Unlike g_spawn_async(), the
748 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
749 * that %G_SPAWN_SEARCH_PATH can have security implications, so
750 * consider using g_spawn_async() directly if appropriate. Possible
751 * errors are those from g_shell_parse_argv() and g_spawn_async().
753 * The same concerns on Windows apply as for g_spawn_command_line_sync().
755 * Returns: %TRUE on success, %FALSE if error is set
757 gboolean
758 g_spawn_command_line_async (const gchar *command_line,
759 GError **error)
761 gboolean retval;
762 gchar **argv = NULL;
764 g_return_val_if_fail (command_line != NULL, FALSE);
766 if (!g_shell_parse_argv (command_line,
767 NULL, &argv,
768 error))
769 return FALSE;
771 retval = g_spawn_async (NULL,
772 argv,
773 NULL,
774 G_SPAWN_SEARCH_PATH,
775 NULL,
776 NULL,
777 NULL,
778 error);
779 g_strfreev (argv);
781 return retval;
785 * g_spawn_check_exit_status:
786 * @exit_status: An exit code as returned from g_spawn_sync()
787 * @error: a #GError
789 * Set @error if @exit_status indicates the child exited abnormally
790 * (e.g. with a nonzero exit code, or via a fatal signal).
792 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
793 * exit status for subprocesses encoded in a platform-specific way.
794 * On Unix, this is guaranteed to be in the same format waitpid() returns,
795 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
797 * Prior to the introduction of this function in GLib 2.34, interpreting
798 * @exit_status required use of platform-specific APIs, which is problematic
799 * for software using GLib as a cross-platform layer.
801 * Additionally, many programs simply want to determine whether or not
802 * the child exited successfully, and either propagate a #GError or
803 * print a message to standard error. In that common case, this function
804 * can be used. Note that the error message in @error will contain
805 * human-readable information about the exit status.
807 * The @domain and @code of @error have special semantics in the case
808 * where the process has an "exit code", as opposed to being killed by
809 * a signal. On Unix, this happens if WIFEXITED() would be true of
810 * @exit_status. On Windows, it is always the case.
812 * The special semantics are that the actual exit code will be the
813 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
814 * This allows you to differentiate between different exit codes.
816 * If the process was terminated by some means other than an exit
817 * status, the domain will be %G_SPAWN_ERROR, and the code will be
818 * %G_SPAWN_ERROR_FAILED.
820 * This function just offers convenience; you can of course also check
821 * the available platform via a macro such as %G_OS_UNIX, and use
822 * WIFEXITED() and WEXITSTATUS() on @exit_status directly. Do not attempt
823 * to scan or parse the error message string; it may be translated and/or
824 * change in future versions of GLib.
826 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
827 * @error will be set)
829 * Since: 2.34
831 gboolean
832 g_spawn_check_exit_status (gint exit_status,
833 GError **error)
835 gboolean ret = FALSE;
837 if (WIFEXITED (exit_status))
839 if (WEXITSTATUS (exit_status) != 0)
841 g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (exit_status),
842 _("Child process exited with code %ld"),
843 (long) WEXITSTATUS (exit_status));
844 goto out;
847 else if (WIFSIGNALED (exit_status))
849 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
850 _("Child process killed by signal %ld"),
851 (long) WTERMSIG (exit_status));
852 goto out;
854 else if (WIFSTOPPED (exit_status))
856 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
857 _("Child process stopped by signal %ld"),
858 (long) WSTOPSIG (exit_status));
859 goto out;
861 else
863 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
864 _("Child process exited abnormally"));
865 goto out;
868 ret = TRUE;
869 out:
870 return ret;
873 static gint
874 exec_err_to_g_error (gint en)
876 switch (en)
878 #ifdef EACCES
879 case EACCES:
880 return G_SPAWN_ERROR_ACCES;
881 break;
882 #endif
884 #ifdef EPERM
885 case EPERM:
886 return G_SPAWN_ERROR_PERM;
887 break;
888 #endif
890 #ifdef E2BIG
891 case E2BIG:
892 return G_SPAWN_ERROR_TOO_BIG;
893 break;
894 #endif
896 #ifdef ENOEXEC
897 case ENOEXEC:
898 return G_SPAWN_ERROR_NOEXEC;
899 break;
900 #endif
902 #ifdef ENAMETOOLONG
903 case ENAMETOOLONG:
904 return G_SPAWN_ERROR_NAMETOOLONG;
905 break;
906 #endif
908 #ifdef ENOENT
909 case ENOENT:
910 return G_SPAWN_ERROR_NOENT;
911 break;
912 #endif
914 #ifdef ENOMEM
915 case ENOMEM:
916 return G_SPAWN_ERROR_NOMEM;
917 break;
918 #endif
920 #ifdef ENOTDIR
921 case ENOTDIR:
922 return G_SPAWN_ERROR_NOTDIR;
923 break;
924 #endif
926 #ifdef ELOOP
927 case ELOOP:
928 return G_SPAWN_ERROR_LOOP;
929 break;
930 #endif
932 #ifdef ETXTBUSY
933 case ETXTBUSY:
934 return G_SPAWN_ERROR_TXTBUSY;
935 break;
936 #endif
938 #ifdef EIO
939 case EIO:
940 return G_SPAWN_ERROR_IO;
941 break;
942 #endif
944 #ifdef ENFILE
945 case ENFILE:
946 return G_SPAWN_ERROR_NFILE;
947 break;
948 #endif
950 #ifdef EMFILE
951 case EMFILE:
952 return G_SPAWN_ERROR_MFILE;
953 break;
954 #endif
956 #ifdef EINVAL
957 case EINVAL:
958 return G_SPAWN_ERROR_INVAL;
959 break;
960 #endif
962 #ifdef EISDIR
963 case EISDIR:
964 return G_SPAWN_ERROR_ISDIR;
965 break;
966 #endif
968 #ifdef ELIBBAD
969 case ELIBBAD:
970 return G_SPAWN_ERROR_LIBBAD;
971 break;
972 #endif
974 default:
975 return G_SPAWN_ERROR_FAILED;
976 break;
980 static gssize
981 write_all (gint fd, gconstpointer vbuf, gsize to_write)
983 gchar *buf = (gchar *) vbuf;
985 while (to_write > 0)
987 gssize count = write (fd, buf, to_write);
988 if (count < 0)
990 if (errno != EINTR)
991 return FALSE;
993 else
995 to_write -= count;
996 buf += count;
1000 return TRUE;
1003 G_GNUC_NORETURN
1004 static void
1005 write_err_and_exit (gint fd, gint msg)
1007 gint en = errno;
1009 write_all (fd, &msg, sizeof(msg));
1010 write_all (fd, &en, sizeof(en));
1012 _exit (1);
1015 static int
1016 set_cloexec (void *data, gint fd)
1018 if (fd >= GPOINTER_TO_INT (data))
1019 fcntl (fd, F_SETFD, FD_CLOEXEC);
1021 return 0;
1024 #ifndef HAVE_FDWALK
1025 static int
1026 fdwalk (int (*cb)(void *data, int fd), void *data)
1028 gint open_max;
1029 gint fd;
1030 gint res = 0;
1032 #ifdef HAVE_SYS_RESOURCE_H
1033 struct rlimit rl;
1034 #endif
1036 #ifdef __linux__
1037 DIR *d;
1039 if ((d = opendir("/proc/self/fd"))) {
1040 struct dirent *de;
1042 while ((de = readdir(d))) {
1043 glong l;
1044 gchar *e = NULL;
1046 if (de->d_name[0] == '.')
1047 continue;
1049 errno = 0;
1050 l = strtol(de->d_name, &e, 10);
1051 if (errno != 0 || !e || *e)
1052 continue;
1054 fd = (gint) l;
1056 if ((glong) fd != l)
1057 continue;
1059 if (fd == dirfd(d))
1060 continue;
1062 if ((res = cb (data, fd)) != 0)
1063 break;
1066 closedir(d);
1067 return res;
1070 /* If /proc is not mounted or not accessible we fall back to the old
1071 * rlimit trick */
1073 #endif
1075 #ifdef HAVE_SYS_RESOURCE_H
1077 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1078 open_max = rl.rlim_max;
1079 else
1080 #endif
1081 open_max = sysconf (_SC_OPEN_MAX);
1083 for (fd = 0; fd < open_max; fd++)
1084 if ((res = cb (data, fd)) != 0)
1085 break;
1087 return res;
1089 #endif
1091 static gint
1092 sane_dup2 (gint fd1, gint fd2)
1094 gint ret;
1096 retry:
1097 ret = dup2 (fd1, fd2);
1098 if (ret < 0 && errno == EINTR)
1099 goto retry;
1101 return ret;
1104 static gint
1105 sane_open (const char *path, gint mode)
1107 gint ret;
1109 retry:
1110 ret = open (path, mode);
1111 if (ret < 0 && errno == EINTR)
1112 goto retry;
1114 return ret;
1117 enum
1119 CHILD_CHDIR_FAILED,
1120 CHILD_EXEC_FAILED,
1121 CHILD_DUP2_FAILED,
1122 CHILD_FORK_FAILED
1125 static void
1126 do_exec (gint child_err_report_fd,
1127 gint stdin_fd,
1128 gint stdout_fd,
1129 gint stderr_fd,
1130 const gchar *working_directory,
1131 gchar **argv,
1132 gchar **envp,
1133 gboolean close_descriptors,
1134 gboolean search_path,
1135 gboolean search_path_from_envp,
1136 gboolean stdout_to_null,
1137 gboolean stderr_to_null,
1138 gboolean child_inherits_stdin,
1139 gboolean file_and_argv_zero,
1140 GSpawnChildSetupFunc child_setup,
1141 gpointer user_data)
1143 if (working_directory && chdir (working_directory) < 0)
1144 write_err_and_exit (child_err_report_fd,
1145 CHILD_CHDIR_FAILED);
1147 /* Close all file descriptors but stdin stdout and stderr as
1148 * soon as we exec. Note that this includes
1149 * child_err_report_fd, which keeps the parent from blocking
1150 * forever on the other end of that pipe.
1152 if (close_descriptors)
1154 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1156 else
1158 /* We need to do child_err_report_fd anyway */
1159 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1162 /* Redirect pipes as required */
1164 if (stdin_fd >= 0)
1166 /* dup2 can't actually fail here I don't think */
1168 if (sane_dup2 (stdin_fd, 0) < 0)
1169 write_err_and_exit (child_err_report_fd,
1170 CHILD_DUP2_FAILED);
1172 /* ignore this if it doesn't work */
1173 close_and_invalidate (&stdin_fd);
1175 else if (!child_inherits_stdin)
1177 /* Keep process from blocking on a read of stdin */
1178 gint read_null = open ("/dev/null", O_RDONLY);
1179 g_assert (read_null != -1);
1180 sane_dup2 (read_null, 0);
1181 close_and_invalidate (&read_null);
1184 if (stdout_fd >= 0)
1186 /* dup2 can't actually fail here I don't think */
1188 if (sane_dup2 (stdout_fd, 1) < 0)
1189 write_err_and_exit (child_err_report_fd,
1190 CHILD_DUP2_FAILED);
1192 /* ignore this if it doesn't work */
1193 close_and_invalidate (&stdout_fd);
1195 else if (stdout_to_null)
1197 gint write_null = sane_open ("/dev/null", O_WRONLY);
1198 g_assert (write_null != -1);
1199 sane_dup2 (write_null, 1);
1200 close_and_invalidate (&write_null);
1203 if (stderr_fd >= 0)
1205 /* dup2 can't actually fail here I don't think */
1207 if (sane_dup2 (stderr_fd, 2) < 0)
1208 write_err_and_exit (child_err_report_fd,
1209 CHILD_DUP2_FAILED);
1211 /* ignore this if it doesn't work */
1212 close_and_invalidate (&stderr_fd);
1214 else if (stderr_to_null)
1216 gint write_null = sane_open ("/dev/null", O_WRONLY);
1217 sane_dup2 (write_null, 2);
1218 close_and_invalidate (&write_null);
1221 /* Call user function just before we exec */
1222 if (child_setup)
1224 (* child_setup) (user_data);
1227 g_execute (argv[0],
1228 file_and_argv_zero ? argv + 1 : argv,
1229 envp, search_path, search_path_from_envp);
1231 /* Exec failed */
1232 write_err_and_exit (child_err_report_fd,
1233 CHILD_EXEC_FAILED);
1236 static gboolean
1237 read_ints (int fd,
1238 gint* buf,
1239 gint n_ints_in_buf,
1240 gint *n_ints_read,
1241 GError **error)
1243 gsize bytes = 0;
1245 while (TRUE)
1247 gssize chunk;
1249 if (bytes >= sizeof(gint)*2)
1250 break; /* give up, who knows what happened, should not be
1251 * possible.
1254 again:
1255 chunk = read (fd,
1256 ((gchar*)buf) + bytes,
1257 sizeof(gint) * n_ints_in_buf - bytes);
1258 if (chunk < 0 && errno == EINTR)
1259 goto again;
1261 if (chunk < 0)
1263 int errsv = errno;
1265 /* Some weird shit happened, bail out */
1266 g_set_error (error,
1267 G_SPAWN_ERROR,
1268 G_SPAWN_ERROR_FAILED,
1269 _("Failed to read from child pipe (%s)"),
1270 g_strerror (errsv));
1272 return FALSE;
1274 else if (chunk == 0)
1275 break; /* EOF */
1276 else /* chunk > 0 */
1277 bytes += chunk;
1280 *n_ints_read = (gint)(bytes / sizeof(gint));
1282 return TRUE;
1285 static gboolean
1286 fork_exec_with_pipes (gboolean intermediate_child,
1287 const gchar *working_directory,
1288 gchar **argv,
1289 gchar **envp,
1290 gboolean close_descriptors,
1291 gboolean search_path,
1292 gboolean search_path_from_envp,
1293 gboolean stdout_to_null,
1294 gboolean stderr_to_null,
1295 gboolean child_inherits_stdin,
1296 gboolean file_and_argv_zero,
1297 gboolean cloexec_pipes,
1298 GSpawnChildSetupFunc child_setup,
1299 gpointer user_data,
1300 GPid *child_pid,
1301 gint *standard_input,
1302 gint *standard_output,
1303 gint *standard_error,
1304 GError **error)
1306 GPid pid = -1;
1307 gint stdin_pipe[2] = { -1, -1 };
1308 gint stdout_pipe[2] = { -1, -1 };
1309 gint stderr_pipe[2] = { -1, -1 };
1310 gint child_err_report_pipe[2] = { -1, -1 };
1311 gint child_pid_report_pipe[2] = { -1, -1 };
1312 guint pipe_flags = cloexec_pipes ? FD_CLOEXEC : 0;
1313 gint status;
1315 if (!g_unix_open_pipe (child_err_report_pipe, pipe_flags, error))
1316 return FALSE;
1318 if (intermediate_child && !g_unix_open_pipe (child_pid_report_pipe, pipe_flags, error))
1319 goto cleanup_and_fail;
1321 if (standard_input && !g_unix_open_pipe (stdin_pipe, pipe_flags, error))
1322 goto cleanup_and_fail;
1324 if (standard_output && !g_unix_open_pipe (stdout_pipe, pipe_flags, error))
1325 goto cleanup_and_fail;
1327 if (standard_error && !g_unix_open_pipe (stderr_pipe, FD_CLOEXEC, error))
1328 goto cleanup_and_fail;
1330 pid = fork ();
1332 if (pid < 0)
1334 int errsv = errno;
1336 g_set_error (error,
1337 G_SPAWN_ERROR,
1338 G_SPAWN_ERROR_FORK,
1339 _("Failed to fork (%s)"),
1340 g_strerror (errsv));
1342 goto cleanup_and_fail;
1344 else if (pid == 0)
1346 /* Immediate child. This may or may not be the child that
1347 * actually execs the new process.
1350 /* Reset some signal handlers that we may use */
1351 signal (SIGCHLD, SIG_DFL);
1352 signal (SIGINT, SIG_DFL);
1353 signal (SIGTERM, SIG_DFL);
1354 signal (SIGHUP, SIG_DFL);
1356 /* Be sure we crash if the parent exits
1357 * and we write to the err_report_pipe
1359 signal (SIGPIPE, SIG_DFL);
1361 /* Close the parent's end of the pipes;
1362 * not needed in the close_descriptors case,
1363 * though
1365 close_and_invalidate (&child_err_report_pipe[0]);
1366 close_and_invalidate (&child_pid_report_pipe[0]);
1367 close_and_invalidate (&stdin_pipe[1]);
1368 close_and_invalidate (&stdout_pipe[0]);
1369 close_and_invalidate (&stderr_pipe[0]);
1371 if (intermediate_child)
1373 /* We need to fork an intermediate child that launches the
1374 * final child. The purpose of the intermediate child
1375 * is to exit, so we can waitpid() it immediately.
1376 * Then the grandchild will not become a zombie.
1378 GPid grandchild_pid;
1380 grandchild_pid = fork ();
1382 if (grandchild_pid < 0)
1384 /* report -1 as child PID */
1385 write_all (child_pid_report_pipe[1], &grandchild_pid,
1386 sizeof(grandchild_pid));
1388 write_err_and_exit (child_err_report_pipe[1],
1389 CHILD_FORK_FAILED);
1391 else if (grandchild_pid == 0)
1393 close_and_invalidate (&child_pid_report_pipe[1]);
1394 do_exec (child_err_report_pipe[1],
1395 stdin_pipe[0],
1396 stdout_pipe[1],
1397 stderr_pipe[1],
1398 working_directory,
1399 argv,
1400 envp,
1401 close_descriptors,
1402 search_path,
1403 search_path_from_envp,
1404 stdout_to_null,
1405 stderr_to_null,
1406 child_inherits_stdin,
1407 file_and_argv_zero,
1408 child_setup,
1409 user_data);
1411 else
1413 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1414 close_and_invalidate (&child_pid_report_pipe[1]);
1416 _exit (0);
1419 else
1421 /* Just run the child.
1424 do_exec (child_err_report_pipe[1],
1425 stdin_pipe[0],
1426 stdout_pipe[1],
1427 stderr_pipe[1],
1428 working_directory,
1429 argv,
1430 envp,
1431 close_descriptors,
1432 search_path,
1433 search_path_from_envp,
1434 stdout_to_null,
1435 stderr_to_null,
1436 child_inherits_stdin,
1437 file_and_argv_zero,
1438 child_setup,
1439 user_data);
1442 else
1444 /* Parent */
1446 gint buf[2];
1447 gint n_ints = 0;
1449 /* Close the uncared-about ends of the pipes */
1450 close_and_invalidate (&child_err_report_pipe[1]);
1451 close_and_invalidate (&child_pid_report_pipe[1]);
1452 close_and_invalidate (&stdin_pipe[0]);
1453 close_and_invalidate (&stdout_pipe[1]);
1454 close_and_invalidate (&stderr_pipe[1]);
1456 /* If we had an intermediate child, reap it */
1457 if (intermediate_child)
1459 wait_again:
1460 if (waitpid (pid, &status, 0) < 0)
1462 if (errno == EINTR)
1463 goto wait_again;
1464 else if (errno == ECHILD)
1465 ; /* do nothing, child already reaped */
1466 else
1467 g_warning ("waitpid() should not fail in "
1468 "'fork_exec_with_pipes'");
1473 if (!read_ints (child_err_report_pipe[0],
1474 buf, 2, &n_ints,
1475 error))
1476 goto cleanup_and_fail;
1478 if (n_ints >= 2)
1480 /* Error from the child. */
1482 switch (buf[0])
1484 case CHILD_CHDIR_FAILED:
1485 g_set_error (error,
1486 G_SPAWN_ERROR,
1487 G_SPAWN_ERROR_CHDIR,
1488 _("Failed to change to directory “%s” (%s)"),
1489 working_directory,
1490 g_strerror (buf[1]));
1492 break;
1494 case CHILD_EXEC_FAILED:
1495 g_set_error (error,
1496 G_SPAWN_ERROR,
1497 exec_err_to_g_error (buf[1]),
1498 _("Failed to execute child process “%s” (%s)"),
1499 argv[0],
1500 g_strerror (buf[1]));
1502 break;
1504 case CHILD_DUP2_FAILED:
1505 g_set_error (error,
1506 G_SPAWN_ERROR,
1507 G_SPAWN_ERROR_FAILED,
1508 _("Failed to redirect output or input of child process (%s)"),
1509 g_strerror (buf[1]));
1511 break;
1513 case CHILD_FORK_FAILED:
1514 g_set_error (error,
1515 G_SPAWN_ERROR,
1516 G_SPAWN_ERROR_FORK,
1517 _("Failed to fork child process (%s)"),
1518 g_strerror (buf[1]));
1519 break;
1521 default:
1522 g_set_error (error,
1523 G_SPAWN_ERROR,
1524 G_SPAWN_ERROR_FAILED,
1525 _("Unknown error executing child process “%s”"),
1526 argv[0]);
1527 break;
1530 goto cleanup_and_fail;
1533 /* Get child pid from intermediate child pipe. */
1534 if (intermediate_child)
1536 n_ints = 0;
1538 if (!read_ints (child_pid_report_pipe[0],
1539 buf, 1, &n_ints, error))
1540 goto cleanup_and_fail;
1542 if (n_ints < 1)
1544 int errsv = errno;
1546 g_set_error (error,
1547 G_SPAWN_ERROR,
1548 G_SPAWN_ERROR_FAILED,
1549 _("Failed to read enough data from child pid pipe (%s)"),
1550 g_strerror (errsv));
1551 goto cleanup_and_fail;
1553 else
1555 /* we have the child pid */
1556 pid = buf[0];
1560 /* Success against all odds! return the information */
1561 close_and_invalidate (&child_err_report_pipe[0]);
1562 close_and_invalidate (&child_pid_report_pipe[0]);
1564 if (child_pid)
1565 *child_pid = pid;
1567 if (standard_input)
1568 *standard_input = stdin_pipe[1];
1569 if (standard_output)
1570 *standard_output = stdout_pipe[0];
1571 if (standard_error)
1572 *standard_error = stderr_pipe[0];
1574 return TRUE;
1577 cleanup_and_fail:
1579 /* There was an error from the Child, reap the child to avoid it being
1580 a zombie.
1583 if (pid > 0)
1585 wait_failed:
1586 if (waitpid (pid, NULL, 0) < 0)
1588 if (errno == EINTR)
1589 goto wait_failed;
1590 else if (errno == ECHILD)
1591 ; /* do nothing, child already reaped */
1592 else
1593 g_warning ("waitpid() should not fail in "
1594 "'fork_exec_with_pipes'");
1598 close_and_invalidate (&child_err_report_pipe[0]);
1599 close_and_invalidate (&child_err_report_pipe[1]);
1600 close_and_invalidate (&child_pid_report_pipe[0]);
1601 close_and_invalidate (&child_pid_report_pipe[1]);
1602 close_and_invalidate (&stdin_pipe[0]);
1603 close_and_invalidate (&stdin_pipe[1]);
1604 close_and_invalidate (&stdout_pipe[0]);
1605 close_and_invalidate (&stdout_pipe[1]);
1606 close_and_invalidate (&stderr_pipe[0]);
1607 close_and_invalidate (&stderr_pipe[1]);
1609 return FALSE;
1612 /* Based on execvp from GNU C Library */
1614 static void
1615 script_execute (const gchar *file,
1616 gchar **argv,
1617 gchar **envp)
1619 /* Count the arguments. */
1620 int argc = 0;
1621 while (argv[argc])
1622 ++argc;
1624 /* Construct an argument list for the shell. */
1626 gchar **new_argv;
1628 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1630 new_argv[0] = (char *) "/bin/sh";
1631 new_argv[1] = (char *) file;
1632 while (argc > 0)
1634 new_argv[argc + 1] = argv[argc];
1635 --argc;
1638 /* Execute the shell. */
1639 if (envp)
1640 execve (new_argv[0], new_argv, envp);
1641 else
1642 execv (new_argv[0], new_argv);
1644 g_free (new_argv);
1648 static gchar*
1649 my_strchrnul (const gchar *str, gchar c)
1651 gchar *p = (gchar*) str;
1652 while (*p && (*p != c))
1653 ++p;
1655 return p;
1658 static gint
1659 g_execute (const gchar *file,
1660 gchar **argv,
1661 gchar **envp,
1662 gboolean search_path,
1663 gboolean search_path_from_envp)
1665 if (*file == '\0')
1667 /* We check the simple case first. */
1668 errno = ENOENT;
1669 return -1;
1672 if (!(search_path || search_path_from_envp) || strchr (file, '/') != NULL)
1674 /* Don't search when it contains a slash. */
1675 if (envp)
1676 execve (file, argv, envp);
1677 else
1678 execv (file, argv);
1680 if (errno == ENOEXEC)
1681 script_execute (file, argv, envp);
1683 else
1685 gboolean got_eacces = 0;
1686 const gchar *path, *p;
1687 gchar *name, *freeme;
1688 gsize len;
1689 gsize pathlen;
1691 path = NULL;
1692 if (search_path_from_envp)
1693 path = g_environ_getenv (envp, "PATH");
1694 if (search_path && path == NULL)
1695 path = g_getenv ("PATH");
1697 if (path == NULL)
1699 /* There is no 'PATH' in the environment. The default
1700 * search path in libc is the current directory followed by
1701 * the path 'confstr' returns for '_CS_PATH'.
1704 /* In GLib we put . last, for security, and don't use the
1705 * unportable confstr(); UNIX98 does not actually specify
1706 * what to search if PATH is unset. POSIX may, dunno.
1709 path = "/bin:/usr/bin:.";
1712 len = strlen (file) + 1;
1713 pathlen = strlen (path);
1714 freeme = name = g_malloc (pathlen + len + 1);
1716 /* Copy the file name at the top, including '\0' */
1717 memcpy (name + pathlen + 1, file, len);
1718 name = name + pathlen;
1719 /* And add the slash before the filename */
1720 *name = '/';
1722 p = path;
1725 char *startp;
1727 path = p;
1728 p = my_strchrnul (path, ':');
1730 if (p == path)
1731 /* Two adjacent colons, or a colon at the beginning or the end
1732 * of 'PATH' means to search the current directory.
1734 startp = name + 1;
1735 else
1736 startp = memcpy (name - (p - path), path, p - path);
1738 /* Try to execute this name. If it works, execv will not return. */
1739 if (envp)
1740 execve (startp, argv, envp);
1741 else
1742 execv (startp, argv);
1744 if (errno == ENOEXEC)
1745 script_execute (startp, argv, envp);
1747 switch (errno)
1749 case EACCES:
1750 /* Record the we got a 'Permission denied' error. If we end
1751 * up finding no executable we can use, we want to diagnose
1752 * that we did find one but were denied access.
1754 got_eacces = TRUE;
1756 /* FALL THRU */
1758 case ENOENT:
1759 #ifdef ESTALE
1760 case ESTALE:
1761 #endif
1762 #ifdef ENOTDIR
1763 case ENOTDIR:
1764 #endif
1765 /* Those errors indicate the file is missing or not executable
1766 * by us, in which case we want to just try the next path
1767 * directory.
1769 break;
1771 case ENODEV:
1772 case ETIMEDOUT:
1773 /* Some strange filesystems like AFS return even
1774 * stranger error numbers. They cannot reasonably mean anything
1775 * else so ignore those, too.
1777 break;
1779 default:
1780 /* Some other error means we found an executable file, but
1781 * something went wrong executing it; return the error to our
1782 * caller.
1784 g_free (freeme);
1785 return -1;
1788 while (*p++ != '\0');
1790 /* We tried every element and none of them worked. */
1791 if (got_eacces)
1792 /* At least one failure was due to permissions, so report that
1793 * error.
1795 errno = EACCES;
1797 g_free (freeme);
1800 /* Return the error from the last attempt (probably ENOENT). */
1801 return -1;
1805 * g_spawn_close_pid:
1806 * @pid: The process reference to close
1808 * On some platforms, notably Windows, the #GPid type represents a resource
1809 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1810 * is provided for this purpose. It should be used on all platforms, even
1811 * though it doesn't do anything under UNIX.
1813 void
1814 g_spawn_close_pid (GPid pid)