Include <string.h> for memcpy.
[glib.git] / gspawn.c
blobc8208f6ca4c8a5ed8eb4da37f1d50f7d3ef0d7c5
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 "glib.h"
24 #include <sys/time.h>
25 #include <sys/types.h>
26 #include <sys/wait.h>
27 #include <unistd.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <string.h>
33 #ifdef HAVE_SYS_SELECT_H
34 #include <sys/select.h>
35 #endif /* HAVE_SYS_SELECT_H */
37 #include "glibintl.h"
39 static gint g_execute (const gchar *file,
40 gchar **argv,
41 gchar **envp,
42 gboolean search_path);
44 static gboolean make_pipe (gint p[2],
45 GError **error);
46 static gboolean fork_exec_with_pipes (gboolean intermediate_child,
47 const gchar *working_directory,
48 gchar **argv,
49 gchar **envp,
50 gboolean close_descriptors,
51 gboolean search_path,
52 gboolean stdout_to_null,
53 gboolean stderr_to_null,
54 gboolean child_inherits_stdin,
55 GSpawnChildSetupFunc child_setup,
56 gpointer user_data,
57 gint *child_pid,
58 gint *standard_input,
59 gint *standard_output,
60 gint *standard_error,
61 GError **error);
63 GQuark
64 g_spawn_error_quark (void)
66 static GQuark quark = 0;
67 if (quark == 0)
68 quark = g_quark_from_static_string ("g-exec-error-quark");
69 return quark;
72 /**
73 * g_spawn_async:
74 * @working_directory: child's current working directory, or NULL to inherit parent's
75 * @argv: child's argument vector
76 * @envp: child's environment, or NULL to inherit parent's
77 * @flags: flags from #GSpawnFlags
78 * @child_setup: function to run in the child just before exec()
79 * @user_data: user data for @child_setup
80 * @child_pid: return location for child process ID, or NULL
81 * @error: return location for error
83 * See g_spawn_async_with_pipes() for a full description; this function
84 * simply calls the g_spawn_async_with_pipes() without any pipes.
86 * Return value: TRUE on success, FALSE if error is set
87 **/
88 gboolean
89 g_spawn_async (const gchar *working_directory,
90 gchar **argv,
91 gchar **envp,
92 GSpawnFlags flags,
93 GSpawnChildSetupFunc child_setup,
94 gpointer user_data,
95 gint *child_pid,
96 GError **error)
98 g_return_val_if_fail (argv != NULL, FALSE);
100 return g_spawn_async_with_pipes (working_directory,
101 argv, envp,
102 flags,
103 child_setup,
104 user_data,
105 child_pid,
106 NULL, NULL, NULL,
107 error);
110 /* Avoids a danger in threaded situations (calling close()
111 * on a file descriptor twice, and another thread has
112 * re-opened it since the first close)
114 static gint
115 close_and_invalidate (gint *fd)
117 gint ret;
119 ret = close (*fd);
120 *fd = -1;
122 return ret;
125 typedef enum
127 READ_FAILED = 0, /* FALSE */
128 READ_OK,
129 READ_EOF
130 } ReadResult;
132 static ReadResult
133 read_data (GString *str,
134 gint fd,
135 GError **error)
137 gint bytes;
138 gchar buf[4096];
140 again:
142 bytes = read (fd, &buf, 4096);
144 if (bytes == 0)
145 return READ_EOF;
146 else if (bytes > 0)
148 g_string_append_len (str, buf, bytes);
149 return READ_OK;
151 else if (bytes < 0 && errno == EINTR)
152 goto again;
153 else if (bytes < 0)
155 g_set_error (error,
156 G_SPAWN_ERROR,
157 G_SPAWN_ERROR_READ,
158 _("Failed to read data from child process (%s)"),
159 g_strerror (errno));
161 return READ_FAILED;
163 else
164 return READ_OK;
168 * g_spawn_sync:
169 * @working_directory: child's current working directory, or NULL to inherit parent's
170 * @argv: child's argument vector
171 * @envp: child's environment, or NULL to inherit parent's
172 * @flags: flags from #GSpawnFlags
173 * @child_setup: function to run in the child just before exec()
174 * @user_data: user data for @child_setup
175 * @standard_output: return location for child output
176 * @standard_error: return location for child error messages
177 * @exit_status: child exit status, as returned by waitpid()
178 * @error: return location for error
180 * Executes a child synchronously (waits for the child to exit before returning).
181 * All output from the child is stored in @standard_output and @standard_error,
182 * if those parameters are non-NULL. If @exit_status is non-NULL, the exit status
183 * of the child is stored there as it would be by waitpid(); standard UNIX
184 * macros such as WIFEXITED() and WEXITSTATUS() must be used to evaluate the
185 * exit status. If an error occurs, no data is returned in @standard_output,
186 * @standard_error, or @exit_status.
188 * This function calls g_spawn_async_with_pipes() internally; see that function
189 * for full details on the other parameters.
191 * Return value: TRUE on success, FALSE if an error was set.
193 gboolean
194 g_spawn_sync (const gchar *working_directory,
195 gchar **argv,
196 gchar **envp,
197 GSpawnFlags flags,
198 GSpawnChildSetupFunc child_setup,
199 gpointer user_data,
200 gchar **standard_output,
201 gchar **standard_error,
202 gint *exit_status,
203 GError **error)
205 gint outpipe = -1;
206 gint errpipe = -1;
207 gint pid;
208 fd_set fds;
209 gint ret;
210 GString *outstr = NULL;
211 GString *errstr = NULL;
212 gboolean failed;
213 gint status;
215 g_return_val_if_fail (argv != NULL, FALSE);
216 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
217 g_return_val_if_fail (standard_output == NULL ||
218 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
219 g_return_val_if_fail (standard_error == NULL ||
220 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
222 /* Just to ensure segfaults if callers try to use
223 * these when an error is reported.
225 if (standard_output)
226 *standard_output = NULL;
228 if (standard_error)
229 *standard_error = NULL;
231 if (!fork_exec_with_pipes (FALSE,
232 working_directory,
233 argv,
234 envp,
235 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
236 (flags & G_SPAWN_SEARCH_PATH) != 0,
237 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
238 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
239 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
240 child_setup,
241 user_data,
242 &pid,
243 NULL,
244 standard_output ? &outpipe : NULL,
245 standard_error ? &errpipe : NULL,
246 error))
247 return FALSE;
249 /* Read data from child. */
251 failed = FALSE;
253 if (outpipe >= 0)
255 outstr = g_string_new ("");
258 if (errpipe >= 0)
260 errstr = g_string_new ("");
263 /* Read data until we get EOF on both pipes. */
264 while (!failed &&
265 (outpipe >= 0 ||
266 errpipe >= 0))
268 ret = 0;
270 FD_ZERO (&fds);
271 if (outpipe >= 0)
272 FD_SET (outpipe, &fds);
273 if (errpipe >= 0)
274 FD_SET (errpipe, &fds);
276 ret = select (MAX (outpipe, errpipe) + 1,
277 &fds,
278 NULL, NULL,
279 NULL /* no timeout */);
281 if (ret < 0 && errno != EINTR)
283 failed = TRUE;
285 g_set_error (error,
286 G_SPAWN_ERROR,
287 G_SPAWN_ERROR_READ,
288 _("Unexpected error in select() reading data from a child process (%s)"),
289 g_strerror (errno));
291 break;
294 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
296 switch (read_data (outstr, outpipe, error))
298 case READ_FAILED:
299 failed = TRUE;
300 break;
301 case READ_EOF:
302 close_and_invalidate (&outpipe);
303 outpipe = -1;
304 break;
305 default:
306 break;
309 if (failed)
310 break;
313 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
315 switch (read_data (errstr, errpipe, error))
317 case READ_FAILED:
318 failed = TRUE;
319 break;
320 case READ_EOF:
321 close_and_invalidate (&errpipe);
322 errpipe = -1;
323 break;
324 default:
325 break;
328 if (failed)
329 break;
333 /* These should only be open still if we had an error. */
335 if (outpipe >= 0)
336 close_and_invalidate (&outpipe);
337 if (errpipe >= 0)
338 close_and_invalidate (&errpipe);
340 /* Wait for child to exit, even if we have
341 * an error pending.
343 again:
345 ret = waitpid (pid, &status, 0);
347 if (ret < 0)
349 if (errno == EINTR)
350 goto again;
351 else if (errno == ECHILD)
353 if (exit_status)
355 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.");
357 else
359 /* We don't need the exit status. */
362 else
364 if (!failed) /* avoid error pileups */
366 failed = TRUE;
368 g_set_error (error,
369 G_SPAWN_ERROR,
370 G_SPAWN_ERROR_READ,
371 _("Unexpected error in waitpid() (%s)"),
372 g_strerror (errno));
377 if (failed)
379 if (outstr)
380 g_string_free (outstr, TRUE);
381 if (errstr)
382 g_string_free (errstr, TRUE);
384 return FALSE;
386 else
388 if (exit_status)
389 *exit_status = status;
391 if (standard_output)
392 *standard_output = g_string_free (outstr, FALSE);
394 if (standard_error)
395 *standard_error = g_string_free (errstr, FALSE);
397 return TRUE;
402 * g_spawn_async_with_pipes:
403 * @working_directory: child's current working directory, or NULL to inherit parent's
404 * @argv: child's argument vector
405 * @envp: child's environment, or NULL to inherit parent's
406 * @flags: flags from #GSpawnFlags
407 * @child_setup: function to run in the child just before exec()
408 * @user_data: user data for @child_setup
409 * @child_pid: return location for child process ID, or NULL
410 * @standard_input: return location for file descriptor to write to child's stdin, or NULL
411 * @standard_output: return location for file descriptor to read child's stdout, or NULL
412 * @standard_error: return location for file descriptor to read child's stderr, or NULL
413 * @error: return location for error
415 * Executes a child program asynchronously (your program will not
416 * block waiting for the child to exit). The child program is
417 * specified by the only argument that must be provided, @argv. @argv
418 * should be a NULL-terminated array of strings, to be passed as the
419 * argument vector for the child. The first string in @argv is of
420 * course the name of the program to execute. By default, the name of
421 * the program must be a full path; the PATH shell variable will only
422 * be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
424 * @envp is a NULL-terminated array of strings, where each string
425 * has the form <literal>KEY=VALUE</literal>. This will become
426 * the child's environment. If @envp is NULL, the child inherits its
427 * parent's environment.
429 * @flags should be the bitwise OR of any flags you want to affect the
430 * function's behavior. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
431 * child will not be automatically reaped; you must call waitpid() or
432 * handle SIGCHLD yourself, or the child will become a zombie.
433 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
434 * descriptors will be inherited by the child; otherwise all
435 * descriptors except stdin/stdout/stderr will be closed before
436 * calling exec() in the child. %G_SPAWN_SEARCH_PATH means that
437 * <literal>argv[0]</literal> need not be an absolute path, it
438 * will be looked for in the user's PATH. %G_SPAWN_STDOUT_TO_DEV_NULL
439 * means that the child's standad output will be discarded, instead
440 * of going to the same location as the parent's standard output.
441 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
442 * will be discarded. %G_SPAWN_CHILD_INHERITS_STDIN means that
443 * the child will inherit the parent's standard input (by default,
444 * the child's standard input is attached to /dev/null).
446 * @child_setup and @user_data are a function and user data to be
447 * called in the child after GLib has performed all the setup it plans
448 * to perform (including creating pipes, closing file descriptors,
449 * etc.) but before calling exec(). That is, @child_setup is called
450 * just before calling exec() in the child. Obviously actions taken in
451 * this function will only affect the child, not the parent.
453 * If non-NULL, @child_pid will be filled with the child's process
454 * ID. You can use the process ID to send signals to the child, or
455 * to waitpid() if you specified the %G_SPAWN_DO_NOT_REAP_CHILD flag.
457 * If non-NULL, the @standard_input, @standard_output, @standard_error
458 * locations will be filled with file descriptors for writing to the child's
459 * standard input or reading from its standard output or standard error.
460 * The caller of g_spawn_async_with_pipes() must close these file descriptors
461 * when they are no longer in use. If these parameters are NULL, the
462 * corresponding pipe won't be created.
464 * @error can be NULL to ignore errors, or non-NULL to report errors.
465 * If an error is set, the function returns FALSE. Errors
466 * are reported even if they occur in the child (for example if the
467 * executable in <literal>argv[0]</literal> is not found). Typically
468 * the <literal>message</literal> field of returned errors should be displayed
469 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
471 * If an error occurs, @child_pid, @standard_input, @standard_output,
472 * and @standard_error will not be filled with valid values.
474 * Return value: TRUE on success, FALSE if an error was set
476 gboolean
477 g_spawn_async_with_pipes (const gchar *working_directory,
478 gchar **argv,
479 gchar **envp,
480 GSpawnFlags flags,
481 GSpawnChildSetupFunc child_setup,
482 gpointer user_data,
483 gint *child_pid,
484 gint *standard_input,
485 gint *standard_output,
486 gint *standard_error,
487 GError **error)
489 g_return_val_if_fail (argv != NULL, FALSE);
490 g_return_val_if_fail (standard_output == NULL ||
491 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
492 g_return_val_if_fail (standard_error == NULL ||
493 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
494 /* can't inherit stdin if we have an input pipe. */
495 g_return_val_if_fail (standard_input == NULL ||
496 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
498 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
499 working_directory,
500 argv,
501 envp,
502 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
503 (flags & G_SPAWN_SEARCH_PATH) != 0,
504 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
505 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
506 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
507 child_setup,
508 user_data,
509 child_pid,
510 standard_input,
511 standard_output,
512 standard_error,
513 error);
517 * g_spawn_command_line_sync:
518 * @command_line: a command line
519 * @standard_output: return location for child output
520 * @standard_error: return location for child errors
521 * @exit_status: return location for child exit status
522 * @error: return location for errors
524 * A simple version of g_spawn_sync() with little-used parameters
525 * removed, taking a command line instead of an argument vector. See
526 * g_spawn_sync() for full details. @command_line will be parsed by
527 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
528 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
529 * implications, so consider using g_spawn_sync() directly if
530 * appropriate. Possible errors are those from g_spawn_sync() and those
531 * from g_shell_parse_argv().
533 * Return value: TRUE on success, FALSE if an error was set
535 gboolean
536 g_spawn_command_line_sync (const gchar *command_line,
537 gchar **standard_output,
538 gchar **standard_error,
539 gint *exit_status,
540 GError **error)
542 gboolean retval;
543 gchar **argv = 0;
545 g_return_val_if_fail (command_line != NULL, FALSE);
547 if (!g_shell_parse_argv (command_line,
548 NULL, &argv,
549 error))
550 return FALSE;
552 retval = g_spawn_sync (NULL,
553 argv,
554 NULL,
555 G_SPAWN_SEARCH_PATH,
556 NULL,
557 NULL,
558 standard_output,
559 standard_error,
560 exit_status,
561 error);
562 g_strfreev (argv);
564 return retval;
568 * g_spawn_command_line_async:
569 * @command_line: a command line
570 * @error: return location for errors
572 * A simple version of g_spawn_async() that parses a command line with
573 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
574 * command line in the background. Unlike g_spawn_async(), the
575 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
576 * that %G_SPAWN_SEARCH_PATH can have security implications, so
577 * consider using g_spawn_async() directly if appropriate. Possible
578 * errors are those from g_shell_parse_argv() and g_spawn_async().
580 * Return value: TRUE on success, FALSE if error is set.
582 gboolean
583 g_spawn_command_line_async (const gchar *command_line,
584 GError **error)
586 gboolean retval;
587 gchar **argv = 0;
589 g_return_val_if_fail (command_line != NULL, FALSE);
591 if (!g_shell_parse_argv (command_line,
592 NULL, &argv,
593 error))
594 return FALSE;
596 retval = g_spawn_async (NULL,
597 argv,
598 NULL,
599 G_SPAWN_SEARCH_PATH,
600 NULL,
601 NULL,
602 NULL,
603 error);
604 g_strfreev (argv);
606 return retval;
609 static gint
610 exec_err_to_g_error (gint en)
612 switch (en)
614 #ifdef EACCES
615 case EACCES:
616 return G_SPAWN_ERROR_ACCES;
617 break;
618 #endif
620 #ifdef EPERM
621 case EPERM:
622 return G_SPAWN_ERROR_PERM;
623 break;
624 #endif
626 #ifdef E2BIG
627 case E2BIG:
628 return G_SPAWN_ERROR_2BIG;
629 break;
630 #endif
632 #ifdef ENOEXEC
633 case ENOEXEC:
634 return G_SPAWN_ERROR_NOEXEC;
635 break;
636 #endif
638 #ifdef ENAMETOOLONG
639 case ENAMETOOLONG:
640 return G_SPAWN_ERROR_NAMETOOLONG;
641 break;
642 #endif
644 #ifdef ENOENT
645 case ENOENT:
646 return G_SPAWN_ERROR_NOENT;
647 break;
648 #endif
650 #ifdef ENOMEM
651 case ENOMEM:
652 return G_SPAWN_ERROR_NOMEM;
653 break;
654 #endif
656 #ifdef ENOTDIR
657 case ENOTDIR:
658 return G_SPAWN_ERROR_NOTDIR;
659 break;
660 #endif
662 #ifdef ELOOP
663 case ELOOP:
664 return G_SPAWN_ERROR_LOOP;
665 break;
666 #endif
668 #ifdef ETXTBUSY
669 case ETXTBUSY:
670 return G_SPAWN_ERROR_TXTBUSY;
671 break;
672 #endif
674 #ifdef EIO
675 case EIO:
676 return G_SPAWN_ERROR_IO;
677 break;
678 #endif
680 #ifdef ENFILE
681 case ENFILE:
682 return G_SPAWN_ERROR_NFILE;
683 break;
684 #endif
686 #ifdef EMFILE
687 case EMFILE:
688 return G_SPAWN_ERROR_MFILE;
689 break;
690 #endif
692 #ifdef EINVAL
693 case EINVAL:
694 return G_SPAWN_ERROR_INVAL;
695 break;
696 #endif
698 #ifdef EISDIR
699 case EISDIR:
700 return G_SPAWN_ERROR_ISDIR;
701 break;
702 #endif
704 #ifdef ELIBBAD
705 case ELIBBAD:
706 return G_SPAWN_ERROR_LIBBAD;
707 break;
708 #endif
710 default:
711 return G_SPAWN_ERROR_FAILED;
712 break;
716 static void
717 write_err_and_exit (gint fd, gint msg)
719 gint en = errno;
721 write (fd, &msg, sizeof(msg));
722 write (fd, &en, sizeof(en));
724 _exit (1);
727 static void
728 set_cloexec (gint fd)
730 fcntl (fd, F_SETFD, FD_CLOEXEC);
733 static gint
734 sane_dup2 (gint fd1, gint fd2)
736 gint ret;
738 retry:
739 ret = dup2 (fd1, fd2);
740 if (ret < 0 && errno == EINTR)
741 goto retry;
743 return ret;
746 enum
748 CHILD_CHDIR_FAILED,
749 CHILD_EXEC_FAILED,
750 CHILD_DUP2_FAILED,
751 CHILD_FORK_FAILED
754 static void
755 do_exec (gint child_err_report_fd,
756 gint stdin_fd,
757 gint stdout_fd,
758 gint stderr_fd,
759 const gchar *working_directory,
760 gchar **argv,
761 gchar **envp,
762 gboolean close_descriptors,
763 gboolean search_path,
764 gboolean stdout_to_null,
765 gboolean stderr_to_null,
766 gboolean child_inherits_stdin,
767 GSpawnChildSetupFunc child_setup,
768 gpointer user_data)
770 if (working_directory && chdir (working_directory) < 0)
771 write_err_and_exit (child_err_report_fd,
772 CHILD_CHDIR_FAILED);
774 /* Close all file descriptors but stdin stdout and stderr as
775 * soon as we exec. Note that this includes
776 * child_err_report_fd, which keeps the parent from blocking
777 * forever on the other end of that pipe.
779 if (close_descriptors)
781 gint open_max;
782 gint i;
784 open_max = sysconf (_SC_OPEN_MAX);
785 for (i = 3; i < open_max; i++)
786 set_cloexec (i);
788 else
790 /* We need to do child_err_report_fd anyway */
791 set_cloexec (child_err_report_fd);
794 /* Redirect pipes as required */
796 if (stdin_fd >= 0)
798 /* dup2 can't actually fail here I don't think */
800 if (sane_dup2 (stdin_fd, 0) < 0)
801 write_err_and_exit (child_err_report_fd,
802 CHILD_DUP2_FAILED);
804 /* ignore this if it doesn't work */
805 close_and_invalidate (&stdin_fd);
807 else if (!child_inherits_stdin)
809 /* Keep process from blocking on a read of stdin */
810 gint read_null = open ("/dev/null", O_RDONLY);
811 sane_dup2 (read_null, 0);
812 close_and_invalidate (&read_null);
815 if (stdout_fd >= 0)
817 /* dup2 can't actually fail here I don't think */
819 if (sane_dup2 (stdout_fd, 1) < 0)
820 write_err_and_exit (child_err_report_fd,
821 CHILD_DUP2_FAILED);
823 /* ignore this if it doesn't work */
824 close_and_invalidate (&stdout_fd);
826 else if (stdout_to_null)
828 gint write_null = open ("/dev/null", O_WRONLY);
829 sane_dup2 (write_null, 1);
830 close_and_invalidate (&write_null);
833 if (stderr_fd >= 0)
835 /* dup2 can't actually fail here I don't think */
837 if (sane_dup2 (stderr_fd, 2) < 0)
838 write_err_and_exit (child_err_report_fd,
839 CHILD_DUP2_FAILED);
841 /* ignore this if it doesn't work */
842 close_and_invalidate (&stderr_fd);
844 else if (stderr_to_null)
846 gint write_null = open ("/dev/null", O_WRONLY);
847 sane_dup2 (write_null, 2);
848 close_and_invalidate (&write_null);
851 /* Call user function just before we exec */
852 if (child_setup)
854 (* child_setup) (user_data);
857 g_execute (argv[0], argv, envp, search_path);
859 /* Exec failed */
860 write_err_and_exit (child_err_report_fd,
861 CHILD_EXEC_FAILED);
864 static gboolean
865 read_ints (int fd,
866 gint* buf,
867 gint n_ints_in_buf,
868 gint *n_ints_read,
869 GError **error)
871 gint bytes = 0;
873 while (TRUE)
875 gint chunk;
877 if (bytes >= sizeof(gint)*2)
878 break; /* give up, who knows what happened, should not be
879 * possible.
882 again:
883 chunk = read (fd,
884 ((gchar*)buf) + bytes,
885 sizeof(gint)*n_ints_in_buf - bytes);
886 if (chunk < 0 && errno == EINTR)
887 goto again;
889 if (chunk < 0)
891 /* Some weird shit happened, bail out */
893 g_set_error (error,
894 G_SPAWN_ERROR,
895 G_SPAWN_ERROR_FAILED,
896 _("Failed to read from child pipe (%s)"),
897 g_strerror (errno));
899 return FALSE;
901 else if (chunk == 0)
902 break; /* EOF */
903 else
905 g_assert (chunk > 0);
907 bytes += chunk;
911 *n_ints_read = bytes/4;
913 return TRUE;
916 static gboolean
917 fork_exec_with_pipes (gboolean intermediate_child,
918 const gchar *working_directory,
919 gchar **argv,
920 gchar **envp,
921 gboolean close_descriptors,
922 gboolean search_path,
923 gboolean stdout_to_null,
924 gboolean stderr_to_null,
925 gboolean child_inherits_stdin,
926 GSpawnChildSetupFunc child_setup,
927 gpointer user_data,
928 gint *child_pid,
929 gint *standard_input,
930 gint *standard_output,
931 gint *standard_error,
932 GError **error)
934 gint pid;
935 gint stdin_pipe[2] = { -1, -1 };
936 gint stdout_pipe[2] = { -1, -1 };
937 gint stderr_pipe[2] = { -1, -1 };
938 gint child_err_report_pipe[2] = { -1, -1 };
939 gint child_pid_report_pipe[2] = { -1, -1 };
940 gint status;
942 if (!make_pipe (child_err_report_pipe, error))
943 return FALSE;
945 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
946 goto cleanup_and_fail;
948 if (standard_input && !make_pipe (stdin_pipe, error))
949 goto cleanup_and_fail;
951 if (standard_output && !make_pipe (stdout_pipe, error))
952 goto cleanup_and_fail;
954 if (standard_error && !make_pipe (stderr_pipe, error))
955 goto cleanup_and_fail;
957 pid = fork ();
959 if (pid < 0)
961 g_set_error (error,
962 G_SPAWN_ERROR,
963 G_SPAWN_ERROR_FORK,
964 _("Failed to fork (%s)"),
965 g_strerror (errno));
967 goto cleanup_and_fail;
969 else if (pid == 0)
971 /* Immediate child. This may or may not be the child that
972 * actually execs the new process.
975 /* Be sure we crash if the parent exits
976 * and we write to the err_report_pipe
978 signal (SIGPIPE, SIG_DFL);
980 /* Close the parent's end of the pipes;
981 * not needed in the close_descriptors case,
982 * though
984 close_and_invalidate (&child_err_report_pipe[0]);
985 close_and_invalidate (&child_pid_report_pipe[0]);
986 close_and_invalidate (&stdin_pipe[1]);
987 close_and_invalidate (&stdout_pipe[0]);
988 close_and_invalidate (&stderr_pipe[0]);
990 if (intermediate_child)
992 /* We need to fork an intermediate child that launches the
993 * final child. The purpose of the intermediate child
994 * is to exit, so we can waitpid() it immediately.
995 * Then the grandchild will not become a zombie.
997 gint grandchild_pid;
999 grandchild_pid = fork ();
1001 if (grandchild_pid < 0)
1003 /* report -1 as child PID */
1004 write (child_pid_report_pipe[1], &grandchild_pid,
1005 sizeof(grandchild_pid));
1007 write_err_and_exit (child_err_report_pipe[1],
1008 CHILD_FORK_FAILED);
1010 else if (grandchild_pid == 0)
1012 do_exec (child_err_report_pipe[1],
1013 stdin_pipe[0],
1014 stdout_pipe[1],
1015 stderr_pipe[1],
1016 working_directory,
1017 argv,
1018 envp,
1019 close_descriptors,
1020 search_path,
1021 stdout_to_null,
1022 stderr_to_null,
1023 child_inherits_stdin,
1024 child_setup,
1025 user_data);
1027 else
1029 write (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1030 close_and_invalidate (&child_pid_report_pipe[1]);
1032 _exit (0);
1035 else
1037 /* Just run the child.
1040 do_exec (child_err_report_pipe[1],
1041 stdin_pipe[0],
1042 stdout_pipe[1],
1043 stderr_pipe[1],
1044 working_directory,
1045 argv,
1046 envp,
1047 close_descriptors,
1048 search_path,
1049 stdout_to_null,
1050 stderr_to_null,
1051 child_inherits_stdin,
1052 child_setup,
1053 user_data);
1056 else
1058 /* Parent */
1060 gint buf[2];
1061 gint n_ints = 0;
1063 /* Close the uncared-about ends of the pipes */
1064 close_and_invalidate (&child_err_report_pipe[1]);
1065 close_and_invalidate (&child_pid_report_pipe[1]);
1066 close_and_invalidate (&stdin_pipe[0]);
1067 close_and_invalidate (&stdout_pipe[1]);
1068 close_and_invalidate (&stderr_pipe[1]);
1070 /* If we had an intermediate child, reap it */
1071 if (intermediate_child)
1073 wait_again:
1074 if (waitpid (pid, &status, 0) < 0)
1076 if (errno == EINTR)
1077 goto wait_again;
1078 else if (errno == ECHILD)
1079 ; /* do nothing, child already reaped */
1080 else
1081 g_warning ("waitpid() should not fail in "
1082 "'fork_exec_with_pipes'");
1087 if (!read_ints (child_err_report_pipe[0],
1088 buf, 2, &n_ints,
1089 error))
1090 goto cleanup_and_fail;
1092 if (n_ints >= 2)
1094 /* Error from the child. */
1096 switch (buf[0])
1098 case CHILD_CHDIR_FAILED:
1099 g_set_error (error,
1100 G_SPAWN_ERROR,
1101 G_SPAWN_ERROR_CHDIR,
1102 _("Failed to change to directory '%s' (%s)"),
1103 working_directory,
1104 g_strerror (buf[1]));
1106 break;
1108 case CHILD_EXEC_FAILED:
1109 g_set_error (error,
1110 G_SPAWN_ERROR,
1111 exec_err_to_g_error (buf[1]),
1112 _("Failed to execute child process (%s)"),
1113 g_strerror (buf[1]));
1115 break;
1117 case CHILD_DUP2_FAILED:
1118 g_set_error (error,
1119 G_SPAWN_ERROR,
1120 G_SPAWN_ERROR_FAILED,
1121 _("Failed to redirect output or input of child process (%s)"),
1122 g_strerror (buf[1]));
1124 break;
1126 case CHILD_FORK_FAILED:
1127 g_set_error (error,
1128 G_SPAWN_ERROR,
1129 G_SPAWN_ERROR_FORK,
1130 _("Failed to fork child process (%s)"),
1131 g_strerror (buf[1]));
1132 break;
1134 default:
1135 g_set_error (error,
1136 G_SPAWN_ERROR,
1137 G_SPAWN_ERROR_FAILED,
1138 _("Unknown error executing child process"));
1139 break;
1142 goto cleanup_and_fail;
1145 /* Get child pid from intermediate child pipe. */
1146 if (intermediate_child)
1148 n_ints = 0;
1150 if (!read_ints (child_pid_report_pipe[0],
1151 buf, 1, &n_ints, error))
1152 goto cleanup_and_fail;
1154 if (n_ints < 1)
1156 g_set_error (error,
1157 G_SPAWN_ERROR,
1158 G_SPAWN_ERROR_FAILED,
1159 _("Failed to read enough data from child pid pipe (%s)"),
1160 g_strerror (errno));
1161 goto cleanup_and_fail;
1163 else
1165 /* we have the child pid */
1166 pid = buf[0];
1170 /* Success against all odds! return the information */
1172 if (child_pid)
1173 *child_pid = pid;
1175 if (standard_input)
1176 *standard_input = stdin_pipe[1];
1177 if (standard_output)
1178 *standard_output = stdout_pipe[0];
1179 if (standard_error)
1180 *standard_error = stderr_pipe[0];
1182 return TRUE;
1185 cleanup_and_fail:
1186 close_and_invalidate (&child_err_report_pipe[0]);
1187 close_and_invalidate (&child_err_report_pipe[1]);
1188 close_and_invalidate (&child_pid_report_pipe[0]);
1189 close_and_invalidate (&child_pid_report_pipe[1]);
1190 close_and_invalidate (&stdin_pipe[0]);
1191 close_and_invalidate (&stdin_pipe[1]);
1192 close_and_invalidate (&stdout_pipe[0]);
1193 close_and_invalidate (&stdout_pipe[1]);
1194 close_and_invalidate (&stderr_pipe[0]);
1195 close_and_invalidate (&stderr_pipe[1]);
1197 return FALSE;
1200 static gboolean
1201 make_pipe (gint p[2],
1202 GError **error)
1204 if (pipe (p) < 0)
1206 g_set_error (error,
1207 G_SPAWN_ERROR,
1208 G_SPAWN_ERROR_FAILED,
1209 _("Failed to create pipe for communicating with child process (%s)"),
1210 g_strerror (errno));
1211 return FALSE;
1213 else
1214 return TRUE;
1217 /* Based on execvp from GNU C Library */
1219 static void
1220 script_execute (const gchar *file,
1221 gchar **argv,
1222 gchar **envp,
1223 gboolean search_path)
1225 /* Count the arguments. */
1226 int argc = 0;
1227 while (argv[argc])
1228 ++argc;
1230 /* Construct an argument list for the shell. */
1232 gchar **new_argv;
1234 new_argv = g_new0 (gchar*, argc + 1);
1236 new_argv[0] = (char *) "/bin/sh";
1237 new_argv[1] = (char *) file;
1238 while (argc > 1)
1240 new_argv[argc] = argv[argc - 1];
1241 --argc;
1244 /* Execute the shell. */
1245 if (envp)
1246 execve (new_argv[0], new_argv, envp);
1247 else
1248 execv (new_argv[0], new_argv);
1250 g_free (new_argv);
1254 static gchar*
1255 my_strchrnul (const gchar *str, gchar c)
1257 gchar *p = (gchar*) str;
1258 while (*p && (*p != c))
1259 ++p;
1261 return p;
1264 static gint
1265 g_execute (const gchar *file,
1266 gchar **argv,
1267 gchar **envp,
1268 gboolean search_path)
1270 if (*file == '\0')
1272 /* We check the simple case first. */
1273 errno = ENOENT;
1274 return -1;
1277 if (!search_path || strchr (file, '/') != NULL)
1279 /* Don't search when it contains a slash. */
1280 if (envp)
1281 execve (file, argv, envp);
1282 else
1283 execv (file, argv);
1285 if (errno == ENOEXEC)
1286 script_execute (file, argv, envp, FALSE);
1288 else
1290 gboolean got_eacces = 0;
1291 const gchar *path, *p;
1292 gchar *name, *freeme;
1293 size_t len;
1294 size_t pathlen;
1296 path = g_getenv ("PATH");
1297 if (path == NULL)
1299 /* There is no `PATH' in the environment. The default
1300 * search path in libc is the current directory followed by
1301 * the path `confstr' returns for `_CS_PATH'.
1304 /* In GLib we put . last, for security, and don't use the
1305 * unportable confstr(); UNIX98 does not actually specify
1306 * what to search if PATH is unset. POSIX may, dunno.
1309 path = "/bin:/usr/bin:.";
1312 len = strlen (file) + 1;
1313 pathlen = strlen (path);
1314 freeme = name = g_malloc (pathlen + len + 1);
1316 /* Copy the file name at the top, including '\0' */
1317 memcpy (name + pathlen + 1, file, len);
1318 name = name + pathlen;
1319 /* And add the slash before the filename */
1320 *name = '/';
1322 p = path;
1325 char *startp;
1327 path = p;
1328 p = my_strchrnul (path, ':');
1330 if (p == path)
1331 /* Two adjacent colons, or a colon at the beginning or the end
1332 * of `PATH' means to search the current directory.
1334 startp = name + 1;
1335 else
1336 startp = memcpy (name - (p - path), path, p - path);
1338 /* Try to execute this name. If it works, execv will not return. */
1339 if (envp)
1340 execve (startp, argv, envp);
1341 else
1342 execv (startp, argv);
1344 if (errno == ENOEXEC)
1345 script_execute (startp, argv, envp, search_path);
1347 switch (errno)
1349 case EACCES:
1350 /* Record the we got a `Permission denied' error. If we end
1351 * up finding no executable we can use, we want to diagnose
1352 * that we did find one but were denied access.
1354 got_eacces = TRUE;
1356 /* FALL THRU */
1358 case ENOENT:
1359 #ifdef ESTALE
1360 case ESTALE:
1361 #endif
1362 #ifdef ENOTDIR
1363 case ENOTDIR:
1364 #endif
1365 /* Those errors indicate the file is missing or not executable
1366 * by us, in which case we want to just try the next path
1367 * directory.
1369 break;
1371 default:
1372 /* Some other error means we found an executable file, but
1373 * something went wrong executing it; return the error to our
1374 * caller.
1376 g_free (freeme);
1377 return -1;
1380 while (*p++ != '\0');
1382 /* We tried every element and none of them worked. */
1383 if (got_eacces)
1384 /* At least one failure was due to permissions, so report that
1385 * error.
1387 errno = EACCES;
1389 g_free (freeme);
1392 /* Return the error from the last attempt (probably ENOENT). */
1393 return -1;