2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
28 #include "dynamic-string.h"
29 #include "fatal-signal.h"
31 #include "poll-loop.h"
33 #include "socket-util.h"
37 VLOG_DEFINE_THIS_MODULE(process);
39 COVERAGE_DEFINE(process_run);
40 COVERAGE_DEFINE(process_run_capture);
41 COVERAGE_DEFINE(process_sigchld);
42 COVERAGE_DEFINE(process_start);
49 /* Modified by signal handler. */
54 /* Pipe used to signal child termination. */
58 static struct list all_processes = LIST_INITIALIZER(&all_processes);
60 static bool sigchld_is_blocked(void);
61 static void block_sigchld(sigset_t *);
62 static void unblock_sigchld(const sigset_t *);
63 static void sigchld_handler(int signr OVS_UNUSED);
64 static bool is_member(int x, const int *array, size_t);
66 /* Initializes the process subsystem (if it is not already initialized). Calls
67 * exit() if initialization fails.
69 * Calling this function is optional; it will be called automatically by
70 * process_start() if necessary. Calling it explicitly allows the client to
71 * prevent the process from exiting at an unexpected time. */
83 /* Create notification pipe. */
84 xpipe_nonblocking(fds);
86 /* Set up child termination signal handler. */
87 memset(&sa, 0, sizeof sa);
88 sa.sa_handler = sigchld_handler;
89 sigemptyset(&sa.sa_mask);
90 sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
91 xsigaction(SIGCHLD, &sa, NULL);
95 process_escape_args(char **argv)
97 struct ds ds = DS_EMPTY_INITIALIZER;
99 for (argp = argv; *argp; argp++) {
100 const char *arg = *argp;
103 ds_put_char(&ds, ' ');
105 if (arg[strcspn(arg, " \t\r\n\v\\\'\"")]) {
106 ds_put_char(&ds, '"');
107 for (p = arg; *p; p++) {
108 if (*p == '\\' || *p == '\"') {
109 ds_put_char(&ds, '\\');
111 ds_put_char(&ds, *p);
113 ds_put_char(&ds, '"');
115 ds_put_cstr(&ds, arg);
121 /* Prepare to start a process whose command-line arguments are given by the
122 * null-terminated 'argv' array. Returns 0 if successful, otherwise a
123 * positive errno value. */
125 process_prestart(char **argv)
131 /* Log the process to be started. */
132 if (VLOG_IS_DBG_ENABLED()) {
133 char *args = process_escape_args(argv);
134 VLOG_DBG("starting subprocess: %s", args);
138 /* execvp() will search PATH too, but the error in that case is more
139 * obscure, since it is only reported post-fork. */
140 binary = process_search_path(argv[0]);
142 VLOG_ERR("%s not found in PATH", argv[0]);
150 /* Creates and returns a new struct process with the specified 'name' and
153 * This is racy unless SIGCHLD is blocked (and has been blocked since before
154 * the fork()) that created the subprocess. */
155 static struct process *
156 process_register(const char *name, pid_t pid)
161 ovs_assert(sigchld_is_blocked());
163 p = xzalloc(sizeof *p);
165 slash = strrchr(name, '/');
166 p->name = xstrdup(slash ? slash + 1 : name);
169 list_push_back(&all_processes, &p->node);
174 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
175 * argv[0] is used as the name of the process. Searches the PATH environment
176 * variable to find the program to execute.
178 * All file descriptors are closed before executing the subprocess, except for
179 * fds 0, 1, and 2 and the 'n_keep_fds' fds listed in 'keep_fds'. Also, any of
180 * the 'n_null_fds' fds listed in 'null_fds' are replaced by /dev/null.
182 * Returns 0 if successful, otherwise a positive errno value indicating the
183 * error. If successful, '*pp' is assigned a new struct process that may be
184 * used to query the process's status. On failure, '*pp' is set to NULL. */
186 process_start(char **argv,
187 const int keep_fds[], size_t n_keep_fds,
188 const int null_fds[], size_t n_null_fds,
197 COVERAGE_INC(process_start);
198 error = process_prestart(argv);
204 nullfd = get_null_fd();
212 block_sigchld(&oldsigs);
215 unblock_sigchld(&oldsigs);
216 VLOG_WARN("fork failed: %s", strerror(errno));
219 /* Running in parent process. */
220 *pp = process_register(argv[0], pid);
221 unblock_sigchld(&oldsigs);
224 /* Running in child process. */
225 int fd_max = get_max_fds();
229 unblock_sigchld(&oldsigs);
230 for (fd = 0; fd < fd_max; fd++) {
231 if (is_member(fd, null_fds, n_null_fds)) {
233 } else if (fd >= 3 && fd != nullfd
234 && !is_member(fd, keep_fds, n_keep_fds)) {
239 && !is_member(nullfd, keep_fds, n_keep_fds)
240 && !is_member(nullfd, null_fds, n_null_fds)) {
243 execvp(argv[0], argv);
244 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
245 argv[0], strerror(errno));
250 /* Destroys process 'p'. */
252 process_destroy(struct process *p)
257 block_sigchld(&oldsigs);
258 list_remove(&p->node);
259 unblock_sigchld(&oldsigs);
266 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
267 * positive errno value. */
269 process_kill(const struct process *p, int signr)
271 return (p->exited ? ESRCH
272 : !kill(p->pid, signr) ? 0
276 /* Returns the pid of process 'p'. */
278 process_pid(const struct process *p)
283 /* Returns the name of process 'p' (the name passed to process_start() with any
284 * leading directories stripped). */
286 process_name(const struct process *p)
291 /* Returns true if process 'p' has exited, false otherwise. */
293 process_exited(struct process *p)
298 char buf[_POSIX_PIPE_BUF];
299 ignore(read(fds[0], buf, sizeof buf));
304 /* Returns process 'p''s exit status, as reported by waitpid(2).
305 * process_status(p) may be called only after process_exited(p) has returned
308 process_status(const struct process *p)
310 ovs_assert(p->exited);
315 process_run(char **argv,
316 const int keep_fds[], size_t n_keep_fds,
317 const int null_fds[], size_t n_null_fds,
323 COVERAGE_INC(process_run);
324 retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
331 while (!process_exited(p)) {
335 *status = process_status(p);
340 /* Given 'status', which is a process status in the form reported by waitpid(2)
341 * and returned by process_status(), returns a string describing how the
342 * process terminated. The caller is responsible for freeing the string when
343 * it is no longer needed. */
345 process_status_msg(int status)
347 struct ds ds = DS_EMPTY_INITIALIZER;
348 if (WIFEXITED(status)) {
349 ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
350 } else if (WIFSIGNALED(status)) {
351 char namebuf[SIGNAL_NAME_BUFSIZE];
353 ds_put_format(&ds, "killed (%s)",
354 signal_name(WTERMSIG(status), namebuf, sizeof namebuf));
355 } else if (WIFSTOPPED(status)) {
356 char namebuf[SIGNAL_NAME_BUFSIZE];
358 ds_put_format(&ds, "stopped (%s)",
359 signal_name(WSTOPSIG(status), namebuf, sizeof namebuf));
361 ds_put_format(&ds, "terminated abnormally (%x)", status);
363 if (WCOREDUMP(status)) {
364 ds_put_cstr(&ds, ", core dumped");
369 /* Causes the next call to poll_block() to wake up when process 'p' has
372 process_wait(struct process *p)
375 poll_immediate_wake();
377 poll_fd_wait(fds[0], POLLIN);
382 process_search_path(const char *name)
384 char *save_ptr = NULL;
388 if (strchr(name, '/') || !getenv("PATH")) {
389 return stat(name, &s) == 0 ? xstrdup(name) : NULL;
392 path = xstrdup(getenv("PATH"));
393 for (dir = strtok_r(path, ":", &save_ptr); dir;
394 dir = strtok_r(NULL, ":", &save_ptr)) {
395 char *file = xasprintf("%s/%s", dir, name);
396 if (stat(file, &s) == 0) {
406 /* process_run_capture() and supporting functions. */
415 stream_open(struct stream *s, size_t max_size)
419 s->max_size = max_size;
422 VLOG_WARN("failed to create pipe: %s", strerror(errno));
425 error = set_nonblocking(s->fds[0]);
434 stream_read(struct stream *s)
445 error = read_fully(s->fds[0], buffer, sizeof buffer, &n);
446 ds_put_buffer(&s->log, buffer, n);
448 if (error == EAGAIN || error == EWOULDBLOCK) {
452 VLOG_WARN("error reading subprocess pipe: %s",
457 } else if (s->log.length > s->max_size) {
458 VLOG_WARN("subprocess output overflowed %zu-byte buffer",
468 stream_wait(struct stream *s)
470 if (s->fds[0] >= 0) {
471 poll_fd_wait(s->fds[0], POLLIN);
476 stream_close(struct stream *s)
479 if (s->fds[0] >= 0) {
482 if (s->fds[1] >= 0) {
487 /* Starts the process whose arguments are given in the null-terminated array
488 * 'argv' and waits for it to exit. On success returns 0 and stores the
489 * process exit value (suitable for passing to process_status_msg()) in
490 * '*status'. On failure, returns a positive errno value and stores 0 in
493 * If 'stdout_log' is nonnull, then the subprocess's output to stdout (up to a
494 * limit of 'log_max' bytes) is captured in a memory buffer, which
495 * when this function returns 0 is stored as a null-terminated string in
496 * '*stdout_log'. The caller is responsible for freeing '*stdout_log' (by
497 * passing it to free()). When this function returns an error, '*stdout_log'
500 * If 'stderr_log' is nonnull, then it is treated like 'stdout_log' except
501 * that it captures the subprocess's output to stderr. */
503 process_run_capture(char **argv, char **stdout_log, char **stderr_log,
504 size_t max_log, int *status)
506 struct stream s_stdout, s_stderr;
511 COVERAGE_INC(process_run_capture);
519 error = process_prestart(argv);
524 error = stream_open(&s_stdout, max_log);
529 error = stream_open(&s_stderr, max_log);
531 stream_close(&s_stdout);
535 block_sigchld(&oldsigs);
540 unblock_sigchld(&oldsigs);
541 VLOG_WARN("fork failed: %s", strerror(error));
543 stream_close(&s_stdout);
544 stream_close(&s_stderr);
548 /* Running in parent process. */
551 p = process_register(argv[0], pid);
552 unblock_sigchld(&oldsigs);
554 close(s_stdout.fds[1]);
555 close(s_stderr.fds[1]);
556 while (!process_exited(p)) {
557 stream_read(&s_stdout);
558 stream_read(&s_stderr);
560 stream_wait(&s_stdout);
561 stream_wait(&s_stderr);
565 stream_read(&s_stdout);
566 stream_read(&s_stderr);
569 *stdout_log = ds_steal_cstr(&s_stdout.log);
572 *stderr_log = ds_steal_cstr(&s_stderr.log);
575 stream_close(&s_stdout);
576 stream_close(&s_stderr);
578 *status = process_status(p);
582 /* Running in child process. */
587 unblock_sigchld(&oldsigs);
589 dup2(get_null_fd(), 0);
590 dup2(s_stdout.fds[1], 1);
591 dup2(s_stderr.fds[1], 2);
593 max_fds = get_max_fds();
594 for (i = 3; i < max_fds; i++) {
598 execvp(argv[0], argv);
599 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
600 argv[0], strerror(errno));
606 sigchld_handler(int signr OVS_UNUSED)
610 COVERAGE_INC(process_sigchld);
611 LIST_FOR_EACH (p, node, &all_processes) {
615 retval = waitpid(p->pid, &status, WNOHANG);
616 } while (retval == -1 && errno == EINTR);
617 if (retval == p->pid) {
620 } else if (retval < 0) {
621 /* XXX We want to log something but we're in a signal
628 ignore(write(fds[1], "", 1));
632 is_member(int x, const int *array, size_t n)
636 for (i = 0; i < n; i++) {
645 sigchld_is_blocked(void)
649 xpthread_sigmask(SIG_SETMASK, NULL, &sigs);
650 return sigismember(&sigs, SIGCHLD);
654 block_sigchld(sigset_t *oldsigs)
658 sigemptyset(&sigchld);
659 sigaddset(&sigchld, SIGCHLD);
660 xpthread_sigmask(SIG_BLOCK, &sigchld, oldsigs);
664 unblock_sigchld(const sigset_t *oldsigs)
666 xpthread_sigmask(SIG_SETMASK, oldsigs, NULL);