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)
1109 /* do waitpid check */
1110 check_babysit_events (grandchild_pid, parent_pipe, 0);
1118 * Spawns a new process. The executable name and argv[0]
1119 * are the same, both are provided in argv[0]. The child_setup
1120 * function is passed the given user_data and is run in the child
1121 * just before calling exec().
1123 * Also creates a "babysitter" which tracks the status of the
1124 * child process, advising the parent if the child exits.
1125 * If the spawn fails, no babysitter is created.
1126 * If sitter_p is #NULL, no babysitter is kept.
1128 * @param sitter_p return location for babysitter or #NULL
1129 * @param argv the executable and arguments
1130 * @param env the environment (not used on unix yet)
1131 * @param child_setup function to call in child pre-exec()
1132 * @param user_data user data for setup function
1133 * @param error error object to be filled in if function fails
1134 * @returns #TRUE on success, #FALSE if error is filled in
1137 _dbus_spawn_async_with_babysitter (DBusBabysitter **sitter_p,
1140 DBusSpawnChildSetupFunc child_setup,
1144 DBusBabysitter *sitter;
1145 int child_err_report_pipe[2] = { -1, -1 };
1146 int babysitter_pipe[2] = { -1, -1 };
1149 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1151 if (sitter_p != NULL)
1156 sitter = _dbus_babysitter_new ();
1159 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1163 sitter->executable = _dbus_strdup (argv[0]);
1164 if (sitter->executable == NULL)
1166 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1167 goto cleanup_and_fail;
1170 if (!make_pipe (child_err_report_pipe, error))
1171 goto cleanup_and_fail;
1173 if (!_dbus_full_duplex_pipe (&babysitter_pipe[0], &babysitter_pipe[1], TRUE, error))
1174 goto cleanup_and_fail;
1176 /* Setting up the babysitter is only useful in the parent,
1177 * but we don't want to run out of memory and fail
1178 * after we've already forked, since then we'd leak
1179 * child processes everywhere.
1181 sitter->error_watch = _dbus_watch_new (child_err_report_pipe[READ_END],
1182 DBUS_WATCH_READABLE,
1183 TRUE, handle_watch, sitter, NULL);
1184 if (sitter->error_watch == NULL)
1186 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1187 goto cleanup_and_fail;
1190 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->error_watch))
1192 /* we need to free it early so the destructor won't try to remove it
1193 * without it having been added, which DBusLoop doesn't allow */
1194 _dbus_watch_invalidate (sitter->error_watch);
1195 _dbus_watch_unref (sitter->error_watch);
1196 sitter->error_watch = NULL;
1198 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1199 goto cleanup_and_fail;
1202 sitter->sitter_watch = _dbus_watch_new (babysitter_pipe[0],
1203 DBUS_WATCH_READABLE,
1204 TRUE, handle_watch, sitter, NULL);
1205 if (sitter->sitter_watch == NULL)
1207 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1208 goto cleanup_and_fail;
1211 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->sitter_watch))
1213 /* we need to free it early so the destructor won't try to remove it
1214 * without it having been added, which DBusLoop doesn't allow */
1215 _dbus_watch_invalidate (sitter->sitter_watch);
1216 _dbus_watch_unref (sitter->sitter_watch);
1217 sitter->sitter_watch = NULL;
1219 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1220 goto cleanup_and_fail;
1223 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1229 dbus_set_error (error,
1230 DBUS_ERROR_SPAWN_FORK_FAILED,
1231 "Failed to fork (%s)",
1232 _dbus_strerror (errno));
1233 goto cleanup_and_fail;
1237 /* Immediate child, this is the babysitter process. */
1240 /* Be sure we crash if the parent exits
1241 * and we write to the err_report_pipe
1243 signal (SIGPIPE, SIG_DFL);
1245 /* Close the parent's end of the pipes. */
1246 close_and_invalidate (&child_err_report_pipe[READ_END]);
1247 close_and_invalidate (&babysitter_pipe[0]);
1249 /* Create the child that will exec () */
1250 grandchild_pid = fork ();
1252 if (grandchild_pid < 0)
1254 write_err_and_exit (babysitter_pipe[1],
1256 _dbus_assert_not_reached ("Got to code after write_err_and_exit()");
1258 else if (grandchild_pid == 0)
1260 /* Go back to ignoring SIGPIPE, since it's evil
1262 signal (SIGPIPE, SIG_IGN);
1264 do_exec (child_err_report_pipe[WRITE_END],
1267 child_setup, user_data);
1268 _dbus_assert_not_reached ("Got to code after exec() - should have exited on error");
1272 babysit (grandchild_pid, babysitter_pipe[1]);
1273 _dbus_assert_not_reached ("Got to code after babysit()");
1278 /* Close the uncared-about ends of the pipes */
1279 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1280 close_and_invalidate (&babysitter_pipe[1]);
1282 sitter->socket_to_babysitter = babysitter_pipe[0];
1283 babysitter_pipe[0] = -1;
1285 sitter->error_pipe_from_child = child_err_report_pipe[READ_END];
1286 child_err_report_pipe[READ_END] = -1;
1288 sitter->sitter_pid = pid;
1290 if (sitter_p != NULL)
1293 _dbus_babysitter_unref (sitter);
1295 dbus_free_string_array (env);
1297 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1304 _DBUS_ASSERT_ERROR_IS_SET (error);
1306 close_and_invalidate (&child_err_report_pipe[READ_END]);
1307 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1308 close_and_invalidate (&babysitter_pipe[0]);
1309 close_and_invalidate (&babysitter_pipe[1]);
1312 _dbus_babysitter_unref (sitter);
1318 _dbus_babysitter_set_result_function (DBusBabysitter *sitter,
1319 DBusBabysitterFinishedFunc finished,
1322 sitter->finished_cb = finished;
1323 sitter->finished_data = user_data;
1328 #ifdef DBUS_BUILD_TESTS
1331 get_test_exec (const char *exe,
1332 DBusString *scratch_space)
1334 const char *dbus_test_exec;
1336 dbus_test_exec = _dbus_getenv ("DBUS_TEST_EXEC");
1338 if (dbus_test_exec == NULL)
1339 dbus_test_exec = DBUS_TEST_EXEC;
1341 if (!_dbus_string_init (scratch_space))
1344 if (!_dbus_string_append_printf (scratch_space, "%s/%s%s",
1345 dbus_test_exec, exe, DBUS_EXEEXT))
1347 _dbus_string_free (scratch_space);
1351 return _dbus_string_get_data (scratch_space);
1355 _dbus_babysitter_block_for_child_exit (DBusBabysitter *sitter)
1357 while (LIVE_CHILDREN (sitter))
1358 babysitter_iteration (sitter, TRUE);
1362 check_spawn_nonexistent (void *data)
1364 char *argv[4] = { NULL, NULL, NULL, NULL };
1365 DBusBabysitter *sitter = NULL;
1366 DBusError error = DBUS_ERROR_INIT;
1368 /*** Test launching nonexistent binary */
1370 argv[0] = "/this/does/not/exist/32542sdgafgafdg";
1371 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1375 _dbus_babysitter_block_for_child_exit (sitter);
1376 _dbus_babysitter_set_child_exit_error (sitter, &error);
1380 _dbus_babysitter_unref (sitter);
1382 if (!dbus_error_is_set (&error))
1384 _dbus_warn ("Did not get an error launching nonexistent executable\n");
1388 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1389 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_EXEC_FAILED)))
1391 _dbus_warn ("Not expecting error when launching nonexistent executable: %s: %s\n",
1392 error.name, error.message);
1393 dbus_error_free (&error);
1397 dbus_error_free (&error);
1403 check_spawn_segfault (void *data)
1405 char *argv[4] = { NULL, NULL, NULL, NULL };
1406 DBusBabysitter *sitter = NULL;
1407 DBusError error = DBUS_ERROR_INIT;
1410 /*** Test launching segfault binary */
1412 argv[0] = get_test_exec ("test-segfault", &argv0);
1414 if (argv[0] == NULL)
1416 /* OOM was simulated, never mind */
1420 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1424 _dbus_babysitter_block_for_child_exit (sitter);
1425 _dbus_babysitter_set_child_exit_error (sitter, &error);
1428 _dbus_string_free (&argv0);
1431 _dbus_babysitter_unref (sitter);
1433 if (!dbus_error_is_set (&error))
1435 _dbus_warn ("Did not get an error launching segfaulting binary\n");
1439 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1440 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
1442 _dbus_warn ("Not expecting error when launching segfaulting executable: %s: %s\n",
1443 error.name, error.message);
1444 dbus_error_free (&error);
1448 dbus_error_free (&error);
1454 check_spawn_exit (void *data)
1456 char *argv[4] = { NULL, NULL, NULL, NULL };
1457 DBusBabysitter *sitter = NULL;
1458 DBusError error = DBUS_ERROR_INIT;
1461 /*** Test launching exit failure binary */
1463 argv[0] = get_test_exec ("test-exit", &argv0);
1465 if (argv[0] == NULL)
1467 /* OOM was simulated, never mind */
1471 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1475 _dbus_babysitter_block_for_child_exit (sitter);
1476 _dbus_babysitter_set_child_exit_error (sitter, &error);
1479 _dbus_string_free (&argv0);
1482 _dbus_babysitter_unref (sitter);
1484 if (!dbus_error_is_set (&error))
1486 _dbus_warn ("Did not get an error launching binary that exited with failure code\n");
1490 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1491 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_EXITED)))
1493 _dbus_warn ("Not expecting error when launching exiting executable: %s: %s\n",
1494 error.name, error.message);
1495 dbus_error_free (&error);
1499 dbus_error_free (&error);
1505 check_spawn_and_kill (void *data)
1507 char *argv[4] = { NULL, NULL, NULL, NULL };
1508 DBusBabysitter *sitter = NULL;
1509 DBusError error = DBUS_ERROR_INIT;
1512 /*** Test launching sleeping binary then killing it */
1514 argv[0] = get_test_exec ("test-sleep-forever", &argv0);
1516 if (argv[0] == NULL)
1518 /* OOM was simulated, never mind */
1522 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1526 _dbus_babysitter_kill_child (sitter);
1528 _dbus_babysitter_block_for_child_exit (sitter);
1530 _dbus_babysitter_set_child_exit_error (sitter, &error);
1533 _dbus_string_free (&argv0);
1536 _dbus_babysitter_unref (sitter);
1538 if (!dbus_error_is_set (&error))
1540 _dbus_warn ("Did not get an error after killing spawned binary\n");
1544 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1545 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
1547 _dbus_warn ("Not expecting error when killing executable: %s: %s\n",
1548 error.name, error.message);
1549 dbus_error_free (&error);
1553 dbus_error_free (&error);
1559 _dbus_spawn_test (const char *test_data_dir)
1561 if (!_dbus_test_oom_handling ("spawn_nonexistent",
1562 check_spawn_nonexistent,
1566 if (!_dbus_test_oom_handling ("spawn_segfault",
1567 check_spawn_segfault,
1571 if (!_dbus_test_oom_handling ("spawn_exit",
1576 if (!_dbus_test_oom_handling ("spawn_and_kill",
1577 check_spawn_and_kill,