Handle multiple user names with the same UID better. (#319535, Laszlo
[glib.git] / glib / gspawn.c
blob6d77b25b747924687f3ac88281a5f19af7286001
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>
34 #ifdef HAVE_SYS_SELECT_H
35 #include <sys/select.h>
36 #endif /* HAVE_SYS_SELECT_H */
38 #include "glib.h"
39 #include "galias.h"
41 #include "glibintl.h"
43 static gint g_execute (const gchar *file,
44 gchar **argv,
45 gchar **envp,
46 gboolean search_path);
48 static gboolean make_pipe (gint p[2],
49 GError **error);
50 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
51 const gchar *working_directory,
52 gchar **argv,
53 gchar **envp,
54 gboolean close_descriptors,
55 gboolean search_path,
56 gboolean stdout_to_null,
57 gboolean stderr_to_null,
58 gboolean child_inherits_stdin,
59 gboolean file_and_argv_zero,
60 GSpawnChildSetupFunc child_setup,
61 gpointer user_data,
62 GPid *child_pid,
63 gint *standard_input,
64 gint *standard_output,
65 gint *standard_error,
66 GError **error);
68 GQuark
69 g_spawn_error_quark (void)
71 static GQuark quark = 0;
72 if (quark == 0)
73 quark = g_quark_from_static_string ("g-exec-error-quark");
74 return quark;
77 /**
78 * g_spawn_async:
79 * @working_directory: child's current working directory, or %NULL to inherit parent's
80 * @argv: child's argument vector
81 * @envp: child's environment, or %NULL to inherit parent's
82 * @flags: flags from #GSpawnFlags
83 * @child_setup: function to run in the child just before exec()
84 * @user_data: user data for @child_setup
85 * @child_pid: return location for child process ID, or %NULL
86 * @error: return location for error
88 * See g_spawn_async_with_pipes() for a full description; this function
89 * simply calls the g_spawn_async_with_pipes() without any pipes.
91 * Return value: %TRUE on success, %FALSE if error is set
92 **/
93 gboolean
94 g_spawn_async (const gchar *working_directory,
95 gchar **argv,
96 gchar **envp,
97 GSpawnFlags flags,
98 GSpawnChildSetupFunc child_setup,
99 gpointer user_data,
100 GPid *child_pid,
101 GError **error)
103 g_return_val_if_fail (argv != NULL, FALSE);
105 return g_spawn_async_with_pipes (working_directory,
106 argv, envp,
107 flags,
108 child_setup,
109 user_data,
110 child_pid,
111 NULL, NULL, NULL,
112 error);
115 /* Avoids a danger in threaded situations (calling close()
116 * on a file descriptor twice, and another thread has
117 * re-opened it since the first close)
119 static gint
120 close_and_invalidate (gint *fd)
122 gint ret;
124 if (*fd < 0)
125 return -1;
126 else
128 ret = close (*fd);
129 *fd = -1;
132 return ret;
135 typedef enum
137 READ_FAILED = 0, /* FALSE */
138 READ_OK,
139 READ_EOF
140 } ReadResult;
142 static ReadResult
143 read_data (GString *str,
144 gint fd,
145 GError **error)
147 gssize bytes;
148 gchar buf[4096];
150 again:
152 bytes = read (fd, buf, 4096);
154 if (bytes == 0)
155 return READ_EOF;
156 else if (bytes > 0)
158 g_string_append_len (str, buf, bytes);
159 return READ_OK;
161 else if (bytes < 0 && errno == EINTR)
162 goto again;
163 else if (bytes < 0)
165 g_set_error (error,
166 G_SPAWN_ERROR,
167 G_SPAWN_ERROR_READ,
168 _("Failed to read data from child process (%s)"),
169 g_strerror (errno));
171 return READ_FAILED;
173 else
174 return READ_OK;
178 * g_spawn_sync:
179 * @working_directory: child's current working directory, or %NULL to inherit parent's
180 * @argv: child's argument vector
181 * @envp: child's environment, or %NULL to inherit parent's
182 * @flags: flags from #GSpawnFlags
183 * @child_setup: function to run in the child just before exec()
184 * @user_data: user data for @child_setup
185 * @standard_output: return location for child output
186 * @standard_error: return location for child error messages
187 * @exit_status: return location for child exit status, as returned by waitpid()
188 * @error: return location for error
190 * Executes a child synchronously (waits for the child to exit before returning).
191 * All output from the child is stored in @standard_output and @standard_error,
192 * if those parameters are non-%NULL. If @exit_status is non-%NULL, the exit
193 * status of the child is stored there as it would be returned by
194 * waitpid(); standard UNIX macros such as WIFEXITED() and WEXITSTATUS()
195 * must be used to evaluate the exit status. If an error occurs, no data is
196 * returned in @standard_output, @standard_error, or @exit_status.
198 * This function calls g_spawn_async_with_pipes() internally; see that
199 * function for full details on the other parameters and details on
200 * how these functions work on Windows.
202 * Return value: %TRUE on success, %FALSE if an error was set.
204 gboolean
205 g_spawn_sync (const gchar *working_directory,
206 gchar **argv,
207 gchar **envp,
208 GSpawnFlags flags,
209 GSpawnChildSetupFunc child_setup,
210 gpointer user_data,
211 gchar **standard_output,
212 gchar **standard_error,
213 gint *exit_status,
214 GError **error)
216 gint outpipe = -1;
217 gint errpipe = -1;
218 GPid pid;
219 fd_set fds;
220 gint ret;
221 GString *outstr = NULL;
222 GString *errstr = NULL;
223 gboolean failed;
224 gint status;
226 g_return_val_if_fail (argv != NULL, FALSE);
227 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
228 g_return_val_if_fail (standard_output == NULL ||
229 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
230 g_return_val_if_fail (standard_error == NULL ||
231 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
233 /* Just to ensure segfaults if callers try to use
234 * these when an error is reported.
236 if (standard_output)
237 *standard_output = NULL;
239 if (standard_error)
240 *standard_error = NULL;
242 if (!fork_exec_with_pipes (FALSE,
243 working_directory,
244 argv,
245 envp,
246 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
247 (flags & G_SPAWN_SEARCH_PATH) != 0,
248 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
249 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
250 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
251 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
252 child_setup,
253 user_data,
254 &pid,
255 NULL,
256 standard_output ? &outpipe : NULL,
257 standard_error ? &errpipe : NULL,
258 error))
259 return FALSE;
261 /* Read data from child. */
263 failed = FALSE;
265 if (outpipe >= 0)
267 outstr = g_string_new (NULL);
270 if (errpipe >= 0)
272 errstr = g_string_new (NULL);
275 /* Read data until we get EOF on both pipes. */
276 while (!failed &&
277 (outpipe >= 0 ||
278 errpipe >= 0))
280 ret = 0;
282 FD_ZERO (&fds);
283 if (outpipe >= 0)
284 FD_SET (outpipe, &fds);
285 if (errpipe >= 0)
286 FD_SET (errpipe, &fds);
288 ret = select (MAX (outpipe, errpipe) + 1,
289 &fds,
290 NULL, NULL,
291 NULL /* no timeout */);
293 if (ret < 0 && errno != EINTR)
295 failed = TRUE;
297 g_set_error (error,
298 G_SPAWN_ERROR,
299 G_SPAWN_ERROR_READ,
300 _("Unexpected error in select() reading data from a child process (%s)"),
301 g_strerror (errno));
303 break;
306 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
308 switch (read_data (outstr, outpipe, error))
310 case READ_FAILED:
311 failed = TRUE;
312 break;
313 case READ_EOF:
314 close_and_invalidate (&outpipe);
315 outpipe = -1;
316 break;
317 default:
318 break;
321 if (failed)
322 break;
325 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
327 switch (read_data (errstr, errpipe, error))
329 case READ_FAILED:
330 failed = TRUE;
331 break;
332 case READ_EOF:
333 close_and_invalidate (&errpipe);
334 errpipe = -1;
335 break;
336 default:
337 break;
340 if (failed)
341 break;
345 /* These should only be open still if we had an error. */
347 if (outpipe >= 0)
348 close_and_invalidate (&outpipe);
349 if (errpipe >= 0)
350 close_and_invalidate (&errpipe);
352 /* Wait for child to exit, even if we have
353 * an error pending.
355 again:
357 ret = waitpid (pid, &status, 0);
359 if (ret < 0)
361 if (errno == EINTR)
362 goto again;
363 else if (errno == ECHILD)
365 if (exit_status)
367 g_warning ("In call to g_spawn_sync(), exit status of a child process was requested but SIGCHLD action was set to SIG_IGN and ECHILD was received by waitpid(), so exit status can't be returned. This is a bug in the program calling g_spawn_sync(); either don't request the exit status, or don't set the SIGCHLD action.");
369 else
371 /* We don't need the exit status. */
374 else
376 if (!failed) /* avoid error pileups */
378 failed = TRUE;
380 g_set_error (error,
381 G_SPAWN_ERROR,
382 G_SPAWN_ERROR_READ,
383 _("Unexpected error in waitpid() (%s)"),
384 g_strerror (errno));
389 if (failed)
391 if (outstr)
392 g_string_free (outstr, TRUE);
393 if (errstr)
394 g_string_free (errstr, TRUE);
396 return FALSE;
398 else
400 if (exit_status)
401 *exit_status = status;
403 if (standard_output)
404 *standard_output = g_string_free (outstr, FALSE);
406 if (standard_error)
407 *standard_error = g_string_free (errstr, FALSE);
409 return TRUE;
414 * g_spawn_async_with_pipes:
415 * @working_directory: child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
416 * @argv: child's argument vector, in the GLib file name encoding
417 * @envp: child's environment, or %NULL to inherit parent's, in the GLib file name encoding
418 * @flags: flags from #GSpawnFlags
419 * @child_setup: function to run in the child just before exec()
420 * @user_data: user data for @child_setup
421 * @child_pid: return location for child process ID, or %NULL
422 * @standard_input: return location for file descriptor to write to child's stdin, or %NULL
423 * @standard_output: return location for file descriptor to read child's stdout, or %NULL
424 * @standard_error: return location for file descriptor to read child's stderr, or %NULL
425 * @error: return location for error
427 * Executes a child program asynchronously (your program will not
428 * block waiting for the child to exit). The child program is
429 * specified by the only argument that must be provided, @argv. @argv
430 * should be a %NULL-terminated array of strings, to be passed as the
431 * argument vector for the child. The first string in @argv is of
432 * course the name of the program to execute. By default, the name of
433 * the program must be a full path; the <envar>PATH</envar> shell variable
434 * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
436 * On Windows, note that all the string or string vector arguments to
437 * this function and the other g_spawn*() functions are in UTF-8, the
438 * GLib file name encoding. Unicode characters that are not part of
439 * the system codepage passed in argument vectors will be correctly
440 * available in the spawned program only if it uses wide character API
441 * to retrieve its command line. For C programs built with Microsoft's
442 * tools it is enough to make the program have a wmain() instead of
443 * main(). wmain() has a wide character argument vector as parameter.
445 * At least currently, mingw doesn't support wmain(), so if you use
446 * mingw to develop the spawned program, it will have to call the
447 * undocumented function __wgetmainargs() to get the wide character
448 * argument vector and environment. See gspawn-win32-helper.c in the
449 * GLib sources or init.c in the mingw runtime sources for a prototype
450 * for that function. Alternatively, you can retrieve the Win32 system
451 * level wide character command line passed to the spawned program
452 * using the GetCommandLineW() function.
454 * On Windows the low-level child process creation API
455 * <function>CreateProcess()</function> doesn't use argument vectors,
456 * but a command line. The C runtime library's
457 * <function>spawn*()</function> family of functions (which
458 * g_spawn_async_with_pipes() eventually calls) paste the argument
459 * vector elements together into a command line, and the C runtime startup code
460 * does a corresponding reconstruction of an argument vector from the
461 * command line, to be passed to main(). Complications arise when you have
462 * argument vector elements that contain spaces of double quotes. The
463 * <function>spawn*()</function> functions don't do any quoting or
464 * escaping, but on the other hand the startup code does do unquoting
465 * and unescaping in order to enable receiving arguments with embedded
466 * spaces or double quotes. To work around this asymmetry,
467 * g_spawn_async_with_pipes() will do quoting and escaping on argument
468 * vector elements that need it before calling the C runtime
469 * spawn() function.
471 * @envp is a %NULL-terminated array of strings, where each string
472 * has the form <literal>KEY=VALUE</literal>. This will become
473 * the child's environment. If @envp is %NULL, the child inherits its
474 * parent's environment.
476 * @flags should be the bitwise OR of any flags you want to affect the
477 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that
478 * the child will not automatically be reaped; you must use a
479 * #GChildWatch source to be notified about the death of the child
480 * process. Eventually you must call g_spawn_close_pid() on the
481 * @child_pid, in order to free resources which may be associated
482 * with the child process. (On Unix, using a #GChildWatch source is
483 * equivalent to calling waitpid() or handling the %SIGCHLD signal
484 * manually. On Windows, calling g_spawn_close_pid() is equivalent
485 * to calling CloseHandle() on the process handle returned in
486 * @child_pid).
488 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
489 * descriptors will be inherited by the child; otherwise all
490 * descriptors except stdin/stdout/stderr will be closed before
491 * calling exec() in the child. %G_SPAWN_SEARCH_PATH
492 * means that <literal>argv[0]</literal> need not be an absolute path, it
493 * will be looked for in the user's <envar>PATH</envar>.
494 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will
495 * be discarded, instead of going to the same location as the parent's
496 * standard output. If you use this flag, @standard_output must be %NULL.
497 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
498 * will be discarded, instead of going to the same location as the parent's
499 * standard error. If you use this flag, @standard_error must be %NULL.
500 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
501 * standard input (by default, the child's standard input is attached to
502 * /dev/null). If you use this flag, @standard_input must be %NULL.
503 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
504 * the file to execute, while the remaining elements are the
505 * actual argument vector to pass to the file. Normally
506 * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
507 * passes all of @argv to the child.
509 * @child_setup and @user_data are a function and user data. On POSIX
510 * platforms, the function is called in the child after GLib has
511 * performed all the setup it plans to perform (including creating
512 * pipes, closing file descriptors, etc.) but before calling
513 * exec(). That is, @child_setup is called just
514 * before calling exec() in the child. Obviously
515 * actions taken in this function will only affect the child, not the
516 * parent. On Windows, there is no separate fork() and exec()
517 * functionality. Child processes are created and run with
518 * a single API call, CreateProcess(). @child_setup is
519 * called in the parent process just before creating the child
520 * process. You should carefully consider what you do in @child_setup
521 * if you intend your software to be portable to Windows.
523 * If non-%NULL, @child_pid will on Unix be filled with the child's
524 * process ID. You can use the process ID to send signals to the
525 * child, or to waitpid() if you specified the
526 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
527 * filled with a handle to the child process only if you specified the
528 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
529 * process using the Win32 API, for example wait for its termination
530 * with the <function>WaitFor*()</function> functions, or examine its
531 * exit code with GetExitCodeProcess(). You should close the handle
532 * with CloseHandle() or g_spawn_close_pid() when you no longer need it.
534 * If non-%NULL, the @standard_input, @standard_output, @standard_error
535 * locations will be filled with file descriptors for writing to the child's
536 * standard input or reading from its standard output or standard error.
537 * The caller of g_spawn_async_with_pipes() must close these file descriptors
538 * when they are no longer in use. If these parameters are %NULL, the corresponding
539 * pipe won't be created.
541 * If @standard_input is NULL, the child's standard input is attached to /dev/null
542 * unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
544 * If @standard_error is NULL, the child's standard error goes to the same location
545 * as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL is set.
547 * If @standard_output is NULL, the child's standard output goes to the same location
548 * as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL is set.
550 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
551 * If an error is set, the function returns %FALSE. Errors
552 * are reported even if they occur in the child (for example if the
553 * executable in <literal>argv[0]</literal> is not found). Typically
554 * the <literal>message</literal> field of returned errors should be displayed
555 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
557 * If an error occurs, @child_pid, @standard_input, @standard_output,
558 * and @standard_error will not be filled with valid values.
560 * If @child_pid is not %NULL and an error does not occur then the returned
561 * pid must be closed using g_spawn_close_pid().
563 * Return value: %TRUE on success, %FALSE if an error was set
565 gboolean
566 g_spawn_async_with_pipes (const gchar *working_directory,
567 gchar **argv,
568 gchar **envp,
569 GSpawnFlags flags,
570 GSpawnChildSetupFunc child_setup,
571 gpointer user_data,
572 GPid *child_pid,
573 gint *standard_input,
574 gint *standard_output,
575 gint *standard_error,
576 GError **error)
578 g_return_val_if_fail (argv != NULL, FALSE);
579 g_return_val_if_fail (standard_output == NULL ||
580 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
581 g_return_val_if_fail (standard_error == NULL ||
582 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
583 /* can't inherit stdin if we have an input pipe. */
584 g_return_val_if_fail (standard_input == NULL ||
585 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
587 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
588 working_directory,
589 argv,
590 envp,
591 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
592 (flags & G_SPAWN_SEARCH_PATH) != 0,
593 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
594 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
595 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
596 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
597 child_setup,
598 user_data,
599 child_pid,
600 standard_input,
601 standard_output,
602 standard_error,
603 error);
607 * g_spawn_command_line_sync:
608 * @command_line: a command line
609 * @standard_output: return location for child output
610 * @standard_error: return location for child errors
611 * @exit_status: return location for child exit status, as returned by waitpid()
612 * @error: return location for errors
614 * A simple version of g_spawn_sync() with little-used parameters
615 * removed, taking a command line instead of an argument vector. See
616 * g_spawn_sync() for full details. @command_line will be parsed by
617 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
618 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
619 * implications, so consider using g_spawn_sync() directly if
620 * appropriate. Possible errors are those from g_spawn_sync() and those
621 * from g_shell_parse_argv().
623 * If @exit_status is non-%NULL, the exit status of the child is stored there as
624 * it would be returned by waitpid(); standard UNIX macros such as WIFEXITED()
625 * and WEXITSTATUS() must be used to evaluate the exit status.
627 * On Windows, please note the implications of g_shell_parse_argv()
628 * parsing @command_line. Parsing is done according to Unix shell rules, not
629 * Windows command interpreter rules.
630 * Space is a separator, and backslashes are
631 * special. Thus you cannot simply pass a @command_line containing
632 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
633 * the backslashes will be eaten, and the space will act as a
634 * separator. You need to enclose such paths with single quotes, like
635 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
637 * Return value: %TRUE on success, %FALSE if an error was set
639 gboolean
640 g_spawn_command_line_sync (const gchar *command_line,
641 gchar **standard_output,
642 gchar **standard_error,
643 gint *exit_status,
644 GError **error)
646 gboolean retval;
647 gchar **argv = NULL;
649 g_return_val_if_fail (command_line != NULL, FALSE);
651 if (!g_shell_parse_argv (command_line,
652 NULL, &argv,
653 error))
654 return FALSE;
656 retval = g_spawn_sync (NULL,
657 argv,
658 NULL,
659 G_SPAWN_SEARCH_PATH,
660 NULL,
661 NULL,
662 standard_output,
663 standard_error,
664 exit_status,
665 error);
666 g_strfreev (argv);
668 return retval;
672 * g_spawn_command_line_async:
673 * @command_line: a command line
674 * @error: return location for errors
676 * A simple version of g_spawn_async() that parses a command line with
677 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
678 * command line in the background. Unlike g_spawn_async(), the
679 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
680 * that %G_SPAWN_SEARCH_PATH can have security implications, so
681 * consider using g_spawn_async() directly if appropriate. Possible
682 * errors are those from g_shell_parse_argv() and g_spawn_async().
684 * The same concerns on Windows apply as for g_spawn_command_line_sync().
686 * Return value: %TRUE on success, %FALSE if error is set.
688 gboolean
689 g_spawn_command_line_async (const gchar *command_line,
690 GError **error)
692 gboolean retval;
693 gchar **argv = NULL;
695 g_return_val_if_fail (command_line != NULL, FALSE);
697 if (!g_shell_parse_argv (command_line,
698 NULL, &argv,
699 error))
700 return FALSE;
702 retval = g_spawn_async (NULL,
703 argv,
704 NULL,
705 G_SPAWN_SEARCH_PATH,
706 NULL,
707 NULL,
708 NULL,
709 error);
710 g_strfreev (argv);
712 return retval;
715 static gint
716 exec_err_to_g_error (gint en)
718 switch (en)
720 #ifdef EACCES
721 case EACCES:
722 return G_SPAWN_ERROR_ACCES;
723 break;
724 #endif
726 #ifdef EPERM
727 case EPERM:
728 return G_SPAWN_ERROR_PERM;
729 break;
730 #endif
732 #ifdef E2BIG
733 case E2BIG:
734 return G_SPAWN_ERROR_2BIG;
735 break;
736 #endif
738 #ifdef ENOEXEC
739 case ENOEXEC:
740 return G_SPAWN_ERROR_NOEXEC;
741 break;
742 #endif
744 #ifdef ENAMETOOLONG
745 case ENAMETOOLONG:
746 return G_SPAWN_ERROR_NAMETOOLONG;
747 break;
748 #endif
750 #ifdef ENOENT
751 case ENOENT:
752 return G_SPAWN_ERROR_NOENT;
753 break;
754 #endif
756 #ifdef ENOMEM
757 case ENOMEM:
758 return G_SPAWN_ERROR_NOMEM;
759 break;
760 #endif
762 #ifdef ENOTDIR
763 case ENOTDIR:
764 return G_SPAWN_ERROR_NOTDIR;
765 break;
766 #endif
768 #ifdef ELOOP
769 case ELOOP:
770 return G_SPAWN_ERROR_LOOP;
771 break;
772 #endif
774 #ifdef ETXTBUSY
775 case ETXTBUSY:
776 return G_SPAWN_ERROR_TXTBUSY;
777 break;
778 #endif
780 #ifdef EIO
781 case EIO:
782 return G_SPAWN_ERROR_IO;
783 break;
784 #endif
786 #ifdef ENFILE
787 case ENFILE:
788 return G_SPAWN_ERROR_NFILE;
789 break;
790 #endif
792 #ifdef EMFILE
793 case EMFILE:
794 return G_SPAWN_ERROR_MFILE;
795 break;
796 #endif
798 #ifdef EINVAL
799 case EINVAL:
800 return G_SPAWN_ERROR_INVAL;
801 break;
802 #endif
804 #ifdef EISDIR
805 case EISDIR:
806 return G_SPAWN_ERROR_ISDIR;
807 break;
808 #endif
810 #ifdef ELIBBAD
811 case ELIBBAD:
812 return G_SPAWN_ERROR_LIBBAD;
813 break;
814 #endif
816 default:
817 return G_SPAWN_ERROR_FAILED;
818 break;
822 static gssize
823 write_all (gint fd, gconstpointer vbuf, gsize to_write)
825 gchar *buf = (gchar *) vbuf;
827 while (to_write > 0)
829 gssize count = write (fd, buf, to_write);
830 if (count < 0)
832 if (errno != EINTR)
833 return FALSE;
835 else
837 to_write -= count;
838 buf += count;
842 return TRUE;
845 static void
846 write_err_and_exit (gint fd, gint msg)
848 gint en = errno;
850 write_all (fd, &msg, sizeof(msg));
851 write_all (fd, &en, sizeof(en));
853 _exit (1);
856 static void
857 set_cloexec (gint fd)
859 fcntl (fd, F_SETFD, FD_CLOEXEC);
862 static gint
863 sane_dup2 (gint fd1, gint fd2)
865 gint ret;
867 retry:
868 ret = dup2 (fd1, fd2);
869 if (ret < 0 && errno == EINTR)
870 goto retry;
872 return ret;
875 enum
877 CHILD_CHDIR_FAILED,
878 CHILD_EXEC_FAILED,
879 CHILD_DUP2_FAILED,
880 CHILD_FORK_FAILED
883 static void
884 do_exec (gint child_err_report_fd,
885 gint stdin_fd,
886 gint stdout_fd,
887 gint stderr_fd,
888 const gchar *working_directory,
889 gchar **argv,
890 gchar **envp,
891 gboolean close_descriptors,
892 gboolean search_path,
893 gboolean stdout_to_null,
894 gboolean stderr_to_null,
895 gboolean child_inherits_stdin,
896 gboolean file_and_argv_zero,
897 GSpawnChildSetupFunc child_setup,
898 gpointer user_data)
900 if (working_directory && chdir (working_directory) < 0)
901 write_err_and_exit (child_err_report_fd,
902 CHILD_CHDIR_FAILED);
904 /* Close all file descriptors but stdin stdout and stderr as
905 * soon as we exec. Note that this includes
906 * child_err_report_fd, which keeps the parent from blocking
907 * forever on the other end of that pipe.
909 if (close_descriptors)
911 gint open_max;
912 gint i;
914 open_max = sysconf (_SC_OPEN_MAX);
915 for (i = 3; i < open_max; i++)
916 set_cloexec (i);
918 else
920 /* We need to do child_err_report_fd anyway */
921 set_cloexec (child_err_report_fd);
924 /* Redirect pipes as required */
926 if (stdin_fd >= 0)
928 /* dup2 can't actually fail here I don't think */
930 if (sane_dup2 (stdin_fd, 0) < 0)
931 write_err_and_exit (child_err_report_fd,
932 CHILD_DUP2_FAILED);
934 /* ignore this if it doesn't work */
935 close_and_invalidate (&stdin_fd);
937 else if (!child_inherits_stdin)
939 /* Keep process from blocking on a read of stdin */
940 gint read_null = open ("/dev/null", O_RDONLY);
941 sane_dup2 (read_null, 0);
942 close_and_invalidate (&read_null);
945 if (stdout_fd >= 0)
947 /* dup2 can't actually fail here I don't think */
949 if (sane_dup2 (stdout_fd, 1) < 0)
950 write_err_and_exit (child_err_report_fd,
951 CHILD_DUP2_FAILED);
953 /* ignore this if it doesn't work */
954 close_and_invalidate (&stdout_fd);
956 else if (stdout_to_null)
958 gint write_null = open ("/dev/null", O_WRONLY);
959 sane_dup2 (write_null, 1);
960 close_and_invalidate (&write_null);
963 if (stderr_fd >= 0)
965 /* dup2 can't actually fail here I don't think */
967 if (sane_dup2 (stderr_fd, 2) < 0)
968 write_err_and_exit (child_err_report_fd,
969 CHILD_DUP2_FAILED);
971 /* ignore this if it doesn't work */
972 close_and_invalidate (&stderr_fd);
974 else if (stderr_to_null)
976 gint write_null = open ("/dev/null", O_WRONLY);
977 sane_dup2 (write_null, 2);
978 close_and_invalidate (&write_null);
981 /* Call user function just before we exec */
982 if (child_setup)
984 (* child_setup) (user_data);
987 g_execute (argv[0],
988 file_and_argv_zero ? argv + 1 : argv,
989 envp, search_path);
991 /* Exec failed */
992 write_err_and_exit (child_err_report_fd,
993 CHILD_EXEC_FAILED);
996 static gboolean
997 read_ints (int fd,
998 gint* buf,
999 gint n_ints_in_buf,
1000 gint *n_ints_read,
1001 GError **error)
1003 gsize bytes = 0;
1005 while (TRUE)
1007 gssize chunk;
1009 if (bytes >= sizeof(gint)*2)
1010 break; /* give up, who knows what happened, should not be
1011 * possible.
1014 again:
1015 chunk = read (fd,
1016 ((gchar*)buf) + bytes,
1017 sizeof(gint) * n_ints_in_buf - bytes);
1018 if (chunk < 0 && errno == EINTR)
1019 goto again;
1021 if (chunk < 0)
1023 /* Some weird shit happened, bail out */
1025 g_set_error (error,
1026 G_SPAWN_ERROR,
1027 G_SPAWN_ERROR_FAILED,
1028 _("Failed to read from child pipe (%s)"),
1029 g_strerror (errno));
1031 return FALSE;
1033 else if (chunk == 0)
1034 break; /* EOF */
1035 else /* chunk > 0 */
1036 bytes += chunk;
1039 *n_ints_read = (gint)(bytes / sizeof(gint));
1041 return TRUE;
1044 static gboolean
1045 fork_exec_with_pipes (gboolean intermediate_child,
1046 const gchar *working_directory,
1047 gchar **argv,
1048 gchar **envp,
1049 gboolean close_descriptors,
1050 gboolean search_path,
1051 gboolean stdout_to_null,
1052 gboolean stderr_to_null,
1053 gboolean child_inherits_stdin,
1054 gboolean file_and_argv_zero,
1055 GSpawnChildSetupFunc child_setup,
1056 gpointer user_data,
1057 GPid *child_pid,
1058 gint *standard_input,
1059 gint *standard_output,
1060 gint *standard_error,
1061 GError **error)
1063 GPid pid = -1;
1064 gint stdin_pipe[2] = { -1, -1 };
1065 gint stdout_pipe[2] = { -1, -1 };
1066 gint stderr_pipe[2] = { -1, -1 };
1067 gint child_err_report_pipe[2] = { -1, -1 };
1068 gint child_pid_report_pipe[2] = { -1, -1 };
1069 gint status;
1071 if (!make_pipe (child_err_report_pipe, error))
1072 return FALSE;
1074 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1075 goto cleanup_and_fail;
1077 if (standard_input && !make_pipe (stdin_pipe, error))
1078 goto cleanup_and_fail;
1080 if (standard_output && !make_pipe (stdout_pipe, error))
1081 goto cleanup_and_fail;
1083 if (standard_error && !make_pipe (stderr_pipe, error))
1084 goto cleanup_and_fail;
1086 pid = fork ();
1088 if (pid < 0)
1090 g_set_error (error,
1091 G_SPAWN_ERROR,
1092 G_SPAWN_ERROR_FORK,
1093 _("Failed to fork (%s)"),
1094 g_strerror (errno));
1096 goto cleanup_and_fail;
1098 else if (pid == 0)
1100 /* Immediate child. This may or may not be the child that
1101 * actually execs the new process.
1104 /* Be sure we crash if the parent exits
1105 * and we write to the err_report_pipe
1107 signal (SIGPIPE, SIG_DFL);
1109 /* Close the parent's end of the pipes;
1110 * not needed in the close_descriptors case,
1111 * though
1113 close_and_invalidate (&child_err_report_pipe[0]);
1114 close_and_invalidate (&child_pid_report_pipe[0]);
1115 close_and_invalidate (&stdin_pipe[1]);
1116 close_and_invalidate (&stdout_pipe[0]);
1117 close_and_invalidate (&stderr_pipe[0]);
1119 if (intermediate_child)
1121 /* We need to fork an intermediate child that launches the
1122 * final child. The purpose of the intermediate child
1123 * is to exit, so we can waitpid() it immediately.
1124 * Then the grandchild will not become a zombie.
1126 GPid grandchild_pid;
1128 grandchild_pid = fork ();
1130 if (grandchild_pid < 0)
1132 /* report -1 as child PID */
1133 write_all (child_pid_report_pipe[1], &grandchild_pid,
1134 sizeof(grandchild_pid));
1136 write_err_and_exit (child_err_report_pipe[1],
1137 CHILD_FORK_FAILED);
1139 else if (grandchild_pid == 0)
1141 do_exec (child_err_report_pipe[1],
1142 stdin_pipe[0],
1143 stdout_pipe[1],
1144 stderr_pipe[1],
1145 working_directory,
1146 argv,
1147 envp,
1148 close_descriptors,
1149 search_path,
1150 stdout_to_null,
1151 stderr_to_null,
1152 child_inherits_stdin,
1153 file_and_argv_zero,
1154 child_setup,
1155 user_data);
1157 else
1159 write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1160 close_and_invalidate (&child_pid_report_pipe[1]);
1162 _exit (0);
1165 else
1167 /* Just run the child.
1170 do_exec (child_err_report_pipe[1],
1171 stdin_pipe[0],
1172 stdout_pipe[1],
1173 stderr_pipe[1],
1174 working_directory,
1175 argv,
1176 envp,
1177 close_descriptors,
1178 search_path,
1179 stdout_to_null,
1180 stderr_to_null,
1181 child_inherits_stdin,
1182 file_and_argv_zero,
1183 child_setup,
1184 user_data);
1187 else
1189 /* Parent */
1191 gint buf[2];
1192 gint n_ints = 0;
1194 /* Close the uncared-about ends of the pipes */
1195 close_and_invalidate (&child_err_report_pipe[1]);
1196 close_and_invalidate (&child_pid_report_pipe[1]);
1197 close_and_invalidate (&stdin_pipe[0]);
1198 close_and_invalidate (&stdout_pipe[1]);
1199 close_and_invalidate (&stderr_pipe[1]);
1201 /* If we had an intermediate child, reap it */
1202 if (intermediate_child)
1204 wait_again:
1205 if (waitpid (pid, &status, 0) < 0)
1207 if (errno == EINTR)
1208 goto wait_again;
1209 else if (errno == ECHILD)
1210 ; /* do nothing, child already reaped */
1211 else
1212 g_warning ("waitpid() should not fail in "
1213 "'fork_exec_with_pipes'");
1218 if (!read_ints (child_err_report_pipe[0],
1219 buf, 2, &n_ints,
1220 error))
1221 goto cleanup_and_fail;
1223 if (n_ints >= 2)
1225 /* Error from the child. */
1227 switch (buf[0])
1229 case CHILD_CHDIR_FAILED:
1230 g_set_error (error,
1231 G_SPAWN_ERROR,
1232 G_SPAWN_ERROR_CHDIR,
1233 _("Failed to change to directory '%s' (%s)"),
1234 working_directory,
1235 g_strerror (buf[1]));
1237 break;
1239 case CHILD_EXEC_FAILED:
1240 g_set_error (error,
1241 G_SPAWN_ERROR,
1242 exec_err_to_g_error (buf[1]),
1243 _("Failed to execute child process \"%s\" (%s)"),
1244 argv[0],
1245 g_strerror (buf[1]));
1247 break;
1249 case CHILD_DUP2_FAILED:
1250 g_set_error (error,
1251 G_SPAWN_ERROR,
1252 G_SPAWN_ERROR_FAILED,
1253 _("Failed to redirect output or input of child process (%s)"),
1254 g_strerror (buf[1]));
1256 break;
1258 case CHILD_FORK_FAILED:
1259 g_set_error (error,
1260 G_SPAWN_ERROR,
1261 G_SPAWN_ERROR_FORK,
1262 _("Failed to fork child process (%s)"),
1263 g_strerror (buf[1]));
1264 break;
1266 default:
1267 g_set_error (error,
1268 G_SPAWN_ERROR,
1269 G_SPAWN_ERROR_FAILED,
1270 _("Unknown error executing child process \"%s\""),
1271 argv[0]);
1272 break;
1275 goto cleanup_and_fail;
1278 /* Get child pid from intermediate child pipe. */
1279 if (intermediate_child)
1281 n_ints = 0;
1283 if (!read_ints (child_pid_report_pipe[0],
1284 buf, 1, &n_ints, error))
1285 goto cleanup_and_fail;
1287 if (n_ints < 1)
1289 g_set_error (error,
1290 G_SPAWN_ERROR,
1291 G_SPAWN_ERROR_FAILED,
1292 _("Failed to read enough data from child pid pipe (%s)"),
1293 g_strerror (errno));
1294 goto cleanup_and_fail;
1296 else
1298 /* we have the child pid */
1299 pid = buf[0];
1303 /* Success against all odds! return the information */
1304 close_and_invalidate (&child_err_report_pipe[0]);
1305 close_and_invalidate (&child_pid_report_pipe[0]);
1307 if (child_pid)
1308 *child_pid = pid;
1310 if (standard_input)
1311 *standard_input = stdin_pipe[1];
1312 if (standard_output)
1313 *standard_output = stdout_pipe[0];
1314 if (standard_error)
1315 *standard_error = stderr_pipe[0];
1317 return TRUE;
1320 cleanup_and_fail:
1322 /* There was an error from the Child, reap the child to avoid it being
1323 a zombie.
1326 if (pid > 0)
1328 wait_failed:
1329 if (waitpid (pid, NULL, 0) < 0)
1331 if (errno == EINTR)
1332 goto wait_failed;
1333 else if (errno == ECHILD)
1334 ; /* do nothing, child already reaped */
1335 else
1336 g_warning ("waitpid() should not fail in "
1337 "'fork_exec_with_pipes'");
1341 close_and_invalidate (&child_err_report_pipe[0]);
1342 close_and_invalidate (&child_err_report_pipe[1]);
1343 close_and_invalidate (&child_pid_report_pipe[0]);
1344 close_and_invalidate (&child_pid_report_pipe[1]);
1345 close_and_invalidate (&stdin_pipe[0]);
1346 close_and_invalidate (&stdin_pipe[1]);
1347 close_and_invalidate (&stdout_pipe[0]);
1348 close_and_invalidate (&stdout_pipe[1]);
1349 close_and_invalidate (&stderr_pipe[0]);
1350 close_and_invalidate (&stderr_pipe[1]);
1352 return FALSE;
1355 static gboolean
1356 make_pipe (gint p[2],
1357 GError **error)
1359 if (pipe (p) < 0)
1361 g_set_error (error,
1362 G_SPAWN_ERROR,
1363 G_SPAWN_ERROR_FAILED,
1364 _("Failed to create pipe for communicating with child process (%s)"),
1365 g_strerror (errno));
1366 return FALSE;
1368 else
1369 return TRUE;
1372 /* Based on execvp from GNU C Library */
1374 static void
1375 script_execute (const gchar *file,
1376 gchar **argv,
1377 gchar **envp,
1378 gboolean search_path)
1380 /* Count the arguments. */
1381 int argc = 0;
1382 while (argv[argc])
1383 ++argc;
1385 /* Construct an argument list for the shell. */
1387 gchar **new_argv;
1389 new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1391 new_argv[0] = (char *) "/bin/sh";
1392 new_argv[1] = (char *) file;
1393 while (argc > 0)
1395 new_argv[argc + 1] = argv[argc];
1396 --argc;
1399 /* Execute the shell. */
1400 if (envp)
1401 execve (new_argv[0], new_argv, envp);
1402 else
1403 execv (new_argv[0], new_argv);
1405 g_free (new_argv);
1409 static gchar*
1410 my_strchrnul (const gchar *str, gchar c)
1412 gchar *p = (gchar*) str;
1413 while (*p && (*p != c))
1414 ++p;
1416 return p;
1419 static gint
1420 g_execute (const gchar *file,
1421 gchar **argv,
1422 gchar **envp,
1423 gboolean search_path)
1425 if (*file == '\0')
1427 /* We check the simple case first. */
1428 errno = ENOENT;
1429 return -1;
1432 if (!search_path || strchr (file, '/') != NULL)
1434 /* Don't search when it contains a slash. */
1435 if (envp)
1436 execve (file, argv, envp);
1437 else
1438 execv (file, argv);
1440 if (errno == ENOEXEC)
1441 script_execute (file, argv, envp, FALSE);
1443 else
1445 gboolean got_eacces = 0;
1446 const gchar *path, *p;
1447 gchar *name, *freeme;
1448 size_t len;
1449 size_t pathlen;
1451 path = g_getenv ("PATH");
1452 if (path == NULL)
1454 /* There is no `PATH' in the environment. The default
1455 * search path in libc is the current directory followed by
1456 * the path `confstr' returns for `_CS_PATH'.
1459 /* In GLib we put . last, for security, and don't use the
1460 * unportable confstr(); UNIX98 does not actually specify
1461 * what to search if PATH is unset. POSIX may, dunno.
1464 path = "/bin:/usr/bin:.";
1467 len = strlen (file) + 1;
1468 pathlen = strlen (path);
1469 freeme = name = g_malloc (pathlen + len + 1);
1471 /* Copy the file name at the top, including '\0' */
1472 memcpy (name + pathlen + 1, file, len);
1473 name = name + pathlen;
1474 /* And add the slash before the filename */
1475 *name = '/';
1477 p = path;
1480 char *startp;
1482 path = p;
1483 p = my_strchrnul (path, ':');
1485 if (p == path)
1486 /* Two adjacent colons, or a colon at the beginning or the end
1487 * of `PATH' means to search the current directory.
1489 startp = name + 1;
1490 else
1491 startp = memcpy (name - (p - path), path, p - path);
1493 /* Try to execute this name. If it works, execv will not return. */
1494 if (envp)
1495 execve (startp, argv, envp);
1496 else
1497 execv (startp, argv);
1499 if (errno == ENOEXEC)
1500 script_execute (startp, argv, envp, search_path);
1502 switch (errno)
1504 case EACCES:
1505 /* Record the we got a `Permission denied' error. If we end
1506 * up finding no executable we can use, we want to diagnose
1507 * that we did find one but were denied access.
1509 got_eacces = TRUE;
1511 /* FALL THRU */
1513 case ENOENT:
1514 #ifdef ESTALE
1515 case ESTALE:
1516 #endif
1517 #ifdef ENOTDIR
1518 case ENOTDIR:
1519 #endif
1520 /* Those errors indicate the file is missing or not executable
1521 * by us, in which case we want to just try the next path
1522 * directory.
1524 break;
1526 default:
1527 /* Some other error means we found an executable file, but
1528 * something went wrong executing it; return the error to our
1529 * caller.
1531 g_free (freeme);
1532 return -1;
1535 while (*p++ != '\0');
1537 /* We tried every element and none of them worked. */
1538 if (got_eacces)
1539 /* At least one failure was due to permissions, so report that
1540 * error.
1542 errno = EACCES;
1544 g_free (freeme);
1547 /* Return the error from the last attempt (probably ENOENT). */
1548 return -1;
1552 * g_spawn_close_pid:
1553 * @pid: The process identifier to close
1555 * On some platforms, notably WIN32, the #GPid type represents a resource
1556 * which must be closed to prevent resource leaking. g_spawn_close_pid()
1557 * is provided for this purpose. It should be used on all platforms, even
1558 * though it doesn't do anything under UNIX.
1560 void
1561 g_spawn_close_pid (GPid pid)
1565 #define __G_SPAWN_C__
1566 #include "galiasdef.c"