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"
45 #include <systemd/sd-journal.h>
48 #if defined(__APPLE__)
49 # include <crt_externs.h>
50 # define environ (*_NSGetEnviron ())
51 #elif !HAVE_DECL_ENVIRON
52 extern char **environ;
56 * @addtogroup DBusInternalsUtils
61 * I'm pretty sure this whole spawn file could be made simpler,
62 * if you thought about it a bit.
66 * Enumeration for status of a read()
70 READ_STATUS_OK, /**< Read succeeded */
71 READ_STATUS_ERROR, /**< Some kind of error */
72 READ_STATUS_EOF /**< EOF returned */
85 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
87 retval = READ_STATUS_OK;
94 to_read = sizeof (int) * n_ints_in_buf - bytes;
102 ((char*)buf) + bytes,
105 if (chunk < 0 && errno == EINTR)
110 dbus_set_error (error,
111 DBUS_ERROR_SPAWN_FAILED,
112 "Failed to read from child pipe (%s)",
113 _dbus_strerror (errno));
115 retval = READ_STATUS_ERROR;
120 retval = READ_STATUS_EOF;
127 *n_ints_read = (int)(bytes / sizeof(int));
140 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
142 retval = READ_STATUS_OK;
149 to_read = sizeof (pid_t) - bytes;
157 ((char*)buf) + bytes,
159 if (chunk < 0 && errno == EINTR)
164 dbus_set_error (error,
165 DBUS_ERROR_SPAWN_FAILED,
166 "Failed to read from child pipe (%s)",
167 _dbus_strerror (errno));
169 retval = READ_STATUS_ERROR;
174 retval = READ_STATUS_EOF;
184 /* The implementation uses an intermediate child between the main process
185 * and the grandchild. The grandchild is our spawned process. The intermediate
186 * child is a babysitter process; it keeps track of when the grandchild
187 * exits/crashes, and reaps the grandchild.
189 * We automatically reap the babysitter process, killing it if necessary,
190 * when the DBusBabysitter's refcount goes to zero.
198 * \- grandchild --> exec --> spawned process
201 * child_err_report_pipe
202 * /-----------<---------<--------------\
205 * main process babysitter grandchild
208 * \-------<->-------/
211 * child_err_report_pipe is genuinely a pipe.
212 * The READ_END (also called error_pipe_from_child) is used in the main
213 * process. The WRITE_END (also called child_err_report_fd) is used in
214 * the grandchild process.
216 * On failure, the grandchild process sends CHILD_EXEC_FAILED + errno.
217 * On success, the pipe just closes (because it's close-on-exec) without
220 * babysitter_pipe is mis-named: it's really a bidirectional socketpair.
221 * The [0] end (also called socket_to_babysitter) is used in the main
222 * process, the [1] end (also called parent_pipe) is used in the babysitter.
224 * If the fork() labelled B in the diagram above fails, the babysitter sends
225 * CHILD_FORK_FAILED + errno.
226 * On success, the babysitter sends CHILD_PID + the grandchild's pid.
227 * On SIGCHLD, the babysitter sends CHILD_EXITED + the exit status.
228 * The main process doesn't explicitly send anything, but when it exits,
229 * the babysitter gets POLLHUP or POLLERR.
232 /* Messages from children to parents */
235 CHILD_EXITED, /* This message is followed by the exit status int */
236 CHILD_FORK_FAILED, /* Followed by errno */
237 CHILD_EXEC_FAILED, /* Followed by errno */
238 CHILD_PID /* Followed by pid_t */
242 * Babysitter implementation details
244 struct DBusBabysitter
246 int refcount; /**< Reference count */
248 char *log_name; /**< the name under which to log messages about this
249 process being spawned */
251 DBusSocket socket_to_babysitter; /**< Connection to the babysitter process */
252 int error_pipe_from_child; /**< Connection to the process that does the exec() */
254 pid_t sitter_pid; /**< PID Of the babysitter */
255 pid_t grandchild_pid; /**< PID of the grandchild */
257 DBusWatchList *watches; /**< Watches */
259 DBusWatch *error_watch; /**< Error pipe watch */
260 DBusWatch *sitter_watch; /**< Sitter pipe watch */
262 DBusBabysitterFinishedFunc finished_cb;
265 int errnum; /**< Error number */
266 int status; /**< Exit status code */
267 unsigned int have_child_status : 1; /**< True if child status has been reaped */
268 unsigned int have_fork_errnum : 1; /**< True if we have an error code from fork() */
269 unsigned int have_exec_errnum : 1; /**< True if we have an error code from exec() */
272 static DBusBabysitter*
273 _dbus_babysitter_new (void)
275 DBusBabysitter *sitter;
277 sitter = dbus_new0 (DBusBabysitter, 1);
281 sitter->refcount = 1;
283 sitter->socket_to_babysitter.fd = -1;
284 sitter->error_pipe_from_child = -1;
286 sitter->sitter_pid = -1;
287 sitter->grandchild_pid = -1;
289 sitter->watches = _dbus_watch_list_new ();
290 if (sitter->watches == NULL)
296 _dbus_babysitter_unref (sitter);
301 * Increment the reference count on the babysitter object.
303 * @param sitter the babysitter
304 * @returns the babysitter
307 _dbus_babysitter_ref (DBusBabysitter *sitter)
309 _dbus_assert (sitter != NULL);
310 _dbus_assert (sitter->refcount > 0);
312 sitter->refcount += 1;
317 static void close_socket_to_babysitter (DBusBabysitter *sitter);
318 static void close_error_pipe_from_child (DBusBabysitter *sitter);
321 * Decrement the reference count on the babysitter object.
322 * When the reference count of the babysitter object reaches
323 * zero, the babysitter is killed and the child that was being
324 * babysat gets emancipated.
326 * @param sitter the babysitter
329 _dbus_babysitter_unref (DBusBabysitter *sitter)
331 _dbus_assert (sitter != NULL);
332 _dbus_assert (sitter->refcount > 0);
334 sitter->refcount -= 1;
335 if (sitter->refcount == 0)
337 /* If we haven't forked other babysitters
338 * since this babysitter and socket were
339 * created then this close will cause the
340 * babysitter to wake up from poll with
341 * a hangup and then the babysitter will
344 close_socket_to_babysitter (sitter);
346 close_error_pipe_from_child (sitter);
348 if (sitter->sitter_pid > 0)
353 /* It's possible the babysitter died on its own above
354 * from the close, or was killed randomly
355 * by some other process, so first try to reap it
357 ret = waitpid (sitter->sitter_pid, &status, WNOHANG);
359 /* If we couldn't reap the child then kill it, and
363 kill (sitter->sitter_pid, SIGKILL);
369 ret = waitpid (sitter->sitter_pid, &status, 0);
371 while (_DBUS_UNLIKELY (ret < 0 && errno == EINTR));
377 _dbus_warn ("Babysitter process not available to be reaped; should not happen");
379 _dbus_warn ("Unexpected error %d in waitpid() for babysitter: %s",
380 errno, _dbus_strerror (errno));
384 _dbus_verbose ("Reaped %ld, waiting for babysitter %ld\n",
385 (long) ret, (long) sitter->sitter_pid);
387 if (WIFEXITED (sitter->status))
388 _dbus_verbose ("Babysitter exited with status %d\n",
389 WEXITSTATUS (sitter->status));
390 else if (WIFSIGNALED (sitter->status))
391 _dbus_verbose ("Babysitter received signal %d\n",
392 WTERMSIG (sitter->status));
394 _dbus_verbose ("Babysitter exited abnormally\n");
397 sitter->sitter_pid = -1;
401 _dbus_watch_list_free (sitter->watches);
403 dbus_free (sitter->log_name);
410 read_data (DBusBabysitter *sitter,
415 DBusError error = DBUS_ERROR_INIT;
418 r = read_ints (fd, &what, 1, &got, &error);
422 case READ_STATUS_ERROR:
423 _dbus_warn ("Failed to read data from fd %d: %s", fd, error.message);
424 dbus_error_free (&error);
427 case READ_STATUS_EOF:
434 _dbus_assert_not_reached ("invalid ReadStatus");
443 case CHILD_FORK_FAILED:
444 case CHILD_EXEC_FAILED:
448 r = read_ints (fd, &arg, 1, &got, &error);
452 case READ_STATUS_ERROR:
453 _dbus_warn ("Failed to read arg from fd %d: %s", fd, error.message);
454 dbus_error_free (&error);
456 case READ_STATUS_EOF:
461 _dbus_assert_not_reached ("invalid ReadStatus");
467 if (what == CHILD_EXITED)
469 /* Do not reset sitter->errnum to 0 here. We get here if
470 * the babysitter reports that the grandchild process has
471 * exited, and there are two ways that can happen:
473 * 1. grandchild successfully exec()s the desired process,
474 * but then the desired process exits or is terminated
475 * by a signal. The babysitter observes this and reports
478 * 2. grandchild fails to exec() the desired process,
479 * attempts to report the exec() failure (which
480 * we will receive as CHILD_EXEC_FAILED), and then
481 * exits itself (which will prompt the babysitter to
482 * send CHILD_EXITED). We want the CHILD_EXEC_FAILED
483 * to take precedence (and have its errno logged),
484 * which _dbus_babysitter_set_child_exit_error() does.
486 sitter->have_child_status = TRUE;
487 sitter->status = arg;
488 _dbus_verbose ("recorded child status exited = %d signaled = %d exitstatus = %d termsig = %d\n",
489 WIFEXITED (sitter->status), WIFSIGNALED (sitter->status),
490 WEXITSTATUS (sitter->status), WTERMSIG (sitter->status));
492 else if (what == CHILD_FORK_FAILED)
494 sitter->have_fork_errnum = TRUE;
495 sitter->errnum = arg;
496 _dbus_verbose ("recorded fork errnum %d\n", sitter->errnum);
498 else if (what == CHILD_EXEC_FAILED)
500 sitter->have_exec_errnum = TRUE;
501 sitter->errnum = arg;
502 _dbus_verbose ("recorded exec errnum %d\n", sitter->errnum);
511 r = read_pid (fd, &pid, &error);
515 case READ_STATUS_ERROR:
516 _dbus_warn ("Failed to read PID from fd %d: %s", fd, error.message);
517 dbus_error_free (&error);
519 case READ_STATUS_EOF:
524 _dbus_assert_not_reached ("invalid ReadStatus");
528 sitter->grandchild_pid = pid;
530 _dbus_verbose ("recorded grandchild pid %d\n", sitter->grandchild_pid);
534 _dbus_warn ("Unknown message received from babysitter process");
543 close_socket_to_babysitter (DBusBabysitter *sitter)
545 _dbus_verbose ("Closing babysitter\n");
547 if (sitter->sitter_watch != NULL)
549 _dbus_assert (sitter->watches != NULL);
550 _dbus_watch_list_remove_watch (sitter->watches, sitter->sitter_watch);
551 _dbus_watch_invalidate (sitter->sitter_watch);
552 _dbus_watch_unref (sitter->sitter_watch);
553 sitter->sitter_watch = NULL;
556 if (sitter->socket_to_babysitter.fd >= 0)
558 _dbus_close_socket (sitter->socket_to_babysitter, NULL);
559 sitter->socket_to_babysitter.fd = -1;
564 close_error_pipe_from_child (DBusBabysitter *sitter)
566 _dbus_verbose ("Closing child error\n");
568 if (sitter->error_watch != NULL)
570 _dbus_assert (sitter->watches != NULL);
571 _dbus_watch_list_remove_watch (sitter->watches, sitter->error_watch);
572 _dbus_watch_invalidate (sitter->error_watch);
573 _dbus_watch_unref (sitter->error_watch);
574 sitter->error_watch = NULL;
577 if (sitter->error_pipe_from_child >= 0)
579 _dbus_close (sitter->error_pipe_from_child, NULL);
580 sitter->error_pipe_from_child = -1;
585 handle_babysitter_socket (DBusBabysitter *sitter,
588 /* Even if we have POLLHUP, we want to keep reading
589 * data until POLLIN goes away; so this function only
590 * looks at HUP/ERR if no IN is set.
592 if (revents & _DBUS_POLLIN)
594 _dbus_verbose ("Reading data from babysitter\n");
595 if (read_data (sitter, sitter->socket_to_babysitter.fd) != READ_STATUS_OK)
596 close_socket_to_babysitter (sitter);
598 else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
600 close_socket_to_babysitter (sitter);
605 handle_error_pipe (DBusBabysitter *sitter,
608 if (revents & _DBUS_POLLIN)
610 _dbus_verbose ("Reading data from child error\n");
611 if (read_data (sitter, sitter->error_pipe_from_child) != READ_STATUS_OK)
612 close_error_pipe_from_child (sitter);
614 else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
616 close_error_pipe_from_child (sitter);
620 /* returns whether there were any poll events handled */
622 babysitter_iteration (DBusBabysitter *sitter,
627 dbus_bool_t descriptors_ready;
629 descriptors_ready = FALSE;
633 if (sitter->error_pipe_from_child >= 0)
635 fds[i].fd = sitter->error_pipe_from_child;
636 fds[i].events = _DBUS_POLLIN;
641 if (sitter->socket_to_babysitter.fd >= 0)
643 fds[i].fd = sitter->socket_to_babysitter.fd;
644 fds[i].events = _DBUS_POLLIN;
655 ret = _dbus_poll (fds, i, 0);
657 while (ret < 0 && errno == EINTR);
659 if (ret == 0 && block)
663 ret = _dbus_poll (fds, i, -1);
665 while (ret < 0 && errno == EINTR);
670 descriptors_ready = TRUE;
675 if (fds[i].fd == sitter->error_pipe_from_child)
676 handle_error_pipe (sitter, fds[i].revents);
677 else if (fds[i].fd == sitter->socket_to_babysitter.fd)
678 handle_babysitter_socket (sitter, fds[i].revents);
683 return descriptors_ready;
687 * Macro returns #TRUE if the babysitter still has live sockets open to the
688 * babysitter child or the grandchild.
690 #define LIVE_CHILDREN(sitter) ((sitter)->socket_to_babysitter.fd >= 0 || (sitter)->error_pipe_from_child >= 0)
693 * Blocks until the babysitter process gives us the PID of the spawned grandchild,
694 * then kills the spawned grandchild.
696 * @param sitter the babysitter object
699 _dbus_babysitter_kill_child (DBusBabysitter *sitter)
701 /* be sure we have the PID of the child */
702 while (LIVE_CHILDREN (sitter) &&
703 sitter->grandchild_pid == -1)
704 babysitter_iteration (sitter, TRUE);
706 _dbus_verbose ("Got child PID %ld for killing\n",
707 (long) sitter->grandchild_pid);
709 if (sitter->grandchild_pid == -1)
710 return; /* child is already dead, or we're so hosed we'll never recover */
712 kill (sitter->grandchild_pid, SIGKILL);
716 * Checks whether the child has exited, without blocking.
718 * @param sitter the babysitter
721 _dbus_babysitter_get_child_exited (DBusBabysitter *sitter)
724 /* Be sure we're up-to-date */
725 while (LIVE_CHILDREN (sitter) &&
726 babysitter_iteration (sitter, FALSE))
729 /* We will have exited the babysitter when the child has exited */
730 return sitter->socket_to_babysitter.fd < 0;
734 * Gets the exit status of the child. We do this so implementation specific
735 * detail is not cluttering up dbus, for example the system launcher code.
736 * This can only be called if the child has exited, i.e. call
737 * _dbus_babysitter_get_child_exited(). It returns FALSE if the child
738 * did not return a status code, e.g. because the child was signaled
739 * or we failed to ever launch the child in the first place.
741 * @param sitter the babysitter
742 * @param status the returned status code
743 * @returns #FALSE on failure
746 _dbus_babysitter_get_child_exit_status (DBusBabysitter *sitter,
749 if (!_dbus_babysitter_get_child_exited (sitter))
750 _dbus_assert_not_reached ("Child has not exited");
752 if (!sitter->have_child_status ||
753 !(WIFEXITED (sitter->status)))
756 *status = WEXITSTATUS (sitter->status);
761 * Sets the #DBusError with an explanation of why the spawned
762 * child process exited (on a signal, or whatever). If
763 * the child process has not exited, does nothing (error
764 * will remain unset).
766 * @param sitter the babysitter
767 * @param error an error to fill in
770 _dbus_babysitter_set_child_exit_error (DBusBabysitter *sitter,
773 if (!_dbus_babysitter_get_child_exited (sitter))
776 /* Note that if exec fails, we will also get a child status
777 * from the babysitter saying the child exited,
778 * so we need to give priority to the exec error
780 if (sitter->have_exec_errnum)
782 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
783 "Failed to execute program %s: %s",
784 sitter->log_name, _dbus_strerror (sitter->errnum));
786 else if (sitter->have_fork_errnum)
788 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
789 "Failed to fork a new process %s: %s",
790 sitter->log_name, _dbus_strerror (sitter->errnum));
792 else if (sitter->have_child_status)
794 if (WIFEXITED (sitter->status))
795 dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_EXITED,
796 "Process %s exited with status %d",
797 sitter->log_name, WEXITSTATUS (sitter->status));
798 else if (WIFSIGNALED (sitter->status))
799 dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_SIGNALED,
800 "Process %s received signal %d",
801 sitter->log_name, WTERMSIG (sitter->status));
803 dbus_set_error (error, DBUS_ERROR_FAILED,
804 "Process %s exited abnormally",
809 dbus_set_error (error, DBUS_ERROR_FAILED,
810 "Process %s exited, reason unknown",
816 * Sets watch functions to notify us when the
817 * babysitter object needs to read/write file descriptors.
819 * @param sitter the babysitter
820 * @param add_function function to begin monitoring a new descriptor.
821 * @param remove_function function to stop monitoring a descriptor.
822 * @param toggled_function function to notify when the watch is enabled/disabled
823 * @param data data to pass to add_function and remove_function.
824 * @param free_data_function function to be called to free the data.
825 * @returns #FALSE on failure (no memory)
828 _dbus_babysitter_set_watch_functions (DBusBabysitter *sitter,
829 DBusAddWatchFunction add_function,
830 DBusRemoveWatchFunction remove_function,
831 DBusWatchToggledFunction toggled_function,
833 DBusFreeFunction free_data_function)
835 return _dbus_watch_list_set_functions (sitter->watches,
844 handle_watch (DBusWatch *watch,
845 unsigned int condition,
848 DBusBabysitter *sitter = _dbus_babysitter_ref (data);
853 if (condition & DBUS_WATCH_READABLE)
854 revents |= _DBUS_POLLIN;
855 if (condition & DBUS_WATCH_ERROR)
856 revents |= _DBUS_POLLERR;
857 if (condition & DBUS_WATCH_HANGUP)
858 revents |= _DBUS_POLLHUP;
860 fd = dbus_watch_get_socket (watch);
862 if (fd == sitter->error_pipe_from_child)
863 handle_error_pipe (sitter, revents);
864 else if (fd == sitter->socket_to_babysitter.fd)
865 handle_babysitter_socket (sitter, revents);
867 while (LIVE_CHILDREN (sitter) &&
868 babysitter_iteration (sitter, FALSE))
871 /* fd.o #32992: if the handle_* methods closed their sockets, they previously
872 * didn't always remove the watches. Check that we don't regress. */
873 _dbus_assert (sitter->socket_to_babysitter.fd != -1 || sitter->sitter_watch == NULL);
874 _dbus_assert (sitter->error_pipe_from_child != -1 || sitter->error_watch == NULL);
876 if (_dbus_babysitter_get_child_exited (sitter) &&
877 sitter->finished_cb != NULL)
879 sitter->finished_cb (sitter, sitter->finished_data);
880 sitter->finished_cb = NULL;
883 _dbus_babysitter_unref (sitter);
887 /** Helps remember which end of the pipe is which */
889 /** Helps remember which end of the pipe is which */
893 /* Avoids a danger in re-entrant situations (calling close()
894 * on a file descriptor twice, and another module has
895 * re-opened it since the first close).
897 * This previously claimed to be relevant for threaded situations, but by
898 * trivial inspection, it is not thread-safe. It doesn't actually
899 * matter, since this module is only used in the -util variant of the
900 * library, which is only used in single-threaded situations.
903 close_and_invalidate (int *fd)
911 ret = _dbus_close (*fd, NULL);
925 dbus_bool_t cloexec_done;
927 retval = pipe2 (p, O_CLOEXEC);
928 cloexec_done = retval >= 0;
930 /* Check if kernel seems to be too old to know pipe2(). We assume
931 that if pipe2 is available, O_CLOEXEC is too. */
932 if (retval < 0 && errno == ENOSYS)
938 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
942 dbus_set_error (error,
943 DBUS_ERROR_SPAWN_FAILED,
944 "Failed to create pipe for communicating with child process (%s)",
945 _dbus_strerror (errno));
953 _dbus_fd_set_close_on_exec (p[0]);
954 _dbus_fd_set_close_on_exec (p[1]);
961 do_write (int fd, const void *buf, size_t count)
963 size_t bytes_written;
970 ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
978 _dbus_warn ("Failed to write data to pipe!");
979 exit (1); /* give up, we suck */
983 bytes_written += ret;
985 if (bytes_written < count)
989 static void write_err_and_exit (int fd, int msg) _DBUS_GNUC_NORETURN;
992 write_err_and_exit (int fd, int msg)
996 do_write (fd, &msg, sizeof (msg));
997 do_write (fd, &en, sizeof (en));
1003 write_pid (int fd, pid_t pid)
1005 int msg = CHILD_PID;
1007 do_write (fd, &msg, sizeof (msg));
1008 do_write (fd, &pid, sizeof (pid));
1011 static void write_status_and_exit (int fd, int status) _DBUS_GNUC_NORETURN;
1014 write_status_and_exit (int fd, int status)
1016 int msg = CHILD_EXITED;
1018 do_write (fd, &msg, sizeof (msg));
1019 do_write (fd, &status, sizeof (status));
1024 static void do_exec (int child_err_report_fd,
1027 DBusSpawnChildSetupFunc child_setup,
1028 void *user_data) _DBUS_GNUC_NORETURN;
1031 do_exec (int child_err_report_fd,
1034 DBusSpawnChildSetupFunc child_setup,
1037 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
1041 _dbus_verbose_reset ();
1042 _dbus_verbose ("Child process has PID " DBUS_PID_FORMAT "\n",
1046 (* child_setup) (user_data);
1048 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
1049 max_open = sysconf (_SC_OPEN_MAX);
1051 for (i = 3; i < max_open; i++)
1055 if (i == child_err_report_fd)
1058 retval = fcntl (i, F_GETFD);
1060 if (retval != -1 && !(retval & FD_CLOEXEC))
1061 _dbus_warn ("Fd %d did not have the close-on-exec flag set!", i);
1067 _dbus_assert (environ != NULL);
1072 execve (argv[0], argv, envp);
1075 write_err_and_exit (child_err_report_fd,
1080 check_babysit_events (pid_t grandchild_pid,
1089 ret = waitpid (grandchild_pid, &status, WNOHANG);
1090 /* The man page says EINTR can't happen with WNOHANG,
1091 * but there are reports of it (maybe only with valgrind?)
1094 while (ret < 0 && errno == EINTR);
1098 _dbus_verbose ("no child exited\n");
1100 ; /* no child exited */
1104 /* This isn't supposed to happen. */
1105 _dbus_warn ("unexpected waitpid() failure in check_babysit_events(): %s",
1106 _dbus_strerror (errno));
1109 else if (ret == grandchild_pid)
1112 _dbus_verbose ("reaped child pid %ld\n", (long) ret);
1114 write_status_and_exit (parent_pipe, status);
1118 _dbus_warn ("waitpid() reaped pid %d that we've never heard of",
1123 if (revents & _DBUS_POLLIN)
1125 _dbus_verbose ("babysitter got POLLIN from parent pipe\n");
1128 if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
1130 /* Parent is gone, so we just exit */
1131 _dbus_verbose ("babysitter got POLLERR or POLLHUP from parent\n");
1136 static int babysit_sigchld_pipe = -1;
1139 babysit_signal_handler (int signo)
1141 /* Signal handlers that might set errno must save and restore the errno
1142 * that the interrupted function might have been relying on. */
1143 int saved_errno = errno;
1147 if (write (babysit_sigchld_pipe, &b, 1) <= 0)
1151 errno = saved_errno;
1154 static void babysit (pid_t grandchild_pid,
1155 int parent_pipe) _DBUS_GNUC_NORETURN;
1158 babysit (pid_t grandchild_pid,
1161 int sigchld_pipe[2];
1163 /* We don't exec, so we keep parent state, such as the pid that
1164 * _dbus_verbose() uses. Reset the pid here.
1166 _dbus_verbose_reset ();
1168 /* I thought SIGCHLD would just wake up the poll, but
1169 * that didn't seem to work, so added this pipe.
1170 * Probably the pipe is more likely to work on busted
1171 * operating systems anyhow.
1173 if (pipe (sigchld_pipe) < 0)
1175 _dbus_warn ("Not enough file descriptors to create pipe in babysitter process");
1179 babysit_sigchld_pipe = sigchld_pipe[WRITE_END];
1181 _dbus_set_signal_handler (SIGCHLD, babysit_signal_handler);
1183 write_pid (parent_pipe, grandchild_pid);
1185 check_babysit_events (grandchild_pid, parent_pipe, 0);
1191 pfds[0].fd = parent_pipe;
1192 pfds[0].events = _DBUS_POLLIN;
1193 pfds[0].revents = 0;
1195 pfds[1].fd = sigchld_pipe[READ_END];
1196 pfds[1].events = _DBUS_POLLIN;
1197 pfds[1].revents = 0;
1199 if (_dbus_poll (pfds, _DBUS_N_ELEMENTS (pfds), -1) < 0 && errno != EINTR)
1201 _dbus_warn ("_dbus_poll() error: %s", strerror (errno));
1205 if (pfds[0].revents != 0)
1207 check_babysit_events (grandchild_pid, parent_pipe, pfds[0].revents);
1209 else if (pfds[1].revents & _DBUS_POLLIN)
1212 if (read (sigchld_pipe[READ_END], &b, 1) == -1)
1216 /* do waitpid check */
1217 check_babysit_events (grandchild_pid, parent_pipe, 0);
1225 * Spawns a new process.
1227 * On Unix platforms, the child_setup function is passed the given
1228 * user_data and is run in the child after fork() but before calling exec().
1229 * This can be used to change uid, resource limits and so on.
1230 * On Windows, this functionality does not fit the multi-processing model
1231 * (Windows does the equivalent of fork() and exec() in a single API call),
1232 * and the child_setup function and its user_data are ignored.
1234 * Also creates a "babysitter" which tracks the status of the
1235 * child process, advising the parent if the child exits.
1236 * If the spawn fails, no babysitter is created.
1237 * If sitter_p is #NULL, no babysitter is kept.
1239 * @param sitter_p return location for babysitter or #NULL
1240 * @param log_name the name under which to log messages about this process being spawned
1241 * @param argv the executable and arguments
1242 * @param env the environment, or #NULL to copy the parent's
1243 * @param child_setup function to call in child pre-exec()
1244 * @param user_data user data for setup function
1245 * @param error error object to be filled in if function fails
1246 * @returns #TRUE on success, #FALSE if error is filled in
1249 _dbus_spawn_async_with_babysitter (DBusBabysitter **sitter_p,
1250 const char *log_name,
1253 DBusSpawnFlags flags,
1254 DBusSpawnChildSetupFunc child_setup,
1258 DBusBabysitter *sitter;
1259 int child_err_report_pipe[2] = { -1, -1 };
1260 DBusSocket babysitter_pipe[2] = { DBUS_SOCKET_INIT, DBUS_SOCKET_INIT };
1267 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1268 _dbus_assert (argv[0] != NULL);
1270 if (sitter_p != NULL)
1275 sitter = _dbus_babysitter_new ();
1278 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1282 sitter->log_name = _dbus_strdup (log_name);
1283 if (sitter->log_name == NULL && log_name != NULL)
1285 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1286 goto cleanup_and_fail;
1289 if (sitter->log_name == NULL)
1290 sitter->log_name = _dbus_strdup (argv[0]);
1292 if (sitter->log_name == NULL)
1294 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1295 goto cleanup_and_fail;
1298 if (!make_pipe (child_err_report_pipe, error))
1299 goto cleanup_and_fail;
1301 if (!_dbus_socketpair (&babysitter_pipe[0], &babysitter_pipe[1], TRUE, error))
1302 goto cleanup_and_fail;
1304 /* Setting up the babysitter is only useful in the parent,
1305 * but we don't want to run out of memory and fail
1306 * after we've already forked, since then we'd leak
1307 * child processes everywhere.
1309 sitter->error_watch = _dbus_watch_new (child_err_report_pipe[READ_END],
1310 DBUS_WATCH_READABLE,
1311 TRUE, handle_watch, sitter, NULL);
1312 if (sitter->error_watch == NULL)
1314 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1315 goto cleanup_and_fail;
1318 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->error_watch))
1320 /* we need to free it early so the destructor won't try to remove it
1321 * without it having been added, which DBusLoop doesn't allow */
1322 _dbus_watch_invalidate (sitter->error_watch);
1323 _dbus_watch_unref (sitter->error_watch);
1324 sitter->error_watch = NULL;
1326 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1327 goto cleanup_and_fail;
1330 sitter->sitter_watch = _dbus_watch_new (babysitter_pipe[0].fd,
1331 DBUS_WATCH_READABLE,
1332 TRUE, handle_watch, sitter, NULL);
1333 if (sitter->sitter_watch == NULL)
1335 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1336 goto cleanup_and_fail;
1339 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->sitter_watch))
1341 /* we need to free it early so the destructor won't try to remove it
1342 * without it having been added, which DBusLoop doesn't allow */
1343 _dbus_watch_invalidate (sitter->sitter_watch);
1344 _dbus_watch_unref (sitter->sitter_watch);
1345 sitter->sitter_watch = NULL;
1347 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1348 goto cleanup_and_fail;
1351 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1354 if (flags & DBUS_SPAWN_REDIRECT_OUTPUT)
1356 /* This may fail, but it's not critical.
1357 * In particular, if we were compiled with journald support but are now
1358 * running on a non-systemd system, this is going to fail, so we
1359 * have to cope gracefully. */
1360 fd_out = sd_journal_stream_fd (sitter->log_name, LOG_INFO, FALSE);
1361 fd_err = sd_journal_stream_fd (sitter->log_name, LOG_WARNING, FALSE);
1369 dbus_set_error (error,
1370 DBUS_ERROR_SPAWN_FORK_FAILED,
1371 "Failed to fork (%s)",
1372 _dbus_strerror (errno));
1373 goto cleanup_and_fail;
1377 /* Immediate child, this is the babysitter process. */
1380 /* Be sure we crash if the parent exits
1381 * and we write to the err_report_pipe
1383 signal (SIGPIPE, SIG_DFL);
1385 /* Close the parent's end of the pipes. */
1386 close_and_invalidate (&child_err_report_pipe[READ_END]);
1387 close_and_invalidate (&babysitter_pipe[0].fd);
1389 /* Create the child that will exec () */
1390 grandchild_pid = fork ();
1392 if (grandchild_pid < 0)
1394 write_err_and_exit (babysitter_pipe[1].fd,
1396 _dbus_assert_not_reached ("Got to code after write_err_and_exit()");
1398 else if (grandchild_pid == 0)
1404 fd = open ("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
1409 fd = open ("/proc/self/oom_score_adj", O_WRONLY);
1410 _dbus_fd_set_close_on_exec (fd);
1415 if (write (fd, "0", sizeof (char)) < 0)
1416 _dbus_warn ("writing oom_score_adj error: %s", strerror (errno));
1417 _dbus_close (fd, NULL);
1420 /* Go back to ignoring SIGPIPE, since it's evil
1422 signal (SIGPIPE, SIG_IGN);
1424 close_and_invalidate (&babysitter_pipe[1].fd);
1426 /* log to systemd journal if possible */
1428 dup2 (fd_out, STDOUT_FILENO);
1430 dup2 (fd_err, STDERR_FILENO);
1431 close_and_invalidate (&fd_out);
1432 close_and_invalidate (&fd_err);
1434 do_exec (child_err_report_pipe[WRITE_END],
1437 child_setup, user_data);
1438 _dbus_assert_not_reached ("Got to code after exec() - should have exited on error");
1442 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1444 close_and_invalidate (&fd_out);
1445 close_and_invalidate (&fd_err);
1447 babysit (grandchild_pid, babysitter_pipe[1].fd);
1448 _dbus_assert_not_reached ("Got to code after babysit()");
1453 /* Close the uncared-about ends of the pipes */
1454 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1455 close_and_invalidate (&babysitter_pipe[1].fd);
1457 close_and_invalidate (&fd_out);
1458 close_and_invalidate (&fd_err);
1461 sitter->socket_to_babysitter = babysitter_pipe[0];
1462 babysitter_pipe[0].fd = -1;
1464 sitter->error_pipe_from_child = child_err_report_pipe[READ_END];
1465 child_err_report_pipe[READ_END] = -1;
1467 sitter->sitter_pid = pid;
1469 if (sitter_p != NULL)
1472 _dbus_babysitter_unref (sitter);
1474 dbus_free_string_array (env);
1476 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1483 _DBUS_ASSERT_ERROR_IS_SET (error);
1485 close_and_invalidate (&child_err_report_pipe[READ_END]);
1486 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1487 close_and_invalidate (&babysitter_pipe[0].fd);
1488 close_and_invalidate (&babysitter_pipe[1].fd);
1490 close_and_invalidate (&fd_out);
1491 close_and_invalidate (&fd_err);
1495 _dbus_babysitter_unref (sitter);
1501 _dbus_babysitter_set_result_function (DBusBabysitter *sitter,
1502 DBusBabysitterFinishedFunc finished,
1505 sitter->finished_cb = finished;
1506 sitter->finished_data = user_data;
1512 _dbus_babysitter_block_for_child_exit (DBusBabysitter *sitter)
1514 while (LIVE_CHILDREN (sitter))
1515 babysitter_iteration (sitter, TRUE);