2 * Copyright (c) 2008, 2009, 2010, 2011 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,
203 COVERAGE_INC(process_start);
204 error = process_prestart(argv);
210 nullfd = get_null_fd();
218 block_sigchld(&oldsigs);
221 unblock_sigchld(&oldsigs);
222 VLOG_WARN("fork failed: %s", strerror(errno));
225 /* Running in parent process. */
226 *pp = process_register(argv[0], pid);
227 unblock_sigchld(&oldsigs);
230 /* Running in child process. */
231 int fd_max = get_max_fds();
235 unblock_sigchld(&oldsigs);
236 for (fd = 0; fd < fd_max; fd++) {
237 if (is_member(fd, null_fds, n_null_fds)) {
239 } else if (fd >= 3 && fd != nullfd
240 && !is_member(fd, keep_fds, n_keep_fds)) {
245 && !is_member(nullfd, keep_fds, n_keep_fds)
246 && !is_member(nullfd, null_fds, n_null_fds)) {
249 execvp(argv[0], argv);
250 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
251 argv[0], strerror(errno));
256 /* Destroys process 'p'. */
258 process_destroy(struct process *p)
263 block_sigchld(&oldsigs);
264 list_remove(&p->node);
265 unblock_sigchld(&oldsigs);
272 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
273 * positive errno value. */
275 process_kill(const struct process *p, int signr)
277 return (p->exited ? ESRCH
278 : !kill(p->pid, signr) ? 0
282 /* Returns the pid of process 'p'. */
284 process_pid(const struct process *p)
289 /* Returns the name of process 'p' (the name passed to process_start() with any
290 * leading directories stripped). */
292 process_name(const struct process *p)
297 /* Returns true if process 'p' has exited, false otherwise. */
299 process_exited(struct process *p)
304 char buf[_POSIX_PIPE_BUF];
305 ignore(read(fds[0], buf, sizeof buf));
310 /* Returns process 'p''s exit status, as reported by waitpid(2).
311 * process_status(p) may be called only after process_exited(p) has returned
314 process_status(const struct process *p)
321 process_run(char **argv,
322 const int keep_fds[], size_t n_keep_fds,
323 const int null_fds[], size_t n_null_fds,
329 COVERAGE_INC(process_run);
330 retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
337 while (!process_exited(p)) {
341 *status = process_status(p);
346 /* Given 'status', which is a process status in the form reported by waitpid(2)
347 * and returned by process_status(), returns a string describing how the
348 * process terminated. The caller is responsible for freeing the string when
349 * it is no longer needed. */
351 process_status_msg(int status)
353 struct ds ds = DS_EMPTY_INITIALIZER;
354 if (WIFEXITED(status)) {
355 ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
356 } else if (WIFSIGNALED(status) || WIFSTOPPED(status)) {
357 int signr = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
358 const char *name = NULL;
359 #ifdef HAVE_STRSIGNAL
360 name = strsignal(signr);
362 ds_put_format(&ds, "%s by signal %d",
363 WIFSIGNALED(status) ? "killed" : "stopped", signr);
365 ds_put_format(&ds, " (%s)", name);
368 ds_put_format(&ds, "terminated abnormally (%x)", status);
370 if (WCOREDUMP(status)) {
371 ds_put_cstr(&ds, ", core dumped");
376 /* Causes the next call to poll_block() to wake up when process 'p' has
379 process_wait(struct process *p)
382 poll_immediate_wake();
384 poll_fd_wait(fds[0], POLLIN);
389 process_search_path(const char *name)
391 char *save_ptr = NULL;
395 if (strchr(name, '/') || !getenv("PATH")) {
396 return stat(name, &s) == 0 ? xstrdup(name) : NULL;
399 path = xstrdup(getenv("PATH"));
400 for (dir = strtok_r(path, ":", &save_ptr); dir;
401 dir = strtok_r(NULL, ":", &save_ptr)) {
402 char *file = xasprintf("%s/%s", dir, name);
403 if (stat(file, &s) == 0) {
413 /* process_run_capture() and supporting functions. */
421 stream_open(struct stream *s)
425 VLOG_WARN("failed to create pipe: %s", strerror(errno));
428 set_nonblocking(s->fds[0]);
433 stream_read(struct stream *s)
444 error = read_fully(s->fds[0], buffer, sizeof buffer, &n);
445 ds_put_buffer(&s->log, buffer, n);
447 if (error == EAGAIN || error == EWOULDBLOCK) {
451 VLOG_WARN("error reading subprocess pipe: %s",
456 } else if (s->log.length > PROCESS_MAX_CAPTURE) {
457 VLOG_WARN("subprocess output overflowed %d-byte buffer",
458 PROCESS_MAX_CAPTURE);
467 stream_wait(struct stream *s)
469 if (s->fds[0] >= 0) {
470 poll_fd_wait(s->fds[0], POLLIN);
475 stream_close(struct stream *s)
478 if (s->fds[0] >= 0) {
481 if (s->fds[1] >= 0) {
486 /* Starts the process whose arguments are given in the null-terminated array
487 * 'argv' and waits for it to exit. On success returns 0 and stores the
488 * process exit value (suitable for passing to process_status_msg()) in
489 * '*status'. On failure, returns a positive errno value and stores 0 in
492 * If 'stdout_log' is nonnull, then the subprocess's output to stdout (up to a
493 * limit of PROCESS_MAX_CAPTURE bytes) is captured in a memory buffer, which
494 * when this function returns 0 is stored as a null-terminated string in
495 * '*stdout_log'. The caller is responsible for freeing '*stdout_log' (by
496 * passing it to free()). When this function returns an error, '*stdout_log'
499 * If 'stderr_log' is nonnull, then it is treated like 'stdout_log' except
500 * that it captures the subprocess's output to stderr. */
502 process_run_capture(char **argv, char **stdout_log, char **stderr_log,
505 struct stream s_stdout, s_stderr;
510 COVERAGE_INC(process_run_capture);
518 error = process_prestart(argv);
523 error = stream_open(&s_stdout);
528 error = stream_open(&s_stderr);
530 stream_close(&s_stdout);
534 block_sigchld(&oldsigs);
539 unblock_sigchld(&oldsigs);
540 VLOG_WARN("fork failed: %s", strerror(error));
542 stream_close(&s_stdout);
543 stream_close(&s_stderr);
547 /* Running in parent process. */
550 p = process_register(argv[0], pid);
551 unblock_sigchld(&oldsigs);
553 close(s_stdout.fds[1]);
554 close(s_stderr.fds[1]);
555 while (!process_exited(p)) {
556 stream_read(&s_stdout);
557 stream_read(&s_stderr);
559 stream_wait(&s_stdout);
560 stream_wait(&s_stderr);
564 stream_read(&s_stdout);
565 stream_read(&s_stderr);
568 *stdout_log = ds_steal_cstr(&s_stdout.log);
571 *stderr_log = ds_steal_cstr(&s_stderr.log);
574 stream_close(&s_stdout);
575 stream_close(&s_stderr);
577 *status = process_status(p);
581 /* Running in child process. */
586 unblock_sigchld(&oldsigs);
588 dup2(get_null_fd(), 0);
589 dup2(s_stdout.fds[1], 1);
590 dup2(s_stderr.fds[1], 2);
592 max_fds = get_max_fds();
593 for (i = 3; i < max_fds; i++) {
597 execvp(argv[0], argv);
598 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
599 argv[0], strerror(errno));
605 sigchld_handler(int signr OVS_UNUSED)
609 COVERAGE_INC(process_sigchld);
610 LIST_FOR_EACH (p, node, &all_processes) {
614 retval = waitpid(p->pid, &status, WNOHANG);
615 } while (retval == -1 && errno == EINTR);
616 if (retval == p->pid) {
619 } else if (retval < 0) {
620 /* XXX We want to log something but we're in a signal
627 ignore(write(fds[1], "", 1));
631 is_member(int x, const int *array, size_t n)
635 for (i = 0; i < n; i++) {
644 sigchld_is_blocked(void)
647 if (sigprocmask(SIG_SETMASK, NULL, &sigs)) {
648 ovs_fatal(errno, "sigprocmask");
650 return sigismember(&sigs, SIGCHLD);
654 block_sigchld(sigset_t *oldsigs)
657 sigemptyset(&sigchld);
658 sigaddset(&sigchld, SIGCHLD);
659 if (sigprocmask(SIG_BLOCK, &sigchld, oldsigs)) {
660 ovs_fatal(errno, "sigprocmask");
665 unblock_sigchld(const sigset_t *oldsigs)
667 if (sigprocmask(SIG_SETMASK, oldsigs, NULL)) {
668 ovs_fatal(errno, "sigprocmask");