2 * Copyright (c) 2008, 2009, 2010 Nicira Networks.
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.
29 #include "dynamic-string.h"
30 #include "fatal-signal.h"
32 #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. */
85 ovs_fatal(errno, "could not create pipe");
87 set_nonblocking(fds[0]);
88 set_nonblocking(fds[1]);
90 /* Set up child termination signal handler. */
91 memset(&sa, 0, sizeof sa);
92 sa.sa_handler = sigchld_handler;
93 sigemptyset(&sa.sa_mask);
94 sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
95 if (sigaction(SIGCHLD, &sa, NULL)) {
96 ovs_fatal(errno, "sigaction(SIGCHLD) failed");
101 process_escape_args(char **argv)
103 struct ds ds = DS_EMPTY_INITIALIZER;
105 for (argp = argv; *argp; argp++) {
106 const char *arg = *argp;
109 ds_put_char(&ds, ' ');
111 if (arg[strcspn(arg, " \t\r\n\v\\\'\"")]) {
112 ds_put_char(&ds, '"');
113 for (p = arg; *p; p++) {
114 if (*p == '\\' || *p == '\"') {
115 ds_put_char(&ds, '\\');
117 ds_put_char(&ds, *p);
119 ds_put_char(&ds, '"');
121 ds_put_cstr(&ds, arg);
127 /* Prepare to start a process whose command-line arguments are given by the
128 * null-terminated 'argv' array. Returns 0 if successful, otherwise a
129 * positive errno value. */
131 process_prestart(char **argv)
137 /* Log the process to be started. */
138 if (VLOG_IS_DBG_ENABLED()) {
139 char *args = process_escape_args(argv);
140 VLOG_DBG("starting subprocess: %s", args);
144 /* execvp() will search PATH too, but the error in that case is more
145 * obscure, since it is only reported post-fork. */
146 binary = process_search_path(argv[0]);
148 VLOG_ERR("%s not found in PATH", argv[0]);
156 /* Creates and returns a new struct process with the specified 'name' and
159 * This is racy unless SIGCHLD is blocked (and has been blocked since before
160 * the fork()) that created the subprocess. */
161 static struct process *
162 process_register(const char *name, pid_t pid)
167 assert(sigchld_is_blocked());
169 p = xzalloc(sizeof *p);
171 slash = strrchr(name, '/');
172 p->name = xstrdup(slash ? slash + 1 : name);
175 list_push_back(&all_processes, &p->node);
180 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
181 * argv[0] is used as the name of the process. Searches the PATH environment
182 * variable to find the program to execute.
184 * All file descriptors are closed before executing the subprocess, except for
185 * fds 0, 1, and 2 and the 'n_keep_fds' fds listed in 'keep_fds'. Also, any of
186 * the 'n_null_fds' fds listed in 'null_fds' are replaced by /dev/null.
188 * Returns 0 if successful, otherwise a positive errno value indicating the
189 * error. If successful, '*pp' is assigned a new struct process that may be
190 * used to query the process's status. On failure, '*pp' is set to NULL. */
192 process_start(char **argv,
193 const int keep_fds[], size_t n_keep_fds,
194 const int null_fds[], size_t n_null_fds,
202 COVERAGE_INC(process_start);
203 error = process_prestart(argv);
208 block_sigchld(&oldsigs);
211 unblock_sigchld(&oldsigs);
212 VLOG_WARN("fork failed: %s", strerror(errno));
215 /* Running in parent process. */
216 *pp = process_register(argv[0], pid);
217 unblock_sigchld(&oldsigs);
220 /* Running in child process. */
221 int fd_max = get_max_fds();
225 unblock_sigchld(&oldsigs);
226 for (fd = 0; fd < fd_max; fd++) {
227 if (is_member(fd, null_fds, n_null_fds)) {
228 /* We can't use get_null_fd() here because we might have
229 * already closed its fd. */
230 int nullfd = open("/dev/null", O_RDWR);
233 } else if (fd >= 3 && !is_member(fd, keep_fds, n_keep_fds)) {
237 execvp(argv[0], argv);
238 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
239 argv[0], strerror(errno));
244 /* Destroys process 'p'. */
246 process_destroy(struct process *p)
251 block_sigchld(&oldsigs);
252 list_remove(&p->node);
253 unblock_sigchld(&oldsigs);
260 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
261 * positive errno value. */
263 process_kill(const struct process *p, int signr)
265 return (p->exited ? ESRCH
266 : !kill(p->pid, signr) ? 0
270 /* Returns the pid of process 'p'. */
272 process_pid(const struct process *p)
277 /* Returns the name of process 'p' (the name passed to process_start() with any
278 * leading directories stripped). */
280 process_name(const struct process *p)
285 /* Returns true if process 'p' has exited, false otherwise. */
287 process_exited(struct process *p)
292 char buf[_POSIX_PIPE_BUF];
293 ignore(read(fds[0], buf, sizeof buf));
298 /* Returns process 'p''s exit status, as reported by waitpid(2).
299 * process_status(p) may be called only after process_exited(p) has returned
302 process_status(const struct process *p)
309 process_run(char **argv,
310 const int keep_fds[], size_t n_keep_fds,
311 const int null_fds[], size_t n_null_fds,
317 COVERAGE_INC(process_run);
318 retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
325 while (!process_exited(p)) {
329 *status = process_status(p);
334 /* Given 'status', which is a process status in the form reported by waitpid(2)
335 * and returned by process_status(), returns a string describing how the
336 * process terminated. The caller is responsible for freeing the string when
337 * it is no longer needed. */
339 process_status_msg(int status)
341 struct ds ds = DS_EMPTY_INITIALIZER;
342 if (WIFEXITED(status)) {
343 ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
344 } else if (WIFSIGNALED(status) || WIFSTOPPED(status)) {
345 int signr = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
346 const char *name = NULL;
347 #ifdef HAVE_STRSIGNAL
348 name = strsignal(signr);
350 ds_put_format(&ds, "%s by signal %d",
351 WIFSIGNALED(status) ? "killed" : "stopped", signr);
353 ds_put_format(&ds, " (%s)", name);
356 ds_put_format(&ds, "terminated abnormally (%x)", status);
358 if (WCOREDUMP(status)) {
359 ds_put_cstr(&ds, ", core dumped");
364 /* Causes the next call to poll_block() to wake up when process 'p' has
367 process_wait(struct process *p)
370 poll_immediate_wake();
372 poll_fd_wait(fds[0], POLLIN);
377 process_search_path(const char *name)
379 char *save_ptr = NULL;
383 if (strchr(name, '/') || !getenv("PATH")) {
384 return stat(name, &s) == 0 ? xstrdup(name) : NULL;
387 path = xstrdup(getenv("PATH"));
388 for (dir = strtok_r(path, ":", &save_ptr); dir;
389 dir = strtok_r(NULL, ":", &save_ptr)) {
390 char *file = xasprintf("%s/%s", dir, name);
391 if (stat(file, &s) == 0) {
401 /* process_run_capture() and supporting functions. */
409 stream_open(struct stream *s)
413 VLOG_WARN("failed to create pipe: %s", strerror(errno));
416 set_nonblocking(s->fds[0]);
421 stream_read(struct stream *s)
432 error = read_fully(s->fds[0], buffer, sizeof buffer, &n);
433 ds_put_buffer(&s->log, buffer, n);
435 if (error == EAGAIN || error == EWOULDBLOCK) {
439 VLOG_WARN("error reading subprocess pipe: %s",
444 } else if (s->log.length > PROCESS_MAX_CAPTURE) {
445 VLOG_WARN("subprocess output overflowed %d-byte buffer",
446 PROCESS_MAX_CAPTURE);
455 stream_wait(struct stream *s)
457 if (s->fds[0] >= 0) {
458 poll_fd_wait(s->fds[0], POLLIN);
463 stream_close(struct stream *s)
466 if (s->fds[0] >= 0) {
469 if (s->fds[1] >= 0) {
474 /* Starts the process whose arguments are given in the null-terminated array
475 * 'argv' and waits for it to exit. On success returns 0 and stores the
476 * process exit value (suitable for passing to process_status_msg()) in
477 * '*status'. On failure, returns a positive errno value and stores 0 in
480 * If 'stdout_log' is nonnull, then the subprocess's output to stdout (up to a
481 * limit of PROCESS_MAX_CAPTURE bytes) is captured in a memory buffer, which
482 * when this function returns 0 is stored as a null-terminated string in
483 * '*stdout_log'. The caller is responsible for freeing '*stdout_log' (by
484 * passing it to free()). When this function returns an error, '*stdout_log'
487 * If 'stderr_log' is nonnull, then it is treated like 'stdout_log' except
488 * that it captures the subprocess's output to stderr. */
490 process_run_capture(char **argv, char **stdout_log, char **stderr_log,
493 struct stream s_stdout, s_stderr;
498 COVERAGE_INC(process_run_capture);
506 error = process_prestart(argv);
511 error = stream_open(&s_stdout);
516 error = stream_open(&s_stderr);
518 stream_close(&s_stdout);
522 block_sigchld(&oldsigs);
527 unblock_sigchld(&oldsigs);
528 VLOG_WARN("fork failed: %s", strerror(error));
530 stream_close(&s_stdout);
531 stream_close(&s_stderr);
535 /* Running in parent process. */
538 p = process_register(argv[0], pid);
539 unblock_sigchld(&oldsigs);
541 close(s_stdout.fds[1]);
542 close(s_stderr.fds[1]);
543 while (!process_exited(p)) {
544 stream_read(&s_stdout);
545 stream_read(&s_stderr);
547 stream_wait(&s_stdout);
548 stream_wait(&s_stderr);
552 stream_read(&s_stdout);
553 stream_read(&s_stderr);
556 *stdout_log = ds_steal_cstr(&s_stdout.log);
559 *stderr_log = ds_steal_cstr(&s_stderr.log);
562 stream_close(&s_stdout);
563 stream_close(&s_stderr);
565 *status = process_status(p);
569 /* Running in child process. */
574 unblock_sigchld(&oldsigs);
576 dup2(get_null_fd(), 0);
577 dup2(s_stdout.fds[1], 1);
578 dup2(s_stderr.fds[1], 2);
580 max_fds = get_max_fds();
581 for (i = 3; i < max_fds; i++) {
585 execvp(argv[0], argv);
586 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
587 argv[0], strerror(errno));
593 sigchld_handler(int signr OVS_UNUSED)
597 COVERAGE_INC(process_sigchld);
598 LIST_FOR_EACH (p, node, &all_processes) {
602 retval = waitpid(p->pid, &status, WNOHANG);
603 } while (retval == -1 && errno == EINTR);
604 if (retval == p->pid) {
607 } else if (retval < 0) {
608 /* XXX We want to log something but we're in a signal
615 ignore(write(fds[1], "", 1));
619 is_member(int x, const int *array, size_t n)
623 for (i = 0; i < n; i++) {
632 sigchld_is_blocked(void)
635 if (sigprocmask(SIG_SETMASK, NULL, &sigs)) {
636 ovs_fatal(errno, "sigprocmask");
638 return sigismember(&sigs, SIGCHLD);
642 block_sigchld(sigset_t *oldsigs)
645 sigemptyset(&sigchld);
646 sigaddset(&sigchld, SIGCHLD);
647 if (sigprocmask(SIG_BLOCK, &sigchld, oldsigs)) {
648 ovs_fatal(errno, "sigprocmask");
653 unblock_sigchld(const sigset_t *oldsigs)
655 if (sigprocmask(SIG_SETMASK, oldsigs, NULL)) {
656 ovs_fatal(errno, "sigprocmask");