Add test for g_path_skip_root().
[glib.git] / gspawn.c
blobb1342ccaa43b7e7ac305ec73e884985ea416a8d9
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 #ifdef _
38 #warning "FIXME remove gettext hack"
39 #endif
41 #define _(x) x
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 GSpawnChildSetupFunc child_setup,
60 gpointer user_data,
61 gint *child_pid,
62 gint *standard_input,
63 gint *standard_output,
64 gint *standard_error,
65 GError **error);
67 GQuark
68 g_spawn_error_quark (void)
70 static GQuark quark = 0;
71 if (quark == 0)
72 quark = g_quark_from_static_string ("g-exec-error-quark");
73 return quark;
76 /**
77 * g_spawn_async:
78 * @working_directory: child's current working directory, or NULL to inherit parent's
79 * @argv: child's argument vector
80 * @envp: child's environment, or NULL to inherit parent's
81 * @flags: flags from #GSpawnFlags
82 * @child_setup: function to run in the child just before exec()
83 * @user_data: user data for @child_setup
84 * @child_pid: return location for child process ID, or NULL
85 * @error: return location for error
87 * See g_spawn_async_with_pipes() for a full description; this function
88 * simply calls the g_spawn_async_with_pipes() without any pipes.
90 * Return value: TRUE on success, FALSE if error is set
91 **/
92 gboolean
93 g_spawn_async (const gchar *working_directory,
94 gchar **argv,
95 gchar **envp,
96 GSpawnFlags flags,
97 GSpawnChildSetupFunc child_setup,
98 gpointer user_data,
99 gint *child_pid,
100 GError **error)
102 g_return_val_if_fail (argv != NULL, FALSE);
104 return g_spawn_async_with_pipes (working_directory,
105 argv, envp,
106 flags,
107 child_setup,
108 user_data,
109 child_pid,
110 NULL, NULL, NULL,
111 error);
114 /* Avoids a danger in threaded situations (calling close()
115 * on a file descriptor twice, and another thread has
116 * re-opened it since the first close)
118 static gint
119 close_and_invalidate (gint *fd)
121 gint ret;
123 ret = close (*fd);
124 *fd = -1;
126 return ret;
129 typedef enum
131 READ_FAILED = 0, /* FALSE */
132 READ_OK,
133 READ_EOF
134 } ReadResult;
136 static ReadResult
137 read_data (GString *str,
138 gint fd,
139 GError **error)
141 gint bytes;
142 gchar buf[4096];
144 again:
146 bytes = read (fd, &buf, 4096);
148 if (bytes == 0)
149 return READ_EOF;
150 else if (bytes > 0)
152 g_string_append_len (str, buf, bytes);
153 return READ_OK;
155 else if (bytes < 0 && errno == EINTR)
156 goto again;
157 else if (bytes < 0)
159 g_set_error (error,
160 G_SPAWN_ERROR,
161 G_SPAWN_ERROR_READ,
162 _("Failed to read data from child process (%s)"),
163 g_strerror (errno));
165 return READ_FAILED;
167 else
168 return READ_OK;
172 * g_spawn_sync:
173 * @working_directory: child's current working directory, or NULL to inherit parent's
174 * @argv: child's argument vector
175 * @envp: child's environment, or NULL to inherit parent's
176 * @flags: flags from #GSpawnFlags
177 * @child_setup: function to run in the child just before exec()
178 * @user_data: user data for @child_setup
179 * @standard_output: return location for child output
180 * @standard_error: return location for child error messages
181 * @exit_status: child exit status, as returned by waitpid()
182 * @error: return location for error
184 * Executes a child synchronously (waits for the child to exit before returning).
185 * All output from the child is stored in @standard_output and @standard_error,
186 * if those parameters are non-NULL. If @exit_status is non-NULL, the exit status
187 * of the child is stored there as it would be by waitpid(); standard UNIX
188 * macros such as WIFEXITED() and WEXITSTATUS() must be used to evaluate the
189 * exit status. If an error occurs, no data is returned in @standard_output,
190 * @standard_error, or @exit_status.
192 * This function calls g_spawn_async_with_pipes() internally; see that function
193 * for full details on the other parameters.
195 * Return value: TRUE on success, FALSE if an error was set.
197 gboolean
198 g_spawn_sync (const gchar *working_directory,
199 gchar **argv,
200 gchar **envp,
201 GSpawnFlags flags,
202 GSpawnChildSetupFunc child_setup,
203 gpointer user_data,
204 gchar **standard_output,
205 gchar **standard_error,
206 gint *exit_status,
207 GError **error)
209 gint outpipe = -1;
210 gint errpipe = -1;
211 gint pid;
212 fd_set fds;
213 gint ret;
214 GString *outstr = NULL;
215 GString *errstr = NULL;
216 gboolean failed;
217 gint status;
219 g_return_val_if_fail (argv != NULL, FALSE);
220 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
221 g_return_val_if_fail (standard_output == NULL ||
222 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
223 g_return_val_if_fail (standard_error == NULL ||
224 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
226 /* Just to ensure segfaults if callers try to use
227 * these when an error is reported.
229 if (standard_output)
230 *standard_output = NULL;
232 if (standard_error)
233 *standard_error = NULL;
235 if (!fork_exec_with_pipes (FALSE,
236 working_directory,
237 argv,
238 envp,
239 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
240 (flags & G_SPAWN_SEARCH_PATH) != 0,
241 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
242 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
243 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
244 child_setup,
245 user_data,
246 &pid,
247 NULL,
248 standard_output ? &outpipe : NULL,
249 standard_error ? &errpipe : NULL,
250 error))
251 return FALSE;
253 /* Read data from child. */
255 failed = FALSE;
257 if (outpipe >= 0)
259 outstr = g_string_new ("");
262 if (errpipe >= 0)
264 errstr = g_string_new ("");
267 /* Read data until we get EOF on both pipes. */
268 while (!failed &&
269 (outpipe >= 0 ||
270 errpipe >= 0))
272 ret = 0;
274 FD_ZERO (&fds);
275 if (outpipe >= 0)
276 FD_SET (outpipe, &fds);
277 if (errpipe >= 0)
278 FD_SET (errpipe, &fds);
280 ret = select (MAX (outpipe, errpipe) + 1,
281 &fds,
282 NULL, NULL,
283 NULL /* no timeout */);
285 if (ret < 0 && errno != EINTR)
287 failed = TRUE;
289 g_set_error (error,
290 G_SPAWN_ERROR,
291 G_SPAWN_ERROR_READ,
292 _("Unexpected error in select() reading data from a child process (%s)"),
293 g_strerror (errno));
295 break;
298 if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
300 switch (read_data (outstr, outpipe, error))
302 case READ_FAILED:
303 failed = TRUE;
304 break;
305 case READ_EOF:
306 close_and_invalidate (&outpipe);
307 outpipe = -1;
308 break;
309 default:
310 break;
313 if (failed)
314 break;
317 if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
319 switch (read_data (errstr, errpipe, error))
321 case READ_FAILED:
322 failed = TRUE;
323 break;
324 case READ_EOF:
325 close_and_invalidate (&errpipe);
326 errpipe = -1;
327 break;
328 default:
329 break;
332 if (failed)
333 break;
337 /* These should only be open still if we had an error. */
339 if (outpipe >= 0)
340 close_and_invalidate (&outpipe);
341 if (errpipe >= 0)
342 close_and_invalidate (&errpipe);
344 /* Wait for child to exit, even if we have
345 * an error pending.
347 again:
349 ret = waitpid (pid, &status, 0);
351 if (ret < 0)
353 if (errno == EINTR)
354 goto again;
355 else if (errno == ECHILD)
357 if (exit_status)
359 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.");
361 else
363 /* We don't need the exit status. */
366 else
368 if (!failed) /* avoid error pileups */
370 failed = TRUE;
372 g_set_error (error,
373 G_SPAWN_ERROR,
374 G_SPAWN_ERROR_READ,
375 _("Unexpected error in waitpid() (%s)"),
376 g_strerror (errno));
381 if (failed)
383 if (outstr)
384 g_string_free (outstr, TRUE);
385 if (errstr)
386 g_string_free (errstr, TRUE);
388 return FALSE;
390 else
392 if (exit_status)
393 *exit_status = status;
395 if (standard_output)
396 *standard_output = g_string_free (outstr, FALSE);
398 if (standard_error)
399 *standard_error = g_string_free (errstr, FALSE);
401 return TRUE;
406 * g_spawn_async_with_pipes:
407 * @working_directory: child's current working directory, or NULL to inherit parent's
408 * @argv: child's argument vector
409 * @envp: child's environment, or NULL to inherit parent's
410 * @flags: flags from #GSpawnFlags
411 * @child_setup: function to run in the child just before exec()
412 * @user_data: user data for @child_setup
413 * @child_pid: return location for child process ID, or NULL
414 * @standard_input: return location for file descriptor to write to child's stdin, or NULL
415 * @standard_output: return location for file descriptor to read child's stdout, or NULL
416 * @standard_error: return location for file descriptor to read child's stderr, or NULL
417 * @error: return location for error
419 * Executes a child program asynchronously (your program will not
420 * block waiting for the child to exit). The child program is
421 * specified by the only argument that must be provided, @argv. @argv
422 * should be a NULL-terminated array of strings, to be passed as the
423 * argument vector for the child. The first string in @argv is of
424 * course the name of the program to execute. By default, the name of
425 * the program must be a full path; the PATH shell variable will only
426 * be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
428 * @envp is a NULL-terminated array of strings, where each string
429 * has the form <literal>KEY=VALUE</literal>. This will become
430 * the child's environment. If @envp is NULL, the child inherits its
431 * parent's environment.
433 * @flags should be the bitwise OR of any flags you want to affect the
434 * function's behavior. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
435 * child will not be automatically reaped; you must call waitpid() or
436 * handle SIGCHLD yourself, or the child will become a zombie.
437 * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
438 * descriptors will be inherited by the child; otherwise all
439 * descriptors except stdin/stdout/stderr will be closed before
440 * calling exec() in the child. %G_SPAWN_SEARCH_PATH means that
441 * <literal>argv[0]</literal> need not be an absolute path, it
442 * will be looked for in the user's PATH. %G_SPAWN_STDOUT_TO_DEV_NULL
443 * means that the child's standad output will be discarded, instead
444 * of going to the same location as the parent's standard output.
445 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
446 * will be discarded. %G_SPAWN_CHILD_INHERITS_STDIN means that
447 * the child will inherit the parent's standard input (by default,
448 * the child's standard input is attached to /dev/null).
450 * @child_setup and @user_data are a function and user data to be
451 * called in the child after GLib has performed all the setup it plans
452 * to perform (including creating pipes, closing file descriptors,
453 * etc.) but before calling exec(). That is, @child_setup is called
454 * just before calling exec() in the child. Obviously actions taken in
455 * this function will only affect the child, not the parent.
457 * If non-NULL, @child_pid will be filled with the child's process
458 * ID. You can use the process ID to send signals to the child, or
459 * to waitpid() if you specified the %G_SPAWN_DO_NOT_REAP_CHILD flag.
461 * If non-NULL, the @standard_input, @standard_output, @standard_error
462 * locations will be filled with file descriptors for writing to the child's
463 * standard input or reading from its standard output or standard error.
464 * The caller of g_spawn_async_with_pipes() must close these file descriptors
465 * when they are no longer in use. If these parameters are NULL, the
466 * corresponding pipe won't be created.
468 * @error can be NULL to ignore errors, or non-NULL to report errors.
469 * If an error is set, the function returns FALSE. Errors
470 * are reported even if they occur in the child (for example if the
471 * executable in <literal>argv[0]</literal> is not found). Typically
472 * the <literal>message</literal> field of returned errors should be displayed
473 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
475 * If an error occurs, @child_pid, @standard_input, @standard_output,
476 * and @standard_error will not be filled with valid values.
478 * Return value: TRUE on success, FALSE if an error was set
480 gboolean
481 g_spawn_async_with_pipes (const gchar *working_directory,
482 gchar **argv,
483 gchar **envp,
484 GSpawnFlags flags,
485 GSpawnChildSetupFunc child_setup,
486 gpointer user_data,
487 gint *child_pid,
488 gint *standard_input,
489 gint *standard_output,
490 gint *standard_error,
491 GError **error)
493 g_return_val_if_fail (argv != NULL, FALSE);
494 g_return_val_if_fail (standard_output == NULL ||
495 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
496 g_return_val_if_fail (standard_error == NULL ||
497 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
498 /* can't inherit stdin if we have an input pipe. */
499 g_return_val_if_fail (standard_input == NULL ||
500 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
502 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
503 working_directory,
504 argv,
505 envp,
506 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
507 (flags & G_SPAWN_SEARCH_PATH) != 0,
508 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
509 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
510 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
511 child_setup,
512 user_data,
513 child_pid,
514 standard_input,
515 standard_output,
516 standard_error,
517 error);
521 * g_spawn_command_line_sync:
522 * @command_line: a command line
523 * @standard_output: return location for child output
524 * @standard_error: return location for child errors
525 * @exit_status: return location for child exit status
526 * @error: return location for errors
528 * A simple version of g_spawn_sync() with little-used parameters
529 * removed, taking a command line instead of an argument vector. See
530 * g_spawn_sync() for full details. @command_line will be parsed by
531 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
532 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
533 * implications, so consider using g_spawn_sync() directly if
534 * appropriate. Possible errors are those from g_spawn_sync() and those
535 * from g_shell_parse_argv().
537 * Return value: TRUE on success, FALSE if an error was set
539 gboolean
540 g_spawn_command_line_sync (const gchar *command_line,
541 gchar **standard_output,
542 gchar **standard_error,
543 gint *exit_status,
544 GError **error)
546 gboolean retval;
547 gchar **argv = 0;
549 g_return_val_if_fail (command_line != NULL, FALSE);
551 if (!g_shell_parse_argv (command_line,
552 NULL, &argv,
553 error))
554 return FALSE;
556 retval = g_spawn_sync (NULL,
557 argv,
558 NULL,
559 G_SPAWN_SEARCH_PATH,
560 NULL,
561 NULL,
562 standard_output,
563 standard_error,
564 exit_status,
565 error);
566 g_strfreev (argv);
568 return retval;
572 * g_spawn_command_line_async:
573 * @command_line: a command line
574 * @error: return location for errors
576 * A simple version of g_spawn_async() that parses a command line with
577 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
578 * command line in the background. Unlike g_spawn_async(), the
579 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
580 * that %G_SPAWN_SEARCH_PATH can have security implications, so
581 * consider using g_spawn_async() directly if appropriate. Possible
582 * errors are those from g_shell_parse_argv() and g_spawn_async().
584 * Return value: TRUE on success, FALSE if error is set.
586 gboolean
587 g_spawn_command_line_async (const gchar *command_line,
588 GError **error)
590 gboolean retval;
591 gchar **argv = 0;
593 g_return_val_if_fail (command_line != NULL, FALSE);
595 if (!g_shell_parse_argv (command_line,
596 NULL, &argv,
597 error))
598 return FALSE;
600 retval = g_spawn_async (NULL,
601 argv,
602 NULL,
603 G_SPAWN_SEARCH_PATH,
604 NULL,
605 NULL,
606 NULL,
607 error);
608 g_strfreev (argv);
610 return retval;
613 static gint
614 exec_err_to_g_error (gint en)
616 switch (en)
618 #ifdef EACCES
619 case EACCES:
620 return G_SPAWN_ERROR_ACCES;
621 break;
622 #endif
624 #ifdef EPERM
625 case EPERM:
626 return G_SPAWN_ERROR_PERM;
627 break;
628 #endif
630 #ifdef E2BIG
631 case E2BIG:
632 return G_SPAWN_ERROR_2BIG;
633 break;
634 #endif
636 #ifdef ENOEXEC
637 case ENOEXEC:
638 return G_SPAWN_ERROR_NOEXEC;
639 break;
640 #endif
642 #ifdef ENAMETOOLONG
643 case ENAMETOOLONG:
644 return G_SPAWN_ERROR_NAMETOOLONG;
645 break;
646 #endif
648 #ifdef ENOENT
649 case ENOENT:
650 return G_SPAWN_ERROR_NOENT;
651 break;
652 #endif
654 #ifdef ENOMEM
655 case ENOMEM:
656 return G_SPAWN_ERROR_NOMEM;
657 break;
658 #endif
660 #ifdef ENOTDIR
661 case ENOTDIR:
662 return G_SPAWN_ERROR_NOTDIR;
663 break;
664 #endif
666 #ifdef ELOOP
667 case ELOOP:
668 return G_SPAWN_ERROR_LOOP;
669 break;
670 #endif
672 #ifdef ETXTBUSY
673 case ETXTBUSY:
674 return G_SPAWN_ERROR_TXTBUSY;
675 break;
676 #endif
678 #ifdef EIO
679 case EIO:
680 return G_SPAWN_ERROR_IO;
681 break;
682 #endif
684 #ifdef ENFILE
685 case ENFILE:
686 return G_SPAWN_ERROR_NFILE;
687 break;
688 #endif
690 #ifdef EMFILE
691 case EMFILE:
692 return G_SPAWN_ERROR_MFILE;
693 break;
694 #endif
696 #ifdef EINVAL
697 case EINVAL:
698 return G_SPAWN_ERROR_INVAL;
699 break;
700 #endif
702 #ifdef EISDIR
703 case EISDIR:
704 return G_SPAWN_ERROR_ISDIR;
705 break;
706 #endif
708 #ifdef ELIBBAD
709 case ELIBBAD:
710 return G_SPAWN_ERROR_LIBBAD;
711 break;
712 #endif
714 default:
715 return G_SPAWN_ERROR_FAILED;
716 break;
720 static void
721 write_err_and_exit (gint fd, gint msg)
723 gint en = errno;
725 write (fd, &msg, sizeof(msg));
726 write (fd, &en, sizeof(en));
728 _exit (1);
731 static void
732 set_cloexec (gint fd)
734 fcntl (fd, F_SETFD, FD_CLOEXEC);
737 static gint
738 sane_dup2 (gint fd1, gint fd2)
740 gint ret;
742 retry:
743 ret = dup2 (fd1, fd2);
744 if (ret < 0 && errno == EINTR)
745 goto retry;
747 return ret;
750 enum
752 CHILD_CHDIR_FAILED,
753 CHILD_EXEC_FAILED,
754 CHILD_DUP2_FAILED,
755 CHILD_FORK_FAILED
758 static void
759 do_exec (gint child_err_report_fd,
760 gint stdin_fd,
761 gint stdout_fd,
762 gint stderr_fd,
763 const gchar *working_directory,
764 gchar **argv,
765 gchar **envp,
766 gboolean close_descriptors,
767 gboolean search_path,
768 gboolean stdout_to_null,
769 gboolean stderr_to_null,
770 gboolean child_inherits_stdin,
771 GSpawnChildSetupFunc child_setup,
772 gpointer user_data)
774 if (working_directory && chdir (working_directory) < 0)
775 write_err_and_exit (child_err_report_fd,
776 CHILD_CHDIR_FAILED);
778 /* Close all file descriptors but stdin stdout and stderr as
779 * soon as we exec. Note that this includes
780 * child_err_report_fd, which keeps the parent from blocking
781 * forever on the other end of that pipe.
783 if (close_descriptors)
785 gint open_max;
786 gint i;
788 open_max = sysconf (_SC_OPEN_MAX);
789 for (i = 3; i < open_max; i++)
790 set_cloexec (i);
792 else
794 /* We need to do child_err_report_fd anyway */
795 set_cloexec (child_err_report_fd);
798 /* Redirect pipes as required */
800 if (stdin_fd >= 0)
802 /* dup2 can't actually fail here I don't think */
804 if (sane_dup2 (stdin_fd, 0) < 0)
805 write_err_and_exit (child_err_report_fd,
806 CHILD_DUP2_FAILED);
808 /* ignore this if it doesn't work */
809 close_and_invalidate (&stdin_fd);
811 else if (!child_inherits_stdin)
813 /* Keep process from blocking on a read of stdin */
814 gint read_null = open ("/dev/null", O_RDONLY);
815 sane_dup2 (read_null, 0);
816 close_and_invalidate (&read_null);
819 if (stdout_fd >= 0)
821 /* dup2 can't actually fail here I don't think */
823 if (sane_dup2 (stdout_fd, 1) < 0)
824 write_err_and_exit (child_err_report_fd,
825 CHILD_DUP2_FAILED);
827 /* ignore this if it doesn't work */
828 close_and_invalidate (&stdout_fd);
830 else if (stdout_to_null)
832 gint write_null = open ("/dev/null", O_WRONLY);
833 sane_dup2 (write_null, 1);
834 close_and_invalidate (&write_null);
837 if (stderr_fd >= 0)
839 /* dup2 can't actually fail here I don't think */
841 if (sane_dup2 (stderr_fd, 2) < 0)
842 write_err_and_exit (child_err_report_fd,
843 CHILD_DUP2_FAILED);
845 /* ignore this if it doesn't work */
846 close_and_invalidate (&stderr_fd);
848 else if (stderr_to_null)
850 gint write_null = open ("/dev/null", O_WRONLY);
851 sane_dup2 (write_null, 2);
852 close_and_invalidate (&write_null);
855 /* Call user function just before we exec */
856 if (child_setup)
858 (* child_setup) (user_data);
861 g_execute (argv[0], argv, envp, search_path);
863 /* Exec failed */
864 write_err_and_exit (child_err_report_fd,
865 CHILD_EXEC_FAILED);
868 static gboolean
869 read_ints (int fd,
870 gint* buf,
871 gint n_ints_in_buf,
872 gint *n_ints_read,
873 GError **error)
875 gint bytes = 0;
877 while (TRUE)
879 gint chunk;
881 if (bytes >= sizeof(gint)*2)
882 break; /* give up, who knows what happened, should not be
883 * possible.
886 again:
887 chunk = read (fd,
888 ((gchar*)buf) + bytes,
889 sizeof(gint)*n_ints_in_buf - bytes);
890 if (chunk < 0 && errno == EINTR)
891 goto again;
893 if (chunk < 0)
895 /* Some weird shit happened, bail out */
897 g_set_error (error,
898 G_SPAWN_ERROR,
899 G_SPAWN_ERROR_FAILED,
900 _("Failed to read from child pipe (%s)"),
901 g_strerror (errno));
903 return FALSE;
905 else if (chunk == 0)
906 break; /* EOF */
907 else
909 g_assert (chunk > 0);
911 bytes += chunk;
915 *n_ints_read = bytes/4;
917 return TRUE;
920 static gboolean
921 fork_exec_with_pipes (gboolean intermediate_child,
922 const gchar *working_directory,
923 gchar **argv,
924 gchar **envp,
925 gboolean close_descriptors,
926 gboolean search_path,
927 gboolean stdout_to_null,
928 gboolean stderr_to_null,
929 gboolean child_inherits_stdin,
930 GSpawnChildSetupFunc child_setup,
931 gpointer user_data,
932 gint *child_pid,
933 gint *standard_input,
934 gint *standard_output,
935 gint *standard_error,
936 GError **error)
938 gint pid;
939 gint stdin_pipe[2] = { -1, -1 };
940 gint stdout_pipe[2] = { -1, -1 };
941 gint stderr_pipe[2] = { -1, -1 };
942 gint child_err_report_pipe[2] = { -1, -1 };
943 gint child_pid_report_pipe[2] = { -1, -1 };
944 gint status;
946 if (!make_pipe (child_err_report_pipe, error))
947 return FALSE;
949 if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
950 goto cleanup_and_fail;
952 if (standard_input && !make_pipe (stdin_pipe, error))
953 goto cleanup_and_fail;
955 if (standard_output && !make_pipe (stdout_pipe, error))
956 goto cleanup_and_fail;
958 if (standard_error && !make_pipe (stderr_pipe, error))
959 goto cleanup_and_fail;
961 pid = fork ();
963 if (pid < 0)
965 g_set_error (error,
966 G_SPAWN_ERROR,
967 G_SPAWN_ERROR_FORK,
968 _("Failed to fork (%s)"),
969 g_strerror (errno));
971 goto cleanup_and_fail;
973 else if (pid == 0)
975 /* Immediate child. This may or may not be the child that
976 * actually execs the new process.
979 /* Be sure we crash if the parent exits
980 * and we write to the err_report_pipe
982 signal (SIGPIPE, SIG_DFL);
984 /* Close the parent's end of the pipes;
985 * not needed in the close_descriptors case,
986 * though
988 close_and_invalidate (&child_err_report_pipe[0]);
989 close_and_invalidate (&child_pid_report_pipe[0]);
990 close_and_invalidate (&stdin_pipe[1]);
991 close_and_invalidate (&stdout_pipe[0]);
992 close_and_invalidate (&stderr_pipe[0]);
994 if (intermediate_child)
996 /* We need to fork an intermediate child that launches the
997 * final child. The purpose of the intermediate child
998 * is to exit, so we can waitpid() it immediately.
999 * Then the grandchild will not become a zombie.
1001 gint grandchild_pid;
1003 grandchild_pid = fork ();
1005 if (grandchild_pid < 0)
1007 /* report -1 as child PID */
1008 write (child_pid_report_pipe[1], &grandchild_pid,
1009 sizeof(grandchild_pid));
1011 write_err_and_exit (child_err_report_pipe[1],
1012 CHILD_FORK_FAILED);
1014 else if (grandchild_pid == 0)
1016 do_exec (child_err_report_pipe[1],
1017 stdin_pipe[0],
1018 stdout_pipe[1],
1019 stderr_pipe[1],
1020 working_directory,
1021 argv,
1022 envp,
1023 close_descriptors,
1024 search_path,
1025 stdout_to_null,
1026 stderr_to_null,
1027 child_inherits_stdin,
1028 child_setup,
1029 user_data);
1031 else
1033 write (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1034 close_and_invalidate (&child_pid_report_pipe[1]);
1036 _exit (0);
1039 else
1041 /* Just run the child.
1044 do_exec (child_err_report_pipe[1],
1045 stdin_pipe[0],
1046 stdout_pipe[1],
1047 stderr_pipe[1],
1048 working_directory,
1049 argv,
1050 envp,
1051 close_descriptors,
1052 search_path,
1053 stdout_to_null,
1054 stderr_to_null,
1055 child_inherits_stdin,
1056 child_setup,
1057 user_data);
1060 else
1062 /* Parent */
1064 gint buf[2];
1065 gint n_ints = 0;
1067 /* Close the uncared-about ends of the pipes */
1068 close_and_invalidate (&child_err_report_pipe[1]);
1069 close_and_invalidate (&child_pid_report_pipe[1]);
1070 close_and_invalidate (&stdin_pipe[0]);
1071 close_and_invalidate (&stdout_pipe[1]);
1072 close_and_invalidate (&stderr_pipe[1]);
1074 /* If we had an intermediate child, reap it */
1075 if (intermediate_child)
1077 wait_again:
1078 if (waitpid (pid, &status, 0) < 0)
1080 if (errno == EINTR)
1081 goto wait_again;
1082 else if (errno == ECHILD)
1083 ; /* do nothing, child already reaped */
1084 else
1085 g_warning ("waitpid() should not fail in "
1086 "'fork_exec_with_pipes'");
1091 if (!read_ints (child_err_report_pipe[0],
1092 buf, 2, &n_ints,
1093 error))
1094 goto cleanup_and_fail;
1096 if (n_ints >= 2)
1098 /* Error from the child. */
1100 switch (buf[0])
1102 case CHILD_CHDIR_FAILED:
1103 g_set_error (error,
1104 G_SPAWN_ERROR,
1105 G_SPAWN_ERROR_CHDIR,
1106 _("Failed to change to directory '%s' (%s)"),
1107 working_directory,
1108 g_strerror (buf[1]));
1110 break;
1112 case CHILD_EXEC_FAILED:
1113 g_set_error (error,
1114 G_SPAWN_ERROR,
1115 exec_err_to_g_error (buf[1]),
1116 _("Failed to execute child process (%s)"),
1117 g_strerror (buf[1]));
1119 break;
1121 case CHILD_DUP2_FAILED:
1122 g_set_error (error,
1123 G_SPAWN_ERROR,
1124 G_SPAWN_ERROR_FAILED,
1125 _("Failed to redirect output or input of child process (%s)"),
1126 g_strerror (buf[1]));
1128 break;
1130 case CHILD_FORK_FAILED:
1131 g_set_error (error,
1132 G_SPAWN_ERROR,
1133 G_SPAWN_ERROR_FORK,
1134 _("Failed to fork child process (%s)"),
1135 g_strerror (buf[1]));
1136 break;
1138 default:
1139 g_set_error (error,
1140 G_SPAWN_ERROR,
1141 G_SPAWN_ERROR_FAILED,
1142 _("Unknown error executing child process"));
1143 break;
1146 goto cleanup_and_fail;
1149 /* Get child pid from intermediate child pipe. */
1150 if (intermediate_child)
1152 n_ints = 0;
1154 if (!read_ints (child_pid_report_pipe[0],
1155 buf, 1, &n_ints, error))
1156 goto cleanup_and_fail;
1158 if (n_ints < 1)
1160 g_set_error (error,
1161 G_SPAWN_ERROR,
1162 G_SPAWN_ERROR_FAILED,
1163 _("Failed to read enough data from child pid pipe (%s)"),
1164 g_strerror (errno));
1165 goto cleanup_and_fail;
1167 else
1169 /* we have the child pid */
1170 pid = buf[0];
1174 /* Success against all odds! return the information */
1176 if (child_pid)
1177 *child_pid = pid;
1179 if (standard_input)
1180 *standard_input = stdin_pipe[1];
1181 if (standard_output)
1182 *standard_output = stdout_pipe[0];
1183 if (standard_error)
1184 *standard_error = stderr_pipe[0];
1186 return TRUE;
1189 cleanup_and_fail:
1190 close_and_invalidate (&child_err_report_pipe[0]);
1191 close_and_invalidate (&child_err_report_pipe[1]);
1192 close_and_invalidate (&child_pid_report_pipe[0]);
1193 close_and_invalidate (&child_pid_report_pipe[1]);
1194 close_and_invalidate (&stdin_pipe[0]);
1195 close_and_invalidate (&stdin_pipe[1]);
1196 close_and_invalidate (&stdout_pipe[0]);
1197 close_and_invalidate (&stdout_pipe[1]);
1198 close_and_invalidate (&stderr_pipe[0]);
1199 close_and_invalidate (&stderr_pipe[1]);
1201 return FALSE;
1204 static gboolean
1205 make_pipe (gint p[2],
1206 GError **error)
1208 if (pipe (p) < 0)
1210 g_set_error (error,
1211 G_SPAWN_ERROR,
1212 G_SPAWN_ERROR_FAILED,
1213 _("Failed to create pipe for communicating with child process (%s)"),
1214 g_strerror (errno));
1215 return FALSE;
1217 else
1218 return TRUE;
1221 /* Based on execvp from GNU C Library */
1223 static void
1224 script_execute (const gchar *file,
1225 gchar **argv,
1226 gchar **envp,
1227 gboolean search_path)
1229 /* Count the arguments. */
1230 int argc = 0;
1231 while (argv[argc])
1232 ++argc;
1234 /* Construct an argument list for the shell. */
1236 gchar **new_argv;
1238 new_argv = g_new0 (gchar*, argc + 1);
1240 new_argv[0] = (char *) "/bin/sh";
1241 new_argv[1] = (char *) file;
1242 while (argc > 1)
1244 new_argv[argc] = argv[argc - 1];
1245 --argc;
1248 /* Execute the shell. */
1249 if (envp)
1250 execve (new_argv[0], new_argv, envp);
1251 else
1252 execv (new_argv[0], new_argv);
1254 g_free (new_argv);
1258 static gchar*
1259 my_strchrnul (const gchar *str, gchar c)
1261 gchar *p = (gchar*) str;
1262 while (*p && (*p != c))
1263 ++p;
1265 return p;
1268 static gint
1269 g_execute (const gchar *file,
1270 gchar **argv,
1271 gchar **envp,
1272 gboolean search_path)
1274 if (*file == '\0')
1276 /* We check the simple case first. */
1277 errno = ENOENT;
1278 return -1;
1281 if (!search_path || strchr (file, '/') != NULL)
1283 /* Don't search when it contains a slash. */
1284 if (envp)
1285 execve (file, argv, envp);
1286 else
1287 execv (file, argv);
1289 if (errno == ENOEXEC)
1290 script_execute (file, argv, envp, FALSE);
1292 else
1294 gboolean got_eacces = 0;
1295 char *path, *p, *name, *freeme;
1296 size_t len;
1297 size_t pathlen;
1299 path = g_getenv ("PATH");
1300 if (path == NULL)
1302 /* There is no `PATH' in the environment. The default
1303 * search path in libc is the current directory followed by
1304 * the path `confstr' returns for `_CS_PATH'.
1307 /* In GLib we put . last, for security, and don't use the
1308 * unportable confstr(); UNIX98 does not actually specify
1309 * what to search if PATH is unset. POSIX may, dunno.
1312 path = "/bin:/usr/bin:.";
1315 len = strlen (file) + 1;
1316 pathlen = strlen (path);
1317 freeme = name = g_malloc (pathlen + len + 1);
1319 /* Copy the file name at the top, including '\0' */
1320 memcpy (name + pathlen + 1, file, len);
1321 name = name + pathlen;
1322 /* And add the slash before the filename */
1323 *name = '/';
1325 p = path;
1328 char *startp;
1330 path = p;
1331 p = my_strchrnul (path, ':');
1333 if (p == path)
1334 /* Two adjacent colons, or a colon at the beginning or the end
1335 * of `PATH' means to search the current directory.
1337 startp = name + 1;
1338 else
1339 startp = memcpy (name - (p - path), path, p - path);
1341 /* Try to execute this name. If it works, execv will not return. */
1342 if (envp)
1343 execve (startp, argv, envp);
1344 else
1345 execv (startp, argv);
1347 if (errno == ENOEXEC)
1348 script_execute (startp, argv, envp, search_path);
1350 switch (errno)
1352 case EACCES:
1353 /* Record the we got a `Permission denied' error. If we end
1354 * up finding no executable we can use, we want to diagnose
1355 * that we did find one but were denied access.
1357 got_eacces = TRUE;
1359 /* FALL THRU */
1361 case ENOENT:
1362 #ifdef ESTALE
1363 case ESTALE:
1364 #endif
1365 #ifdef ENOTDIR
1366 case ENOTDIR:
1367 #endif
1368 /* Those errors indicate the file is missing or not executable
1369 * by us, in which case we want to just try the next path
1370 * directory.
1372 break;
1374 default:
1375 /* Some other error means we found an executable file, but
1376 * something went wrong executing it; return the error to our
1377 * caller.
1379 g_free (freeme);
1380 return -1;
1383 while (*p++ != '\0');
1385 /* We tried every element and none of them worked. */
1386 if (got_eacces)
1387 /* At least one failure was due to permissions, so report that
1388 * error.
1390 errno = EACCES;
1392 g_free (freeme);
1395 /* Return the error from the last attempt (probably ENOENT). */
1396 return -1;