1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-spawn.c Wrapper around fork/exec
4 * Copyright (C) 2002, 2003, 2004 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "dbus-spawn.h"
28 #include "dbus-sysdeps-unix.h"
29 #include "dbus-internals.h"
30 #include "dbus-test.h"
31 #include "dbus-protocol.h"
42 extern char **environ;
45 * @addtogroup DBusInternalsUtils
50 * I'm pretty sure this whole spawn file could be made simpler,
51 * if you thought about it a bit.
55 * Enumeration for status of a read()
59 READ_STATUS_OK, /**< Read succeeded */
60 READ_STATUS_ERROR, /**< Some kind of error */
61 READ_STATUS_EOF /**< EOF returned */
74 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
76 retval = READ_STATUS_OK;
83 to_read = sizeof (int) * n_ints_in_buf - bytes;
94 if (chunk < 0 && errno == EINTR)
99 dbus_set_error (error,
100 DBUS_ERROR_SPAWN_FAILED,
101 "Failed to read from child pipe (%s)",
102 _dbus_strerror (errno));
104 retval = READ_STATUS_ERROR;
109 retval = READ_STATUS_EOF;
116 *n_ints_read = (int)(bytes / sizeof(int));
129 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
131 retval = READ_STATUS_OK;
138 to_read = sizeof (pid_t) - bytes;
146 ((char*)buf) + bytes,
148 if (chunk < 0 && errno == EINTR)
153 dbus_set_error (error,
154 DBUS_ERROR_SPAWN_FAILED,
155 "Failed to read from child pipe (%s)",
156 _dbus_strerror (errno));
158 retval = READ_STATUS_ERROR;
163 retval = READ_STATUS_EOF;
173 /* The implementation uses an intermediate child between the main process
174 * and the grandchild. The grandchild is our spawned process. The intermediate
175 * child is a babysitter process; it keeps track of when the grandchild
176 * exits/crashes, and reaps the grandchild.
179 /* Messages from children to parents */
182 CHILD_EXITED, /* This message is followed by the exit status int */
183 CHILD_FORK_FAILED, /* Followed by errno */
184 CHILD_EXEC_FAILED, /* Followed by errno */
185 CHILD_PID /* Followed by pid_t */
189 * Babysitter implementation details
191 struct DBusBabysitter
193 int refcount; /**< Reference count */
195 char *executable; /**< executable name to use in error messages */
197 int socket_to_babysitter; /**< Connection to the babysitter process */
198 int error_pipe_from_child; /**< Connection to the process that does the exec() */
200 pid_t sitter_pid; /**< PID Of the babysitter */
201 pid_t grandchild_pid; /**< PID of the grandchild */
203 DBusWatchList *watches; /**< Watches */
205 DBusWatch *error_watch; /**< Error pipe watch */
206 DBusWatch *sitter_watch; /**< Sitter pipe watch */
208 DBusBabysitterFinishedFunc finished_cb;
211 int errnum; /**< Error number */
212 int status; /**< Exit status code */
213 unsigned int have_child_status : 1; /**< True if child status has been reaped */
214 unsigned int have_fork_errnum : 1; /**< True if we have an error code from fork() */
215 unsigned int have_exec_errnum : 1; /**< True if we have an error code from exec() */
218 static DBusBabysitter*
219 _dbus_babysitter_new (void)
221 DBusBabysitter *sitter;
223 sitter = dbus_new0 (DBusBabysitter, 1);
227 sitter->refcount = 1;
229 sitter->socket_to_babysitter = -1;
230 sitter->error_pipe_from_child = -1;
232 sitter->sitter_pid = -1;
233 sitter->grandchild_pid = -1;
235 sitter->watches = _dbus_watch_list_new ();
236 if (sitter->watches == NULL)
242 _dbus_babysitter_unref (sitter);
247 * Increment the reference count on the babysitter object.
249 * @param sitter the babysitter
250 * @returns the babysitter
253 _dbus_babysitter_ref (DBusBabysitter *sitter)
255 _dbus_assert (sitter != NULL);
256 _dbus_assert (sitter->refcount > 0);
258 sitter->refcount += 1;
263 static void close_socket_to_babysitter (DBusBabysitter *sitter);
264 static void close_error_pipe_from_child (DBusBabysitter *sitter);
267 * Decrement the reference count on the babysitter object.
268 * When the reference count of the babysitter object reaches
269 * zero, the babysitter is killed and the child that was being
270 * babysat gets emancipated.
272 * @param sitter the babysitter
275 _dbus_babysitter_unref (DBusBabysitter *sitter)
277 _dbus_assert (sitter != NULL);
278 _dbus_assert (sitter->refcount > 0);
280 sitter->refcount -= 1;
281 if (sitter->refcount == 0)
283 /* If we haven't forked other babysitters
284 * since this babysitter and socket were
285 * created then this close will cause the
286 * babysitter to wake up from poll with
287 * a hangup and then the babysitter will
290 close_socket_to_babysitter (sitter);
292 close_error_pipe_from_child (sitter);
294 if (sitter->sitter_pid > 0)
299 /* It's possible the babysitter died on its own above
300 * from the close, or was killed randomly
301 * by some other process, so first try to reap it
303 ret = waitpid (sitter->sitter_pid, &status, WNOHANG);
305 /* If we couldn't reap the child then kill it, and
309 kill (sitter->sitter_pid, SIGKILL);
313 ret = waitpid (sitter->sitter_pid, &status, 0);
319 else if (errno == ECHILD)
320 _dbus_warn ("Babysitter process not available to be reaped; should not happen\n");
322 _dbus_warn ("Unexpected error %d in waitpid() for babysitter: %s\n",
323 errno, _dbus_strerror (errno));
327 _dbus_verbose ("Reaped %ld, waiting for babysitter %ld\n",
328 (long) ret, (long) sitter->sitter_pid);
330 if (WIFEXITED (sitter->status))
331 _dbus_verbose ("Babysitter exited with status %d\n",
332 WEXITSTATUS (sitter->status));
333 else if (WIFSIGNALED (sitter->status))
334 _dbus_verbose ("Babysitter received signal %d\n",
335 WTERMSIG (sitter->status));
337 _dbus_verbose ("Babysitter exited abnormally\n");
340 sitter->sitter_pid = -1;
344 _dbus_watch_list_free (sitter->watches);
346 dbus_free (sitter->executable);
353 read_data (DBusBabysitter *sitter,
358 DBusError error = DBUS_ERROR_INIT;
361 r = read_ints (fd, &what, 1, &got, &error);
365 case READ_STATUS_ERROR:
366 _dbus_warn ("Failed to read data from fd %d: %s\n", fd, error.message);
367 dbus_error_free (&error);
370 case READ_STATUS_EOF:
382 case CHILD_FORK_FAILED:
383 case CHILD_EXEC_FAILED:
387 r = read_ints (fd, &arg, 1, &got, &error);
391 case READ_STATUS_ERROR:
392 _dbus_warn ("Failed to read arg from fd %d: %s\n", fd, error.message);
393 dbus_error_free (&error);
395 case READ_STATUS_EOF:
403 if (what == CHILD_EXITED)
405 sitter->have_child_status = TRUE;
406 sitter->status = arg;
408 _dbus_verbose ("recorded child status exited = %d signaled = %d exitstatus = %d termsig = %d\n",
409 WIFEXITED (sitter->status), WIFSIGNALED (sitter->status),
410 WEXITSTATUS (sitter->status), WTERMSIG (sitter->status));
412 else if (what == CHILD_FORK_FAILED)
414 sitter->have_fork_errnum = TRUE;
415 sitter->errnum = arg;
416 _dbus_verbose ("recorded fork errnum %d\n", sitter->errnum);
418 else if (what == CHILD_EXEC_FAILED)
420 sitter->have_exec_errnum = TRUE;
421 sitter->errnum = arg;
422 _dbus_verbose ("recorded exec errnum %d\n", sitter->errnum);
431 r = read_pid (fd, &pid, &error);
435 case READ_STATUS_ERROR:
436 _dbus_warn ("Failed to read PID from fd %d: %s\n", fd, error.message);
437 dbus_error_free (&error);
439 case READ_STATUS_EOF:
445 sitter->grandchild_pid = pid;
447 _dbus_verbose ("recorded grandchild pid %d\n", sitter->grandchild_pid);
451 _dbus_warn ("Unknown message received from babysitter process\n");
460 close_socket_to_babysitter (DBusBabysitter *sitter)
462 _dbus_verbose ("Closing babysitter\n");
464 if (sitter->sitter_watch != NULL)
466 _dbus_assert (sitter->watches != NULL);
467 _dbus_watch_list_remove_watch (sitter->watches, sitter->sitter_watch);
468 _dbus_watch_invalidate (sitter->sitter_watch);
469 _dbus_watch_unref (sitter->sitter_watch);
470 sitter->sitter_watch = NULL;
473 if (sitter->socket_to_babysitter >= 0)
475 _dbus_close_socket (sitter->socket_to_babysitter, NULL);
476 sitter->socket_to_babysitter = -1;
481 close_error_pipe_from_child (DBusBabysitter *sitter)
483 _dbus_verbose ("Closing child error\n");
485 if (sitter->error_watch != NULL)
487 _dbus_assert (sitter->watches != NULL);
488 _dbus_watch_list_remove_watch (sitter->watches, sitter->error_watch);
489 _dbus_watch_invalidate (sitter->error_watch);
490 _dbus_watch_unref (sitter->error_watch);
491 sitter->error_watch = NULL;
494 if (sitter->error_pipe_from_child >= 0)
496 _dbus_close_socket (sitter->error_pipe_from_child, NULL);
497 sitter->error_pipe_from_child = -1;
502 handle_babysitter_socket (DBusBabysitter *sitter,
505 /* Even if we have POLLHUP, we want to keep reading
506 * data until POLLIN goes away; so this function only
507 * looks at HUP/ERR if no IN is set.
509 if (revents & _DBUS_POLLIN)
511 _dbus_verbose ("Reading data from babysitter\n");
512 if (read_data (sitter, sitter->socket_to_babysitter) != READ_STATUS_OK)
513 close_socket_to_babysitter (sitter);
515 else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
517 close_socket_to_babysitter (sitter);
522 handle_error_pipe (DBusBabysitter *sitter,
525 if (revents & _DBUS_POLLIN)
527 _dbus_verbose ("Reading data from child error\n");
528 if (read_data (sitter, sitter->error_pipe_from_child) != READ_STATUS_OK)
529 close_error_pipe_from_child (sitter);
531 else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
533 close_error_pipe_from_child (sitter);
537 /* returns whether there were any poll events handled */
539 babysitter_iteration (DBusBabysitter *sitter,
544 dbus_bool_t descriptors_ready;
546 descriptors_ready = FALSE;
550 if (sitter->error_pipe_from_child >= 0)
552 fds[i].fd = sitter->error_pipe_from_child;
553 fds[i].events = _DBUS_POLLIN;
558 if (sitter->socket_to_babysitter >= 0)
560 fds[i].fd = sitter->socket_to_babysitter;
561 fds[i].events = _DBUS_POLLIN;
572 ret = _dbus_poll (fds, i, 0);
574 while (ret < 0 && errno == EINTR);
576 if (ret == 0 && block)
580 ret = _dbus_poll (fds, i, -1);
582 while (ret < 0 && errno == EINTR);
587 descriptors_ready = TRUE;
592 if (fds[i].fd == sitter->error_pipe_from_child)
593 handle_error_pipe (sitter, fds[i].revents);
594 else if (fds[i].fd == sitter->socket_to_babysitter)
595 handle_babysitter_socket (sitter, fds[i].revents);
600 return descriptors_ready;
604 * Macro returns #TRUE if the babysitter still has live sockets open to the
605 * babysitter child or the grandchild.
607 #define LIVE_CHILDREN(sitter) ((sitter)->socket_to_babysitter >= 0 || (sitter)->error_pipe_from_child >= 0)
610 * Blocks until the babysitter process gives us the PID of the spawned grandchild,
611 * then kills the spawned grandchild.
613 * @param sitter the babysitter object
616 _dbus_babysitter_kill_child (DBusBabysitter *sitter)
618 /* be sure we have the PID of the child */
619 while (LIVE_CHILDREN (sitter) &&
620 sitter->grandchild_pid == -1)
621 babysitter_iteration (sitter, TRUE);
623 _dbus_verbose ("Got child PID %ld for killing\n",
624 (long) sitter->grandchild_pid);
626 if (sitter->grandchild_pid == -1)
627 return; /* child is already dead, or we're so hosed we'll never recover */
629 kill (sitter->grandchild_pid, SIGKILL);
633 * Checks whether the child has exited, without blocking.
635 * @param sitter the babysitter
638 _dbus_babysitter_get_child_exited (DBusBabysitter *sitter)
641 /* Be sure we're up-to-date */
642 while (LIVE_CHILDREN (sitter) &&
643 babysitter_iteration (sitter, FALSE))
646 /* We will have exited the babysitter when the child has exited */
647 return sitter->socket_to_babysitter < 0;
651 * Gets the exit status of the child. We do this so implementation specific
652 * detail is not cluttering up dbus, for example the system launcher code.
653 * This can only be called if the child has exited, i.e. call
654 * _dbus_babysitter_get_child_exited(). It returns FALSE if the child
655 * did not return a status code, e.g. because the child was signaled
656 * or we failed to ever launch the child in the first place.
658 * @param sitter the babysitter
659 * @param status the returned status code
660 * @returns #FALSE on failure
663 _dbus_babysitter_get_child_exit_status (DBusBabysitter *sitter,
666 if (!_dbus_babysitter_get_child_exited (sitter))
667 _dbus_assert_not_reached ("Child has not exited");
669 if (!sitter->have_child_status ||
670 !(WIFEXITED (sitter->status)))
673 *status = WEXITSTATUS (sitter->status);
678 * Sets the #DBusError with an explanation of why the spawned
679 * child process exited (on a signal, or whatever). If
680 * the child process has not exited, does nothing (error
681 * will remain unset).
683 * @param sitter the babysitter
684 * @param error an error to fill in
687 _dbus_babysitter_set_child_exit_error (DBusBabysitter *sitter,
690 if (!_dbus_babysitter_get_child_exited (sitter))
693 /* Note that if exec fails, we will also get a child status
694 * from the babysitter saying the child exited,
695 * so we need to give priority to the exec error
697 if (sitter->have_exec_errnum)
699 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
700 "Failed to execute program %s: %s",
701 sitter->executable, _dbus_strerror (sitter->errnum));
703 else if (sitter->have_fork_errnum)
705 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
706 "Failed to fork a new process %s: %s",
707 sitter->executable, _dbus_strerror (sitter->errnum));
709 else if (sitter->have_child_status)
711 if (WIFEXITED (sitter->status))
712 dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_EXITED,
713 "Process %s exited with status %d",
714 sitter->executable, WEXITSTATUS (sitter->status));
715 else if (WIFSIGNALED (sitter->status))
716 dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_SIGNALED,
717 "Process %s received signal %d",
718 sitter->executable, WTERMSIG (sitter->status));
720 dbus_set_error (error, DBUS_ERROR_FAILED,
721 "Process %s exited abnormally",
726 dbus_set_error (error, DBUS_ERROR_FAILED,
727 "Process %s exited, reason unknown",
733 * Sets watch functions to notify us when the
734 * babysitter object needs to read/write file descriptors.
736 * @param sitter the babysitter
737 * @param add_function function to begin monitoring a new descriptor.
738 * @param remove_function function to stop monitoring a descriptor.
739 * @param toggled_function function to notify when the watch is enabled/disabled
740 * @param data data to pass to add_function and remove_function.
741 * @param free_data_function function to be called to free the data.
742 * @returns #FALSE on failure (no memory)
745 _dbus_babysitter_set_watch_functions (DBusBabysitter *sitter,
746 DBusAddWatchFunction add_function,
747 DBusRemoveWatchFunction remove_function,
748 DBusWatchToggledFunction toggled_function,
750 DBusFreeFunction free_data_function)
752 return _dbus_watch_list_set_functions (sitter->watches,
761 handle_watch (DBusWatch *watch,
762 unsigned int condition,
765 DBusBabysitter *sitter = _dbus_babysitter_ref (data);
770 if (condition & DBUS_WATCH_READABLE)
771 revents |= _DBUS_POLLIN;
772 if (condition & DBUS_WATCH_ERROR)
773 revents |= _DBUS_POLLERR;
774 if (condition & DBUS_WATCH_HANGUP)
775 revents |= _DBUS_POLLHUP;
777 fd = dbus_watch_get_socket (watch);
779 if (fd == sitter->error_pipe_from_child)
780 handle_error_pipe (sitter, revents);
781 else if (fd == sitter->socket_to_babysitter)
782 handle_babysitter_socket (sitter, revents);
784 while (LIVE_CHILDREN (sitter) &&
785 babysitter_iteration (sitter, FALSE))
788 /* fd.o #32992: if the handle_* methods closed their sockets, they previously
789 * didn't always remove the watches. Check that we don't regress. */
790 _dbus_assert (sitter->socket_to_babysitter != -1 || sitter->sitter_watch == NULL);
791 _dbus_assert (sitter->error_pipe_from_child != -1 || sitter->error_watch == NULL);
793 if (_dbus_babysitter_get_child_exited (sitter) &&
794 sitter->finished_cb != NULL)
796 sitter->finished_cb (sitter, sitter->finished_data);
797 sitter->finished_cb = NULL;
800 _dbus_babysitter_unref (sitter);
804 /** Helps remember which end of the pipe is which */
806 /** Helps remember which end of the pipe is which */
810 /* Avoids a danger in threaded situations (calling close()
811 * on a file descriptor twice, and another thread has
812 * re-opened it since the first close)
815 close_and_invalidate (int *fd)
823 ret = _dbus_close_socket (*fd, NULL);
837 dbus_bool_t cloexec_done;
839 retval = pipe2 (p, O_CLOEXEC);
840 cloexec_done = retval >= 0;
842 /* Check if kernel seems to be too old to know pipe2(). We assume
843 that if pipe2 is available, O_CLOEXEC is too. */
844 if (retval < 0 && errno == ENOSYS)
850 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
854 dbus_set_error (error,
855 DBUS_ERROR_SPAWN_FAILED,
856 "Failed to create pipe for communicating with child process (%s)",
857 _dbus_strerror (errno));
865 _dbus_fd_set_close_on_exec (p[0]);
866 _dbus_fd_set_close_on_exec (p[1]);
873 do_write (int fd, const void *buf, size_t count)
875 size_t bytes_written;
882 ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
890 _dbus_warn ("Failed to write data to pipe!\n");
891 exit (1); /* give up, we suck */
895 bytes_written += ret;
897 if (bytes_written < count)
902 write_err_and_exit (int fd, int msg)
906 do_write (fd, &msg, sizeof (msg));
907 do_write (fd, &en, sizeof (en));
913 write_pid (int fd, pid_t pid)
917 do_write (fd, &msg, sizeof (msg));
918 do_write (fd, &pid, sizeof (pid));
922 write_status_and_exit (int fd, int status)
924 int msg = CHILD_EXITED;
926 do_write (fd, &msg, sizeof (msg));
927 do_write (fd, &status, sizeof (status));
933 do_exec (int child_err_report_fd,
936 DBusSpawnChildSetupFunc child_setup,
939 #ifdef DBUS_BUILD_TESTS
943 _dbus_verbose_reset ();
944 _dbus_verbose ("Child process has PID " DBUS_PID_FORMAT "\n",
948 (* child_setup) (user_data);
950 #ifdef DBUS_BUILD_TESTS
951 max_open = sysconf (_SC_OPEN_MAX);
953 for (i = 3; i < max_open; i++)
957 if (i == child_err_report_fd)
960 retval = fcntl (i, F_GETFD);
962 if (retval != -1 && !(retval & FD_CLOEXEC))
963 _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
969 _dbus_assert (environ != NULL);
974 execve (argv[0], argv, envp);
977 write_err_and_exit (child_err_report_fd,
982 check_babysit_events (pid_t grandchild_pid,
991 ret = waitpid (grandchild_pid, &status, WNOHANG);
992 /* The man page says EINTR can't happen with WNOHANG,
993 * but there are reports of it (maybe only with valgrind?)
996 while (ret < 0 && errno == EINTR);
1000 _dbus_verbose ("no child exited\n");
1002 ; /* no child exited */
1006 /* This isn't supposed to happen. */
1007 _dbus_warn ("unexpected waitpid() failure in check_babysit_events(): %s\n",
1008 _dbus_strerror (errno));
1011 else if (ret == grandchild_pid)
1014 _dbus_verbose ("reaped child pid %ld\n", (long) ret);
1016 write_status_and_exit (parent_pipe, status);
1020 _dbus_warn ("waitpid() reaped pid %d that we've never heard of\n",
1025 if (revents & _DBUS_POLLIN)
1027 _dbus_verbose ("babysitter got POLLIN from parent pipe\n");
1030 if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
1032 /* Parent is gone, so we just exit */
1033 _dbus_verbose ("babysitter got POLLERR or POLLHUP from parent\n");
1038 static int babysit_sigchld_pipe = -1;
1041 babysit_signal_handler (int signo)
1045 if (write (babysit_sigchld_pipe, &b, 1) <= 0)
1051 babysit (pid_t grandchild_pid,
1054 int sigchld_pipe[2];
1056 /* We don't exec, so we keep parent state, such as the pid that
1057 * _dbus_verbose() uses. Reset the pid here.
1059 _dbus_verbose_reset ();
1061 /* I thought SIGCHLD would just wake up the poll, but
1062 * that didn't seem to work, so added this pipe.
1063 * Probably the pipe is more likely to work on busted
1064 * operating systems anyhow.
1066 if (pipe (sigchld_pipe) < 0)
1068 _dbus_warn ("Not enough file descriptors to create pipe in babysitter process\n");
1072 babysit_sigchld_pipe = sigchld_pipe[WRITE_END];
1074 _dbus_set_signal_handler (SIGCHLD, babysit_signal_handler);
1076 write_pid (parent_pipe, grandchild_pid);
1078 check_babysit_events (grandchild_pid, parent_pipe, 0);
1084 pfds[0].fd = parent_pipe;
1085 pfds[0].events = _DBUS_POLLIN;
1086 pfds[0].revents = 0;
1088 pfds[1].fd = sigchld_pipe[READ_END];
1089 pfds[1].events = _DBUS_POLLIN;
1090 pfds[1].revents = 0;
1092 if (_dbus_poll (pfds, _DBUS_N_ELEMENTS (pfds), -1) < 0 && errno != EINTR)
1094 _dbus_warn ("_dbus_poll() error: %s\n", strerror (errno));
1098 if (pfds[0].revents != 0)
1100 check_babysit_events (grandchild_pid, parent_pipe, pfds[0].revents);
1102 else if (pfds[1].revents & _DBUS_POLLIN)
1105 if (read (sigchld_pipe[READ_END], &b, 1) == -1)
1107 /* do waitpid check */
1108 check_babysit_events (grandchild_pid, parent_pipe, 0);
1116 * Spawns a new process. The executable name and argv[0]
1117 * are the same, both are provided in argv[0]. The child_setup
1118 * function is passed the given user_data and is run in the child
1119 * just before calling exec().
1121 * Also creates a "babysitter" which tracks the status of the
1122 * child process, advising the parent if the child exits.
1123 * If the spawn fails, no babysitter is created.
1124 * If sitter_p is #NULL, no babysitter is kept.
1126 * @param sitter_p return location for babysitter or #NULL
1127 * @param argv the executable and arguments
1128 * @param env the environment (not used on unix yet)
1129 * @param child_setup function to call in child pre-exec()
1130 * @param user_data user data for setup function
1131 * @param error error object to be filled in if function fails
1132 * @returns #TRUE on success, #FALSE if error is filled in
1135 _dbus_spawn_async_with_babysitter (DBusBabysitter **sitter_p,
1138 DBusSpawnChildSetupFunc child_setup,
1142 DBusBabysitter *sitter;
1143 int child_err_report_pipe[2] = { -1, -1 };
1144 int babysitter_pipe[2] = { -1, -1 };
1147 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1149 if (sitter_p != NULL)
1154 sitter = _dbus_babysitter_new ();
1157 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1161 sitter->executable = _dbus_strdup (argv[0]);
1162 if (sitter->executable == NULL)
1164 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1165 goto cleanup_and_fail;
1168 if (!make_pipe (child_err_report_pipe, error))
1169 goto cleanup_and_fail;
1171 if (!_dbus_full_duplex_pipe (&babysitter_pipe[0], &babysitter_pipe[1], TRUE, error))
1172 goto cleanup_and_fail;
1174 /* Setting up the babysitter is only useful in the parent,
1175 * but we don't want to run out of memory and fail
1176 * after we've already forked, since then we'd leak
1177 * child processes everywhere.
1179 sitter->error_watch = _dbus_watch_new (child_err_report_pipe[READ_END],
1180 DBUS_WATCH_READABLE,
1181 TRUE, handle_watch, sitter, NULL);
1182 if (sitter->error_watch == NULL)
1184 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1185 goto cleanup_and_fail;
1188 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->error_watch))
1190 /* we need to free it early so the destructor won't try to remove it
1191 * without it having been added, which DBusLoop doesn't allow */
1192 _dbus_watch_invalidate (sitter->error_watch);
1193 _dbus_watch_unref (sitter->error_watch);
1194 sitter->error_watch = NULL;
1196 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1197 goto cleanup_and_fail;
1200 sitter->sitter_watch = _dbus_watch_new (babysitter_pipe[0],
1201 DBUS_WATCH_READABLE,
1202 TRUE, handle_watch, sitter, NULL);
1203 if (sitter->sitter_watch == NULL)
1205 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1206 goto cleanup_and_fail;
1209 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->sitter_watch))
1211 /* we need to free it early so the destructor won't try to remove it
1212 * without it having been added, which DBusLoop doesn't allow */
1213 _dbus_watch_invalidate (sitter->sitter_watch);
1214 _dbus_watch_unref (sitter->sitter_watch);
1215 sitter->sitter_watch = NULL;
1217 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1218 goto cleanup_and_fail;
1221 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1227 dbus_set_error (error,
1228 DBUS_ERROR_SPAWN_FORK_FAILED,
1229 "Failed to fork (%s)",
1230 _dbus_strerror (errno));
1231 goto cleanup_and_fail;
1235 /* Immediate child, this is the babysitter process. */
1238 /* Be sure we crash if the parent exits
1239 * and we write to the err_report_pipe
1241 signal (SIGPIPE, SIG_DFL);
1243 /* Close the parent's end of the pipes. */
1244 close_and_invalidate (&child_err_report_pipe[READ_END]);
1245 close_and_invalidate (&babysitter_pipe[0]);
1247 /* Create the child that will exec () */
1248 grandchild_pid = fork ();
1250 if (grandchild_pid < 0)
1252 write_err_and_exit (babysitter_pipe[1],
1254 _dbus_assert_not_reached ("Got to code after write_err_and_exit()");
1256 else if (grandchild_pid == 0)
1258 do_exec (child_err_report_pipe[WRITE_END],
1261 child_setup, user_data);
1262 _dbus_assert_not_reached ("Got to code after exec() - should have exited on error");
1266 babysit (grandchild_pid, babysitter_pipe[1]);
1267 _dbus_assert_not_reached ("Got to code after babysit()");
1272 /* Close the uncared-about ends of the pipes */
1273 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1274 close_and_invalidate (&babysitter_pipe[1]);
1276 sitter->socket_to_babysitter = babysitter_pipe[0];
1277 babysitter_pipe[0] = -1;
1279 sitter->error_pipe_from_child = child_err_report_pipe[READ_END];
1280 child_err_report_pipe[READ_END] = -1;
1282 sitter->sitter_pid = pid;
1284 if (sitter_p != NULL)
1287 _dbus_babysitter_unref (sitter);
1289 dbus_free_string_array (env);
1291 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1298 _DBUS_ASSERT_ERROR_IS_SET (error);
1300 close_and_invalidate (&child_err_report_pipe[READ_END]);
1301 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1302 close_and_invalidate (&babysitter_pipe[0]);
1303 close_and_invalidate (&babysitter_pipe[1]);
1306 _dbus_babysitter_unref (sitter);
1312 _dbus_babysitter_set_result_function (DBusBabysitter *sitter,
1313 DBusBabysitterFinishedFunc finished,
1316 sitter->finished_cb = finished;
1317 sitter->finished_data = user_data;
1322 #ifdef DBUS_BUILD_TESTS
1325 _dbus_babysitter_block_for_child_exit (DBusBabysitter *sitter)
1327 while (LIVE_CHILDREN (sitter))
1328 babysitter_iteration (sitter, TRUE);
1332 check_spawn_nonexistent (void *data)
1334 char *argv[4] = { NULL, NULL, NULL, NULL };
1335 DBusBabysitter *sitter = NULL;
1336 DBusError error = DBUS_ERROR_INIT;
1338 /*** Test launching nonexistent binary */
1340 argv[0] = "/this/does/not/exist/32542sdgafgafdg";
1341 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1345 _dbus_babysitter_block_for_child_exit (sitter);
1346 _dbus_babysitter_set_child_exit_error (sitter, &error);
1350 _dbus_babysitter_unref (sitter);
1352 if (!dbus_error_is_set (&error))
1354 _dbus_warn ("Did not get an error launching nonexistent executable\n");
1358 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1359 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_EXEC_FAILED)))
1361 _dbus_warn ("Not expecting error when launching nonexistent executable: %s: %s\n",
1362 error.name, error.message);
1363 dbus_error_free (&error);
1367 dbus_error_free (&error);
1373 check_spawn_segfault (void *data)
1375 char *argv[4] = { NULL, NULL, NULL, NULL };
1376 DBusBabysitter *sitter = NULL;
1377 DBusError error = DBUS_ERROR_INIT;
1379 /*** Test launching segfault binary */
1381 argv[0] = TEST_SEGFAULT_BINARY;
1382 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1386 _dbus_babysitter_block_for_child_exit (sitter);
1387 _dbus_babysitter_set_child_exit_error (sitter, &error);
1391 _dbus_babysitter_unref (sitter);
1393 if (!dbus_error_is_set (&error))
1395 _dbus_warn ("Did not get an error launching segfaulting binary\n");
1399 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1400 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
1402 _dbus_warn ("Not expecting error when launching segfaulting executable: %s: %s\n",
1403 error.name, error.message);
1404 dbus_error_free (&error);
1408 dbus_error_free (&error);
1414 check_spawn_exit (void *data)
1416 char *argv[4] = { NULL, NULL, NULL, NULL };
1417 DBusBabysitter *sitter = NULL;
1418 DBusError error = DBUS_ERROR_INIT;
1420 /*** Test launching exit failure binary */
1422 argv[0] = TEST_EXIT_BINARY;
1423 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1427 _dbus_babysitter_block_for_child_exit (sitter);
1428 _dbus_babysitter_set_child_exit_error (sitter, &error);
1432 _dbus_babysitter_unref (sitter);
1434 if (!dbus_error_is_set (&error))
1436 _dbus_warn ("Did not get an error launching binary that exited with failure code\n");
1440 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1441 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_EXITED)))
1443 _dbus_warn ("Not expecting error when launching exiting executable: %s: %s\n",
1444 error.name, error.message);
1445 dbus_error_free (&error);
1449 dbus_error_free (&error);
1455 check_spawn_and_kill (void *data)
1457 char *argv[4] = { NULL, NULL, NULL, NULL };
1458 DBusBabysitter *sitter = NULL;
1459 DBusError error = DBUS_ERROR_INIT;
1461 /*** Test launching sleeping binary then killing it */
1463 argv[0] = TEST_SLEEP_FOREVER_BINARY;
1464 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1468 _dbus_babysitter_kill_child (sitter);
1470 _dbus_babysitter_block_for_child_exit (sitter);
1472 _dbus_babysitter_set_child_exit_error (sitter, &error);
1476 _dbus_babysitter_unref (sitter);
1478 if (!dbus_error_is_set (&error))
1480 _dbus_warn ("Did not get an error after killing spawned binary\n");
1484 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1485 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
1487 _dbus_warn ("Not expecting error when killing executable: %s: %s\n",
1488 error.name, error.message);
1489 dbus_error_free (&error);
1493 dbus_error_free (&error);
1499 _dbus_spawn_test (const char *test_data_dir)
1501 if (!_dbus_test_oom_handling ("spawn_nonexistent",
1502 check_spawn_nonexistent,
1506 if (!_dbus_test_oom_handling ("spawn_segfault",
1507 check_spawn_segfault,
1511 if (!_dbus_test_oom_handling ("spawn_exit",
1516 if (!_dbus_test_oom_handling ("spawn_and_kill",
1517 check_spawn_and_kill,