gatomic: Add missing new line in API doc comment
[glib.git] / glib / gspawn.c
blob3cd43a4e4407059046f2983705c59204b7f938d3
1 /* gspawn.c - Process launching
3 * Copyright 2000 Red Hat, Inc.
4 * g_execvpe implementation based on GNU libc execvp:
5 * Copyright 1991, 92, 95, 96, 97, 98, 99 Free Software Foundation, Inc.
7 * GLib is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2 of the
10 * License, or (at your option) any later version.
12 * GLib is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with GLib; see the file COPYING.LIB. If not, write
19 * to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
23 #include "config.h"
25 #include <sys/time.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <string.h>
33 #include <stdlib.h> /* for fdwalk */
34 #include <dirent.h>
36 #ifdef HAVE_SYS_SELECT_H
37 #include <sys/select.h>
38 #endif /* HAVE_SYS_SELECT_H */
40 #ifdef HAVE_SYS_RESOURCE_H
41 #include <sys/resource.h>
42 #endif /* HAVE_SYS_RESOURCE_H */
44 #include "gspawn.h"
45 #include "gthread.h"
46 #include "glib/gstdio.h"
48 #include "genviron.h"
49 #include "gmem.h"
50 #include "gshell.h"
51 #include "gstring.h"
52 #include "gstrfuncs.h"
53 #include "gtestutils.h"
54 #include "gutils.h"
55 #include "glibintl.h"
56 #include "glib-unix.h"
58 /**
59 * SECTION:spawn
60 * @Short_description: process launching
61 * @Title: Spawning Processes
63 * GLib supports spawning of processes with an API that is more
64 * convenient than the bare UNIX fork() and exec().
66 * The g_spawn family of functions has synchronous (g_spawn_sync())
67 * and asynchronous variants (g_spawn_async(), g_spawn_async_with_pipes()),
68 * as well as convenience variants that take a complete shell-like
69 * commandline (g_spawn_command_line_sync(), g_spawn_command_line_async()).
71 * See #GSubprocess in GIO for a higher-level API that provides
72 * stream interfaces for communication with child processes.
77 static gint g_execute (const gchar *file,
78 gchar **argv,
79 gchar **envp,
80 gboolean search_path,
81 gboolean search_path_from_envp);
83 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
84 const gchar *working_directory,
85 gchar **argv,
86 gchar **envp,
87 gboolean close_descriptors,
88 gboolean search_path,
89 gboolean search_path_from_envp,
90 gboolean stdout_to_null,
91 gboolean stderr_to_null,
92 gboolean child_inherits_stdin,
93 gboolean file_and_argv_zero,
94 gboolean cloexec_pipes,
95 GSpawnChildSetupFunc child_setup,
96 gpointer user_data,
97 GPid *child_pid,
98 gint *standard_input,
99 gint *standard_output,
100 gint *standard_error,
101 GError **error);
103 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
104 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
107 * g_spawn_async:
108 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
109 * @argv: (array zero-terminated=1): child's argument vector
110 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
111 * @flags: flags from #GSpawnFlags
112 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
113 * @user_data: (closure): user data for @child_setup
114 * @child_pid: (out) (allow-none): return location for child process reference, or %NULL
115 * @error: return location for error
117 * See g_spawn_async_with_pipes() for a full description; this function
118 * simply calls the g_spawn_async_with_pipes() without any pipes.
120 * You should call g_spawn_close_pid() on the returned child process
121 * reference when you don't need it any more.
123 * If you are writing a GTK+ application, and the program you are
124 * spawning is a graphical application, too, then you may want to
125 * use gdk_spawn_on_screen() instead to ensure that the spawned program
126 * opens its windows on the right screen.
128 * Note that the returned @child_pid on Windows is a handle to the child
129 * process and not its identifier. Process handles and process identifiers
130 * are different concepts on Windows.
132 * Returns: %TRUE on success, %FALSE if error is set
134 gboolean
135 g_spawn_async (const gchar *working_directory,
136 gchar **argv,
137 gchar **envp,
138 GSpawnFlags flags,
139 GSpawnChildSetupFunc child_setup,
140 gpointer user_data,
141 GPid *child_pid,
142 GError **error)
144 g_return_val_if_fail (argv != NULL, FALSE);
146 return g_spawn_async_with_pipes (working_directory,
147 argv, envp,
148 flags,
149 child_setup,
150 user_data,
151 child_pid,
152 NULL, NULL, NULL,
153 error);
156 /* Avoids a danger in threaded situations (calling close()
157 * on a file descriptor twice, and another thread has
158 * re-opened it since the first close)
160 static void
161 close_and_invalidate (gint *fd)
163 if (*fd < 0)
164 return;
165 else
167 (void) g_close (*fd, NULL);
168 *fd = -1;
172 /* Some versions of OS X define READ_OK in public headers */
173 #undef READ_OK
175 typedef enum
177 READ_FAILED = 0, /* FALSE */
178 READ_OK,
179 READ_EOF
180 } ReadResult;
182 static ReadResult
183 read_data (GString *str,
184 gint fd,
185 GError **error)
187 gssize bytes;
188 gchar buf[4096];
190 again:
191 bytes = read (fd, buf, 4096);
193 if (bytes == 0)
194 return READ_EOF;
195 else if (bytes > 0)
197 g_string_append_len (str, buf, bytes);
198 return READ_OK;
200 else if (errno == EINTR)
201 goto again;
202 else
204 int errsv = errno;
206 g_set_error (error,
207 G_SPAWN_ERROR,
208 G_SPAWN_ERROR_READ,
209 _("Failed to read data from child process (%s)"),
210 g_strerror (errsv));
212 return READ_FAILED;
217 * g_spawn_sync:
218 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's
219 * @argv: (array zero-terminated=1): child's argument vector
220 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's
221 * @flags: flags from #GSpawnFlags
222 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
223 * @user_data: (closure): user data for @child_setup
224 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output, or %NULL
225 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child error messages, or %NULL
226 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid(), or %NULL
227 * @error: return location for error, or %NULL
229 * Executes a child synchronously (waits for the child to exit before returning).
230 * All output from the child is stored in @standard_output and @standard_error,
231 * if those parameters are non-%NULL. Note that you must set the
232 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
233 * passing %NULL for @standard_output and @standard_error.
235 * If @exit_status is non-%NULL, the platform-specific exit status of
236 * the child is stored there; see the documentation of
237 * g_spawn_check_exit_status() for how to use and interpret this.
238 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
239 * @flags.
241 * If an error occurs, no data is returned in @standard_output,
242 * @standard_error, or @exit_status.
244 * This function calls g_spawn_async_with_pipes() internally; see that
245 * function for full details on the other parameters and details on
246 * how these functions work on Windows.
248 * Returns: %TRUE on success, %FALSE if an error was set
250 gboolean
251 g_spawn_sync (const gchar *working_directory,
252 gchar **argv,
253 gchar **envp,
254 GSpawnFlags flags,
255 GSpawnChildSetupFunc child_setup,
256 gpointer user_data,
257 gchar **standard_output,
258 gchar **standard_error,
259 gint *exit_status,
260 GError **error)
262 gint outpipe = -1;
263 gint errpipe = -1;
264 GPid pid;
265 fd_set fds;
266 gint ret;
267 GString *outstr = NULL;
268 GString *errstr = NULL;
269 gboolean failed;
270 gint status;
272 g_return_val_if_fail (argv != NULL, FALSE);
273 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
274 g_return_val_if_fail (standard_output == NULL ||
275 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
276 g_return_val_if_fail (standard_error == NULL ||
277 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
279 /* Just to ensure segfaults if callers try to use
280 * these when an error is reported.
282 if (standard_output)
283 *standard_output = NULL;
285 if (standard_error)
286 *standard_error = NULL;
288 if (!fork_exec_with_pipes (FALSE,
289 working_directory,
290 argv,
291 envp,
292 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
293 (flags & G_SPAWN_SEARCH_PATH) != 0,
294 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
295 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
296 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
297 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
298 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
299 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
300 child_setup,
301 user_data,
302 &pid,
303 NULL,
304 standard_output ? &outpipe : NULL,
305 standard_error ? &errpipe : NULL,
306 error))
307 return FALSE;
309 /* Read data from child. */
311 failed = FALSE;
313 if (outpipe >= 0)
315 outstr = g_string_new (NULL);
318 if (errpipe >= 0)
320 errstr = g_string_new (NULL);
323 /* Read data until we get EOF on both pipes. */
324 while (!failed &&
325 (outpipe >= 0 ||
326 errpipe >= 0))
328 ret = 0;
330 FD_ZERO (&fds);
331 if (outpipe >= 0)
332 FD_SET (outpipe, &fds);
333 if (errpipe >= 0)
334 FD_SET (errpipe, &fds);
336 ret = select (MAX (outpipe, errpipe) + 1,
337 &fds,
338 NULL, NULL,
339 NULL /* no timeout */);
341 if (ret < 0)
343 int errsv = errno;
345 if (errno == EINTR)
346 continue;
348 failed = TRUE;
350 g_set_error (error,
351 G_SPAWN_ERROR,
352 G_SPAWN_ERROR_READ,
353 _("Unexpected error in select() reading data from a child process (%s)"),
354 g_strerror (errsv));
356 break;
359 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
361 switch (read_data (outstr, outpipe, error))
363 case READ_FAILED:
364 failed = TRUE;
365 break;
366 case READ_EOF:
367 close_and_invalidate (&outpipe);
368 outpipe = -1;
369 break;
370 default:
371 break;
374 if (failed)
375 break;
378 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
380 switch (read_data (errstr, errpipe, error))
382 case READ_FAILED:
383 failed = TRUE;
384 break;
385 case READ_EOF:
386 close_and_invalidate (&errpipe);
387 errpipe = -1;
388 break;
389 default:
390 break;
393 if (failed)
394 break;
398 /* These should only be open still if we had an error. */
400 if (outpipe >= 0)
401 close_and_invalidate (&outpipe);
402 if (errpipe >= 0)
403 close_and_invalidate (&errpipe);
405 /* Wait for child to exit, even if we have
406 * an error pending.
408 again:
410 ret = waitpid (pid, &status, 0);
412 if (ret < 0)
414 if (errno == EINTR)
415 goto again;
416 else if (errno == ECHILD)
418 if (exit_status)
420 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.");
422 else
424 /* We don't need the exit status. */
427 else
429 if (!failed) /* avoid error pileups */
431 int errsv = errno;
433 failed = TRUE;
435 g_set_error (error,
436 G_SPAWN_ERROR,
437 G_SPAWN_ERROR_READ,
438 _("Unexpected error in waitpid() (%s)"),
439 g_strerror (errsv));
444 if (failed)
446 if (outstr)
447 g_string_free (outstr, TRUE);
448 if (errstr)
449 g_string_free (errstr, TRUE);
451 return FALSE;
453 else
455 if (exit_status)
456 *exit_status = status;
458 if (standard_output)
459 *standard_output = g_string_free (outstr, FALSE);
461 if (standard_error)
462 *standard_error = g_string_free (errstr, FALSE);
464 return TRUE;
469 * g_spawn_async_with_pipes:
470 * @working_directory: (allow-none): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
471 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding
472 * @envp: (array zero-terminated=1) (allow-none): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
473 * @flags: flags from #GSpawnFlags
474 * @child_setup: (scope async) (allow-none): function to run in the child just before exec()
475 * @user_data: (closure): user data for @child_setup
476 * @child_pid: (out) (allow-none): return location for child process ID, or %NULL
477 * @standard_input: (out) (allow-none): return location for file descriptor to write to child's stdin, or %NULL
478 * @standard_output: (out) (allow-none): return location for file descriptor to read child's stdout, or %NULL
479 * @standard_error: (out) (allow-none): return location for file descriptor to read child's stderr, or %NULL
480 * @error: return location for error
482 * Executes a child program asynchronously (your program will not
483 * block waiting for the child to exit). The child program is
484 * specified by the only argument that must be provided, @argv.
485 * @argv should be a %NULL-terminated array of strings, to be passed
486 * as the argument vector for the child. The first string in @argv
487 * is of course the name of the program to execute. By default, the
488 * name of the program must be a full path. If @flags contains the
489 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is
490 * used to search for the executable. If @flags contains the
491 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from
492 * @envp is used to search for the executable. If both the
493 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags
494 * are set, the `PATH` variable from @envp takes precedence over
495 * the environment variable.
497 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag is not
498 * used, then the program will be run from the current directory (or
499 * @working_directory, if specified); this might be unexpected or even
500 * dangerous in some cases when the current directory is world-writable.
502 * On Windows, note that all the string or string vector arguments to
503 * this function and the other g_spawn*() functions are in UTF-8, the
504 * GLib file name encoding. Unicode characters that are not part of
505 * the system codepage passed in these arguments will be correctly
506 * available in the spawned program only if it uses wide character API
507 * to retrieve its command line. For C programs built with Microsoft's
508 * tools it is enough to make the program have a wmain() instead of
509 * main(). wmain() has a wide character argument vector as parameter.
511 * At least currently, mingw doesn't support wmain(), so if you use
512 * mingw to develop the spawned program, it will have to call the
513 * undocumented function __wgetmainargs() to get the wide character
514 * argument vector and environment. See gspawn-win32-helper.c in the
515 * GLib sources or init.c in the mingw runtime sources for a prototype
516 * for that function. Alternatively, you can retrieve the Win32 system
517 * level wide character command line passed to the spawned program
518 * using the GetCommandLineW() function.
520 * On Windows the low-level child process creation API CreateProcess()
521 * doesn't use argument vectors, but a command line. The C runtime
522 * library's spawn*() family of functions (which g_spawn_async_with_pipes()
523 * eventually calls) paste the argument vector elements together into
524 * a command line, and the C runtime startup code does a corresponding
525 * reconstruction of an argument vector from the command line, to be
526 * passed to main(). Complications arise when you have argument vector
527 * elements that contain spaces of double quotes. The spawn*() functions
528 * don't do any quoting or escaping, but on the other hand the startup
529 * code does do unquoting and unescaping in order to enable receiving
530 * arguments with embedded spaces or double quotes. To work around this
531 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
532 * argument vector elements that need it before calling the C runtime
533 * spawn() function.
535 * The returned @child_pid on Windows is a handle to the child
536 * process, not its identifier. Process handles and process
537 * identifiers are different concepts on Windows.
539 * @envp is a %NULL-terminated array of strings, where each string
540 * has the form `KEY=VALUE`. This will become the child's environment.
541 * If @envp is %NULL, the child inherits its parent's environment.
543 * @flags should be the bitwise OR of any flags you want to affect the
544 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
545 * child will not automatically be reaped; you must use a child watch to
546 * be notified about the death of the child process. Eventually you must
547 * call g_spawn_close_pid() on the @child_pid, in order to free
548 * resources which may be associated with the child process. (On Unix,
549 * using a child watch is equivalent to calling waitpid() or handling
550 * the %SIGCHLD signal manually. On Windows, calling g_spawn_close_pid()
551 * is equivalent to calling CloseHandle() on the process handle returned
552 * in @child_pid). See g_child_watch_add().
554 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
555 * descriptors will be inherited by the child; otherwise all descriptors
556 * except stdin/stdout/stderr will be closed before calling exec() in
557 * the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
558 * absolute path, it will be looked for in the `PATH` environment
559 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
560 * absolute path, it will be looked for in the `PATH` variable from
561 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
562 * are used, the value from @envp takes precedence over the environment.
563 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
564 * will be discarded, instead of going to the same location as the parent's
565 * standard output. If you use this flag, @standard_output must be %NULL.
566 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
567 * will be discarded, instead of going to the same location as the parent's
568 * standard error. If you use this flag, @standard_error must be %NULL.
569 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
570 * standard input (by default, the child's standard input is attached to
571 * /dev/null). If you use this flag, @standard_input must be %NULL.
572 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
573 * the file to execute, while the remaining elements are the actual
574 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
575 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
577 * @child_setup and @user_data are a function and user data. On POSIX
578 * platforms, the function is called in the child after GLib has
579 * performed all the setup it plans to perform (including creating
580 * pipes, closing file descriptors, etc.) but before calling exec().
581 * That is, @child_setup is called just before calling exec() in the
582 * child. Obviously actions taken in this function will only affect
583 * the child, not the parent.
585 * On Windows, there is no separate fork() and exec() functionality.
586 * Child processes are created and run with a single API call,
587 * CreateProcess(). There is no sensible thing @child_setup
588 * could be used for on Windows so it is ignored and not called.
590 * If non-%NULL, @child_pid will on Unix be filled with the child's
591 * process ID. You can use the process ID to send signals to the child,
592 * or to use g_child_watch_add() (or waitpid()) if you specified the
593 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
594 * filled with a handle to the child process only if you specified the
595 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
596 * process using the Win32 API, for example wait for its termination
597 * with the WaitFor*() functions, or examine its exit code with
598 * GetExitCodeProcess(). You should close the handle with CloseHandle()
599 * or g_spawn_close_pid() when you no longer need it.
601 * If non-%NULL, the @standard_input, @standard_output, @standard_error
602 * locations will be filled with file descriptors for writing to the child's
603 * standard input or reading from its standard output or standard error.
604 * The caller of g_spawn_async_with_pipes() must close these file descriptors
605 * when they are no longer in use. If these parameters are %NULL, the
606 * corresponding pipe won't be created.
608 * If @standard_input is NULL, the child's standard input is attached to
609 * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
611 * If @standard_error is NULL, the child's standard error goes to the same
612 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
613 * is set.
615 * If @standard_output is NULL, the child's standard output goes to the same
616 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
617 * is set.
619 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
620 * If an error is set, the function returns %FALSE. Errors are reported
621 * even if they occur in the child (for example if the executable in
622 * @argv[0] is not found). Typically the `message` field of returned
623 * errors should be displayed to users. Possible errors are those from
624 * the #G_SPAWN_ERROR domain.
626 * If an error occurs, @child_pid, @standard_input, @standard_output,
627 * and @standard_error will not be filled with valid values.
629 * If @child_pid is not %NULL and an error does not occur then the returned
630 * process reference must be closed using g_spawn_close_pid().
632 * If you are writing a GTK+ application, and the program you
633 * are spawning is a graphical application, too, then you may
634 * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that
635 * the spawned program opens its windows on the right screen.
637 * Returns: %TRUE on success, %FALSE if an error was set
639 gboolean
640 g_spawn_async_with_pipes (const gchar *working_directory,
641 gchar **argv,
642 gchar **envp,
643 GSpawnFlags flags,
644 GSpawnChildSetupFunc child_setup,
645 gpointer user_data,
646 GPid *child_pid,
647 gint *standard_input,
648 gint *standard_output,
649 gint *standard_error,
650 GError **error)
652 g_return_val_if_fail (argv != NULL, FALSE);
653 g_return_val_if_fail (standard_output == NULL ||
654 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
655 g_return_val_if_fail (standard_error == NULL ||
656 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
657 /* can't inherit stdin if we have an input pipe. */
658 g_return_val_if_fail (standard_input == NULL ||
659 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
661 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
662 working_directory,
663 argv,
664 envp,
665 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
666 (flags & G_SPAWN_SEARCH_PATH) != 0,
667 (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
668 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
669 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
670 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
671 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
672 (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
673 child_setup,
674 user_data,
675 child_pid,
676 standard_input,
677 standard_output,
678 standard_error,
679 error);
683 * g_spawn_command_line_sync:
684 * @command_line: a command line
685 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child output
686 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (allow-none): return location for child errors
687 * @exit_status: (out) (allow-none): return location for child exit status, as returned by waitpid()
688 * @error: return location for errors
690 * A simple version of g_spawn_sync() with little-used parameters
691 * removed, taking a command line instead of an argument vector. See
692 * g_spawn_sync() for full details. @command_line will be parsed by
693 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
694 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
695 * implications, so consider using g_spawn_sync() directly if
696 * appropriate. Possible errors are those from g_spawn_sync() and those
697 * from g_shell_parse_argv().
699 * If @exit_status is non-%NULL, the platform-specific exit status of
700 * the child is stored there; see the documentation of
701 * g_spawn_check_exit_status() for how to use and interpret this.
703 * On Windows, please note the implications of g_shell_parse_argv()
704 * parsing @command_line. Parsing is done according to Unix shell rules, not
705 * Windows command interpreter rules.
706 * Space is a separator, and backslashes are
707 * special. Thus you cannot simply pass a @command_line containing
708 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
709 * the backslashes will be eaten, and the space will act as a
710 * separator. You need to enclose such paths with single quotes, like
711 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
713 * Returns: %TRUE on success, %FALSE if an error was set
715 gboolean
716 g_spawn_command_line_sync (const gchar *command_line,
717 gchar **standard_output,
718 gchar **standard_error,
719 gint *exit_status,
720 GError **error)
722 gboolean retval;
723 gchar **argv = NULL;
725 g_return_val_if_fail (command_line != NULL, FALSE);
727 if (!g_shell_parse_argv (command_line,
728 NULL, &argv,
729 error))
730 return FALSE;
732 retval = g_spawn_sync (NULL,
733 argv,
734 NULL,
735 G_SPAWN_SEARCH_PATH,
736 NULL,
737 NULL,
738 standard_output,
739 standard_error,
740 exit_status,
741 error);
742 g_strfreev (argv);
744 return retval;
748 * g_spawn_command_line_async:
749 * @command_line: a command line
750 * @error: return location for errors
752 * A simple version of g_spawn_async() that parses a command line with
753 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
754 * command line in the background. Unlike g_spawn_async(), the
755 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
756 * that %G_SPAWN_SEARCH_PATH can have security implications, so
757 * consider using g_spawn_async() directly if appropriate. Possible
758 * errors are those from g_shell_parse_argv() and g_spawn_async().
760 * The same concerns on Windows apply as for g_spawn_command_line_sync().
762 * Returns: %TRUE on success, %FALSE if error is set
764 gboolean
765 g_spawn_command_line_async (const gchar *command_line,
766 GError **error)
768 gboolean retval;
769 gchar **argv = NULL;
771 g_return_val_if_fail (command_line != NULL, FALSE);
773 if (!g_shell_parse_argv (command_line,
774 NULL, &argv,
775 error))
776 return FALSE;
778 retval = g_spawn_async (NULL,
779 argv,
780 NULL,
781 G_SPAWN_SEARCH_PATH,
782 NULL,
783 NULL,
784 NULL,
785 error);
786 g_strfreev (argv);
788 return retval;
792 * g_spawn_check_exit_status:
793 * @exit_status: An exit code as returned from g_spawn_sync()
794 * @error: a #GError
796 * Set @error if @exit_status indicates the child exited abnormally
797 * (e.g. with a nonzero exit code, or via a fatal signal).
799 * The g_spawn_sync() and g_child_watch_add() family of APIs return an
800 * exit status for subprocesses encoded in a platform-specific way.
801 * On Unix, this is guaranteed to be in the same format waitpid() returns,
802 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
804 * Prior to the introduction of this function in GLib 2.34, interpreting
805 * @exit_status required use of platform-specific APIs, which is problematic
806 * for software using GLib as a cross-platform layer.
808 * Additionally, many programs simply want to determine whether or not
809 * the child exited successfully, and either propagate a #GError or
810 * print a message to standard error. In that common case, this function
811 * can be used. Note that the error message in @error will contain
812 * human-readable information about the exit status.
814 * The @domain and @code of @error have special semantics in the case
815 * where the process has an "exit code", as opposed to being killed by
816 * a signal. On Unix, this happens if WIFEXITED() would be true of
817 * @exit_status. On Windows, it is always the case.
819 * The special semantics are that the actual exit code will be the
820 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
821 * This allows you to differentiate between different exit codes.
823 * If the process was terminated by some means other than an exit
824 * status, the domain will be %G_SPAWN_ERROR, and the code will be
825 * %G_SPAWN_ERROR_FAILED.
827 * This function just offers convenience; you can of course also check
828 * the available platform via a macro such as %G_OS_UNIX, and use
829 * WIFEXITED() and WEXITSTATUS() on @exit_status directly. Do not attempt
830 * to scan or parse the error message string; it may be translated and/or
831 * change in future versions of GLib.
833 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
834 * @error will be set)
836 * Since: 2.34
838 gboolean
839 g_spawn_check_exit_status (gint exit_status,
840 GError **error)
842 gboolean ret = FALSE;
844 if (WIFEXITED (exit_status))
846 if (WEXITSTATUS (exit_status) != 0)
848 g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (exit_status),
849 _("Child process exited with code %ld"),
850 (long) WEXITSTATUS (exit_status));
851 goto out;
854 else if (WIFSIGNALED (exit_status))
856 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
857 _("Child process killed by signal %ld"),
858 (long) WTERMSIG (exit_status));
859 goto out;
861 else if (WIFSTOPPED (exit_status))
863 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
864 _("Child process stopped by signal %ld"),
865 (long) WSTOPSIG (exit_status));
866 goto out;
868 else
870 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
871 _("Child process exited abnormally"));
872 goto out;
875 ret = TRUE;
876 out:
877 return ret;
880 static gint
881 exec_err_to_g_error (gint en)
883 switch (en)
885 #ifdef EACCES
886 case EACCES:
887 return G_SPAWN_ERROR_ACCES;
888 break;
889 #endif
891 #ifdef EPERM
892 case EPERM:
893 return G_SPAWN_ERROR_PERM;
894 break;
895 #endif
897 #ifdef E2BIG
898 case E2BIG:
899 return G_SPAWN_ERROR_TOO_BIG;
900 break;
901 #endif
903 #ifdef ENOEXEC
904 case ENOEXEC:
905 return G_SPAWN_ERROR_NOEXEC;
906 break;
907 #endif
909 #ifdef ENAMETOOLONG
910 case ENAMETOOLONG:
911 return G_SPAWN_ERROR_NAMETOOLONG;
912 break;
913 #endif
915 #ifdef ENOENT
916 case ENOENT:
917 return G_SPAWN_ERROR_NOENT;
918 break;
919 #endif
921 #ifdef ENOMEM
922 case ENOMEM:
923 return G_SPAWN_ERROR_NOMEM;
924 break;
925 #endif
927 #ifdef ENOTDIR
928 case ENOTDIR:
929 return G_SPAWN_ERROR_NOTDIR;
930 break;
931 #endif
933 #ifdef ELOOP
934 case ELOOP:
935 return G_SPAWN_ERROR_LOOP;
936 break;
937 #endif
939 #ifdef ETXTBUSY
940 case ETXTBUSY:
941 return G_SPAWN_ERROR_TXTBUSY;
942 break;
943 #endif
945 #ifdef EIO
946 case EIO:
947 return G_SPAWN_ERROR_IO;
948 break;
949 #endif
951 #ifdef ENFILE
952 case ENFILE:
953 return G_SPAWN_ERROR_NFILE;
954 break;
955 #endif
957 #ifdef EMFILE
958 case EMFILE:
959 return G_SPAWN_ERROR_MFILE;
960 break;
961 #endif
963 #ifdef EINVAL
964 case EINVAL:
965 return G_SPAWN_ERROR_INVAL;
966 break;
967 #endif
969 #ifdef EISDIR
970 case EISDIR:
971 return G_SPAWN_ERROR_ISDIR;
972 break;
973 #endif
975 #ifdef ELIBBAD
976 case ELIBBAD:
977 return G_SPAWN_ERROR_LIBBAD;
978 break;
979 #endif
981 default:
982 return G_SPAWN_ERROR_FAILED;
983 break;
987 static gssize
988 write_all (gint fd, gconstpointer vbuf, gsize to_write)
990 gchar *buf = (gchar *) vbuf;
992 while (to_write > 0)
994 gssize count = write (fd, buf, to_write);
995 if (count < 0)
997 if (errno != EINTR)
998 return FALSE;
1000 else
1002 to_write -= count;
1003 buf += count;
1007 return TRUE;
1010 G_GNUC_NORETURN
1011 static void
1012 write_err_and_exit (gint fd, gint msg)
1014 gint en = errno;
1016 write_all (fd, &msg, sizeof(msg));
1017 write_all (fd, &en, sizeof(en));
1019 _exit (1);
1022 static int
1023 set_cloexec (void *data, gint fd)
1025 if (fd >= GPOINTER_TO_INT (data))
1026 fcntl (fd, F_SETFD, FD_CLOEXEC);
1028 return 0;
1031 #ifndef HAVE_FDWALK
1032 static int
1033 fdwalk (int (*cb)(void *data, int fd), void *data)
1035 gint open_max;
1036 gint fd;
1037 gint res = 0;
1039 #ifdef HAVE_SYS_RESOURCE_H
1040 struct rlimit rl;
1041 #endif
1043 #ifdef __linux__
1044 DIR *d;
1046 if ((d = opendir("/proc/self/fd"))) {
1047 struct dirent *de;
1049 while ((de = readdir(d))) {
1050 glong l;
1051 gchar *e = NULL;
1053 if (de->d_name[0] == '.')
1054 continue;
1056 errno = 0;
1057 l = strtol(de->d_name, &e, 10);
1058 if (errno != 0 || !e || *e)
1059 continue;
1061 fd = (gint) l;
1063 if ((glong) fd != l)
1064 continue;
1066 if (fd == dirfd(d))
1067 continue;
1069 if ((res = cb (data, fd)) != 0)
1070 break;
1073 closedir(d);
1074 return res;
1077 /* If /proc is not mounted or not accessible we fall back to the old
1078 * rlimit trick */
1080 #endif
1082 #ifdef HAVE_SYS_RESOURCE_H
1084 if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1085 open_max = rl.rlim_max;
1086 else
1087 #endif
1088 open_max = sysconf (_SC_OPEN_MAX);
1090 for (fd = 0; fd < open_max; fd++)
1091 if ((res = cb (data, fd)) != 0)
1092 break;
1094 return res;
1096 #endif
1098 static gint
1099 sane_dup2 (gint fd1, gint fd2)
1101 gint ret;
1103 retry:
1104 ret = dup2 (fd1, fd2);
1105 if (ret < 0 && errno == EINTR)
1106 goto retry;
1108 return ret;
1111 static gint
1112 sane_open (const char *path, gint mode)
1114 gint ret;
1116 retry:
1117 ret = open (path, mode);
1118 if (ret < 0 && errno == EINTR)
1119 goto retry;
1121 return ret;
1124 enum
1126 CHILD_CHDIR_FAILED,
1127 CHILD_EXEC_FAILED,
1128 CHILD_DUP2_FAILED,
1129 CHILD_FORK_FAILED
1132 static void
1133 do_exec (gint child_err_report_fd,
1134 gint stdin_fd,
1135 gint stdout_fd,
1136 gint stderr_fd,
1137 const gchar *working_directory,
1138 gchar **argv,
1139 gchar **envp,
1140 gboolean close_descriptors,
1141 gboolean search_path,
1142 gboolean search_path_from_envp,
1143 gboolean stdout_to_null,
1144 gboolean stderr_to_null,
1145 gboolean child_inherits_stdin,
1146 gboolean file_and_argv_zero,
1147 GSpawnChildSetupFunc child_setup,
1148 gpointer user_data)
1150 if (working_directory && chdir (working_directory) < 0)
1151 write_err_and_exit (child_err_report_fd,
1152 CHILD_CHDIR_FAILED);
1154 /* Close all file descriptors but stdin stdout and stderr as
1155 * soon as we exec. Note that this includes
1156 * child_err_report_fd, which keeps the parent from blocking
1157 * forever on the other end of that pipe.
1159 if (close_descriptors)
1161 fdwalk (set_cloexec, GINT_TO_POINTER(3));
1163 else
1165 /* We need to do child_err_report_fd anyway */
1166 set_cloexec (GINT_TO_POINTER(0), child_err_report_fd);
1169 /* Redirect pipes as required */
1171 if (stdin_fd >= 0)
1173 /* dup2 can't actually fail here I don't think */
1175 if (sane_dup2 (stdin_fd, 0) < 0)
1176 write_err_and_exit (child_err_report_fd,
1177 CHILD_DUP2_FAILED);
1179 /* ignore this if it doesn't work */
1180 close_and_invalidate (&stdin_fd);
1182 else if (!child_inherits_stdin)
1184 /* Keep process from blocking on a read of stdin */
1185 gint read_null = open ("/dev/null", O_RDONLY);
1186 g_assert (read_null != -1);
1187 sane_dup2 (read_null, 0);
1188 close_and_invalidate (&read_null);
1191 if (stdout_fd >= 0)
1193 /* dup2 can't actually fail here I don't think */
1195 if (sane_dup2 (stdout_fd, 1) < 0)
1196 write_err_and_exit (child_err_report_fd,
1197 CHILD_DUP2_FAILED);
1199 /* ignore this if it doesn't work */
1200 close_and_invalidate (&stdout_fd);
1202 else if (stdout_to_null)
1204 gint write_null = sane_open ("/dev/null", O_WRONLY);
1205 g_assert (write_null != -1);
1206 sane_dup2 (write_null, 1);
1207 close_and_invalidate (&write_null);
1210 if (stderr_fd >= 0)
1212 /* dup2 can't actually fail here I don't think */
1214 if (sane_dup2 (stderr_fd, 2) < 0)
1215 write_err_and_exit (child_err_report_fd,
1216 CHILD_DUP2_FAILED);
1218 /* ignore this if it doesn't work */
1219 close_and_invalidate (&stderr_fd);
1221 else if (stderr_to_null)
1223 gint write_null = sane_open ("/dev/null", O_WRONLY);
1224 sane_dup2 (write_null, 2);
1225 close_and_invalidate (&write_null);
1228 /* Call user function just before we exec */
1229 if (child_setup)
1231 (* child_setup) (user_data);
1234 g_execute (argv[0],
1235 file_and_argv_zero ? argv + 1 : argv,
1236 envp, search_path, search_path_from_envp);
1238 /* Exec failed */
1239 write_err_and_exit (child_err_report_fd,
1240 CHILD_EXEC_FAILED);
1243 static gboolean
1244 read_ints (int fd,
1245 gint* buf,
1246 gint n_ints_in_buf,
1247 gint *n_ints_read,
1248 GError **error)
1250 gsize bytes = 0;
1252 while (TRUE)
1254 gssize chunk;
1256 if (bytes >= sizeof(gint)*2)
1257 break; /* give up, who knows what happened, should not be
1258 * possible.
1261 again:
1262 chunk = read (fd,
1263 ((gchar*)buf) + bytes,
1264 sizeof(gint) * n_ints_in_buf - bytes);
1265 if (chunk < 0 && errno == EINTR)
1266 goto again;
1268 if (chunk < 0)
1270 int errsv = errno;
1272 /* Some weird shit happened, bail out */
1273 g_set_error (error,
1274 G_SPAWN_ERROR,
1275 G_SPAWN_ERROR_FAILED,
1276 _("Failed to read from child pipe (%s)"),
1277 g_strerror (errsv));
1279 return FALSE;
1281 else if (chunk == 0)
1282 break; /* EOF */
1283 else /* chunk > 0 */
1284 bytes += chunk;
1287 *n_ints_read = (gint)(bytes / sizeof(gint));
1289 return TRUE;
1292 static gboolean
1293 fork_exec_with_pipes (gboolean intermediate_child,
1294 const gchar *working_directory,
1295 gchar **argv,
1296 gchar **envp,
1297 gboolean close_descriptors,
1298 gboolean search_path,
1299 gboolean search_path_from_envp,
1300 gboolean stdout_to_null,
1301 gboolean stderr_to_null,
1302 gboolean child_inherits_stdin,
1303 gboolean file_and_argv_zero,
1304 gboolean cloexec_pipes,
1305 GSpawnChildSetupFunc child_setup,
1306 gpointer user_data,
1307 GPid *child_pid,
1308 gint *standard_input,
1309 gint *standard_output,
1310 gint *standard_error,
1311 GError **error)
1313 GPid pid = -1;
1314 gint stdin_pipe[2] = { -1, -1 };
1315 gint stdout_pipe[2] = { -1, -1 };
1316 gint stderr_pipe[2] = { -1, -1 };
1317 gint child_err_report_pipe[2] = { -1, -1 };
1318 gint child_pid_report_pipe[2] = { -1, -1 };
1319 guint pipe_flags = cloexec_pipes ? FD_CLOEXEC : 0;
1320 gint status;
1322 if (!g_unix_open_pipe (child_err_report_pipe, pipe_flags, error))
1323 return FALSE;
1325 if (intermediate_child && !g_unix_open_pipe (child_pid_report_pipe, pipe_flags, error))
1326 goto cleanup_and_fail;
1328 if (standard_input && !g_unix_open_pipe (stdin_pipe, pipe_flags, error))
1329 goto cleanup_and_fail;
1331 if (standard_output && !g_unix_open_pipe (stdout_pipe, pipe_flags, error))
1332 goto cleanup_and_fail;
1334 if (standard_error && !g_unix_open_pipe (stderr_pipe, FD_CLOEXEC, error))
1335 goto cleanup_and_fail;
1337 pid = fork ();
1339 if (pid < 0)
1341 int errsv = errno;
1343 g_set_error (error,
1344 G_SPAWN_ERROR,
1345 G_SPAWN_ERROR_FORK,
1346 _("Failed to fork (%s)"),
1347 g_strerror (errsv));
1349 goto cleanup_and_fail;
1351 else if (pid == 0)
1353 /* Immediate child. This may or may not be the child that
1354 * actually execs the new process.
1357 /* Reset some signal handlers that we may use */
1358 signal (SIGCHLD, SIG_DFL);
1359 signal (SIGINT, SIG_DFL);
1360 signal (SIGTERM, SIG_DFL);
1361 signal (SIGHUP, SIG_DFL);
1363 /* Be sure we crash if the parent exits
1364 * and we write to the err_report_pipe
1366 signal (SIGPIPE, SIG_DFL);
1368 /* Close the parent's end of the pipes;
1369 * not needed in the close_descriptors case,
1370 * though
1372 close_and_invalidate (&child_err_report_pipe[0]);
1373 close_and_invalidate (&child_pid_report_pipe[0]);
1374 close_and_invalidate (&stdin_pipe[1]);
1375 close_and_invalidate (&stdout_pipe[0]);
1376 close_and_invalidate (&stderr_pipe[0]);
1378 if (intermediate_child)
1380 /* We need to fork an intermediate child that launches the
1381 * final child. The purpose of the intermediate child
1382 * is to exit, so we can waitpid() it immediately.
1383 * Then the grandchild will not become a zombie.
1385 GPid grandchild_pid;
1387 grandchild_pid = fork ();
1389 if (grandchild_pid < 0)
1391 /* report -1 as child PID */
1392 write_all (child_pid_report_pipe[1], &grandchild_pid,
1393 sizeof(grandchild_pid));
1395 write_err_and_exit (child_err_report_pipe[1],
1396 CHILD_FORK_FAILED);
1398 else if (grandchild_pid == 0)
1400 close_and_invalidate (&child_pid_report_pipe[1]);
1401 do_exec (child_err_report_pipe[1],
1402 stdin_pipe[0],
1403 stdout_pipe[1],
1404 stderr_pipe[1],
1405 working_directory,
1406 argv,
1407 envp,
1408 close_descriptors,
1409 search_path,
1410 search_path_from_envp,
1411 stdout_to_null,
1412 stderr_to_null,
1413 child_inherits_stdin,
1414 file_and_argv_zero,
1415 child_setup,
1416 user_data);
1418 else
1420 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1421 close_and_invalidate (&child_pid_report_pipe[1]);
1423 _exit (0);
1426 else
1428 /* Just run the child.
1431 do_exec (child_err_report_pipe[1],
1432 stdin_pipe[0],
1433 stdout_pipe[1],
1434 stderr_pipe[1],
1435 working_directory,
1436 argv,
1437 envp,
1438 close_descriptors,
1439 search_path,
1440 search_path_from_envp,
1441 stdout_to_null,
1442 stderr_to_null,
1443 child_inherits_stdin,
1444 file_and_argv_zero,
1445 child_setup,
1446 user_data);
1449 else
1451 /* Parent */
1453 gint buf[2];
1454 gint n_ints = 0;
1456 /* Close the uncared-about ends of the pipes */
1457 close_and_invalidate (&child_err_report_pipe[1]);
1458 close_and_invalidate (&child_pid_report_pipe[1]);
1459 close_and_invalidate (&stdin_pipe[0]);
1460 close_and_invalidate (&stdout_pipe[1]);
1461 close_and_invalidate (&stderr_pipe[1]);
1463 /* If we had an intermediate child, reap it */
1464 if (intermediate_child)
1466 wait_again:
1467 if (waitpid (pid, &status, 0) < 0)
1469 if (errno == EINTR)
1470 goto wait_again;
1471 else if (errno == ECHILD)
1472 ; /* do nothing, child already reaped */
1473 else
1474 g_warning ("waitpid() should not fail in "
1475 "'fork_exec_with_pipes'");
1480 if (!read_ints (child_err_report_pipe[0],
1481 buf, 2, &n_ints,
1482 error))
1483 goto cleanup_and_fail;
1485 if (n_ints >= 2)
1487 /* Error from the child. */
1489 switch (buf[0])
1491 case CHILD_CHDIR_FAILED:
1492 g_set_error (error,
1493 G_SPAWN_ERROR,
1494 G_SPAWN_ERROR_CHDIR,
1495 _("Failed to change to directory '%s' (%s)"),
1496 working_directory,
1497 g_strerror (buf[1]));
1499 break;
1501 case CHILD_EXEC_FAILED:
1502 g_set_error (error,
1503 G_SPAWN_ERROR,
1504 exec_err_to_g_error (buf[1]),
1505 _("Failed to execute child process \"%s\" (%s)"),
1506 argv[0],
1507 g_strerror (buf[1]));
1509 break;
1511 case CHILD_DUP2_FAILED:
1512 g_set_error (error,
1513 G_SPAWN_ERROR,
1514 G_SPAWN_ERROR_FAILED,
1515 _("Failed to redirect output or input of child process (%s)"),
1516 g_strerror (buf[1]));
1518 break;
1520 case CHILD_FORK_FAILED:
1521 g_set_error (error,
1522 G_SPAWN_ERROR,
1523 G_SPAWN_ERROR_FORK,
1524 _("Failed to fork child process (%s)"),
1525 g_strerror (buf[1]));
1526 break;
1528 default:
1529 g_set_error (error,
1530 G_SPAWN_ERROR,
1531 G_SPAWN_ERROR_FAILED,
1532 _("Unknown error executing child process \"%s\""),
1533 argv[0]);
1534 break;
1537 goto cleanup_and_fail;
1540 /* Get child pid from intermediate child pipe. */
1541 if (intermediate_child)
1543 n_ints = 0;
1545 if (!read_ints (child_pid_report_pipe[0],
1546 buf, 1, &n_ints, error))
1547 goto cleanup_and_fail;
1549 if (n_ints < 1)
1551 int errsv = errno;
1553 g_set_error (error,
1554 G_SPAWN_ERROR,
1555 G_SPAWN_ERROR_FAILED,
1556 _("Failed to read enough data from child pid pipe (%s)"),
1557 g_strerror (errsv));
1558 goto cleanup_and_fail;
1560 else
1562 /* we have the child pid */
1563 pid = buf[0];
1567 /* Success against all odds! return the information */
1568 close_and_invalidate (&child_err_report_pipe[0]);
1569 close_and_invalidate (&child_pid_report_pipe[0]);
1571 if (child_pid)
1572 *child_pid = pid;
1574 if (standard_input)
1575 *standard_input = stdin_pipe[1];
1576 if (standard_output)
1577 *standard_output = stdout_pipe[0];
1578 if (standard_error)
1579 *standard_error = stderr_pipe[0];
1581 return TRUE;
1584 cleanup_and_fail:
1586 /* There was an error from the Child, reap the child to avoid it being
1587 a zombie.
1590 if (pid > 0)
1592 wait_failed:
1593 if (waitpid (pid, NULL, 0) < 0)
1595 if (errno == EINTR)
1596 goto wait_failed;
1597 else if (errno == ECHILD)
1598 ; /* do nothing, child already reaped */
1599 else
1600 g_warning ("waitpid() should not fail in "
1601 "'fork_exec_with_pipes'");
1605 close_and_invalidate (&child_err_report_pipe[0]);
1606 close_and_invalidate (&child_err_report_pipe[1]);
1607 close_and_invalidate (&child_pid_report_pipe[0]);
1608 close_and_invalidate (&child_pid_report_pipe[1]);
1609 close_and_invalidate (&stdin_pipe[0]);
1610 close_and_invalidate (&stdin_pipe[1]);
1611 close_and_invalidate (&stdout_pipe[0]);
1612 close_and_invalidate (&stdout_pipe[1]);
1613 close_and_invalidate (&stderr_pipe[0]);
1614 close_and_invalidate (&stderr_pipe[1]);
1616 return FALSE;
1619 /* Based on execvp from GNU C Library */
1621 static void
1622 script_execute (const gchar *file,
1623 gchar **argv,
1624 gchar **envp)
1626 /* Count the arguments. */
1627 int argc = 0;
1628 while (argv[argc])
1629 ++argc;
1631 /* Construct an argument list for the shell. */
1633 gchar **new_argv;
1635 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1637 new_argv[0] = (char *) "/bin/sh";
1638 new_argv[1] = (char *) file;
1639 while (argc > 0)
1641 new_argv[argc + 1] = argv[argc];
1642 --argc;
1645 /* Execute the shell. */
1646 if (envp)
1647 execve (new_argv[0], new_argv, envp);
1648 else
1649 execv (new_argv[0], new_argv);
1651 g_free (new_argv);
1655 static gchar*
1656 my_strchrnul (const gchar *str, gchar c)
1658 gchar *p = (gchar*) str;
1659 while (*p && (*p != c))
1660 ++p;
1662 return p;
1665 static gint
1666 g_execute (const gchar *file,
1667 gchar **argv,
1668 gchar **envp,
1669 gboolean search_path,
1670 gboolean search_path_from_envp)
1672 if (*file == '\0')
1674 /* We check the simple case first. */
1675 errno = ENOENT;
1676 return -1;
1679 if (!(search_path || search_path_from_envp) || strchr (file, '/') != NULL)
1681 /* Don't search when it contains a slash. */
1682 if (envp)
1683 execve (file, argv, envp);
1684 else
1685 execv (file, argv);
1687 if (errno == ENOEXEC)
1688 script_execute (file, argv, envp);
1690 else
1692 gboolean got_eacces = 0;
1693 const gchar *path, *p;
1694 gchar *name, *freeme;
1695 gsize len;
1696 gsize pathlen;
1698 path = NULL;
1699 if (search_path_from_envp)
1700 path = g_environ_getenv (envp, "PATH");
1701 if (search_path && path == NULL)
1702 path = g_getenv ("PATH");
1704 if (path == NULL)
1706 /* There is no 'PATH' in the environment. The default
1707 * search path in libc is the current directory followed by
1708 * the path 'confstr' returns for '_CS_PATH'.
1711 /* In GLib we put . last, for security, and don't use the
1712 * unportable confstr(); UNIX98 does not actually specify
1713 * what to search if PATH is unset. POSIX may, dunno.
1716 path = "/bin:/usr/bin:.";
1719 len = strlen (file) + 1;
1720 pathlen = strlen (path);
1721 freeme = name = g_malloc (pathlen + len + 1);
1723 /* Copy the file name at the top, including '\0' */
1724 memcpy (name + pathlen + 1, file, len);
1725 name = name + pathlen;
1726 /* And add the slash before the filename */
1727 *name = '/';
1729 p = path;
1732 char *startp;
1734 path = p;
1735 p = my_strchrnul (path, ':');
1737 if (p == path)
1738 /* Two adjacent colons, or a colon at the beginning or the end
1739 * of 'PATH' means to search the current directory.
1741 startp = name + 1;
1742 else
1743 startp = memcpy (name - (p - path), path, p - path);
1745 /* Try to execute this name. If it works, execv will not return. */
1746 if (envp)
1747 execve (startp, argv, envp);
1748 else
1749 execv (startp, argv);
1751 if (errno == ENOEXEC)
1752 script_execute (startp, argv, envp);
1754 switch (errno)
1756 case EACCES:
1757 /* Record the we got a 'Permission denied' error. If we end
1758 * up finding no executable we can use, we want to diagnose
1759 * that we did find one but were denied access.
1761 got_eacces = TRUE;
1763 /* FALL THRU */
1765 case ENOENT:
1766 #ifdef ESTALE
1767 case ESTALE:
1768 #endif
1769 #ifdef ENOTDIR
1770 case ENOTDIR:
1771 #endif
1772 /* Those errors indicate the file is missing or not executable
1773 * by us, in which case we want to just try the next path
1774 * directory.
1776 break;
1778 case ENODEV:
1779 case ETIMEDOUT:
1780 /* Some strange filesystems like AFS return even
1781 * stranger error numbers. They cannot reasonably mean anything
1782 * else so ignore those, too.
1784 break;
1786 default:
1787 /* Some other error means we found an executable file, but
1788 * something went wrong executing it; return the error to our
1789 * caller.
1791 g_free (freeme);
1792 return -1;
1795 while (*p++ != '\0');
1797 /* We tried every element and none of them worked. */
1798 if (got_eacces)
1799 /* At least one failure was due to permissions, so report that
1800 * error.
1802 errno = EACCES;
1804 g_free (freeme);
1807 /* Return the error from the last attempt (probably ENOENT). */
1808 return -1;
1812 * g_spawn_close_pid:
1813 * @pid: The process reference to close
1815 * On some platforms, notably Windows, the #GPid type represents a resource
1816 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1817 * is provided for this purpose. It should be used on all platforms, even
1818 * though it doesn't do anything under UNIX.
1820 void
1821 g_spawn_close_pid (GPid pid)