2 * Copyright (c) 2008, 2009, 2010, 2011, 2012 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.
29 #include "dynamic-string.h"
30 #include "fatal-signal.h"
32 #include "poll-loop.h"
34 #include "socket-util.h"
38 VLOG_DEFINE_THIS_MODULE(process);
40 COVERAGE_DEFINE(process_run);
41 COVERAGE_DEFINE(process_run_capture);
42 COVERAGE_DEFINE(process_sigchld);
43 COVERAGE_DEFINE(process_start);
50 /* Modified by signal handler. */
55 /* Pipe used to signal child termination. */
59 static struct list all_processes = LIST_INITIALIZER(&all_processes);
61 static bool sigchld_is_blocked(void);
62 static void block_sigchld(sigset_t *);
63 static void unblock_sigchld(const sigset_t *);
64 static void sigchld_handler(int signr OVS_UNUSED);
65 static bool is_member(int x, const int *array, size_t);
67 /* Initializes the process subsystem (if it is not already initialized). Calls
68 * exit() if initialization fails.
70 * Calling this function is optional; it will be called automatically by
71 * process_start() if necessary. Calling it explicitly allows the client to
72 * prevent the process from exiting at an unexpected time. */
84 /* Create notification pipe. */
86 xset_nonblocking(fds[0]);
87 xset_nonblocking(fds[1]);
89 /* Set up child termination signal handler. */
90 memset(&sa, 0, sizeof sa);
91 sa.sa_handler = sigchld_handler;
92 sigemptyset(&sa.sa_mask);
93 sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
94 xsigaction(SIGCHLD, &sa, NULL);
98 process_escape_args(char **argv)
100 struct ds ds = DS_EMPTY_INITIALIZER;
102 for (argp = argv; *argp; argp++) {
103 const char *arg = *argp;
106 ds_put_char(&ds, ' ');
108 if (arg[strcspn(arg, " \t\r\n\v\\\'\"")]) {
109 ds_put_char(&ds, '"');
110 for (p = arg; *p; p++) {
111 if (*p == '\\' || *p == '\"') {
112 ds_put_char(&ds, '\\');
114 ds_put_char(&ds, *p);
116 ds_put_char(&ds, '"');
118 ds_put_cstr(&ds, arg);
124 /* Prepare to start a process whose command-line arguments are given by the
125 * null-terminated 'argv' array. Returns 0 if successful, otherwise a
126 * positive errno value. */
128 process_prestart(char **argv)
134 /* Log the process to be started. */
135 if (VLOG_IS_DBG_ENABLED()) {
136 char *args = process_escape_args(argv);
137 VLOG_DBG("starting subprocess: %s", args);
141 /* execvp() will search PATH too, but the error in that case is more
142 * obscure, since it is only reported post-fork. */
143 binary = process_search_path(argv[0]);
145 VLOG_ERR("%s not found in PATH", argv[0]);
153 /* Creates and returns a new struct process with the specified 'name' and
156 * This is racy unless SIGCHLD is blocked (and has been blocked since before
157 * the fork()) that created the subprocess. */
158 static struct process *
159 process_register(const char *name, pid_t pid)
164 assert(sigchld_is_blocked());
166 p = xzalloc(sizeof *p);
168 slash = strrchr(name, '/');
169 p->name = xstrdup(slash ? slash + 1 : name);
172 list_push_back(&all_processes, &p->node);
177 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
178 * argv[0] is used as the name of the process. Searches the PATH environment
179 * variable to find the program to execute.
181 * All file descriptors are closed before executing the subprocess, except for
182 * fds 0, 1, and 2 and the 'n_keep_fds' fds listed in 'keep_fds'. Also, any of
183 * the 'n_null_fds' fds listed in 'null_fds' are replaced by /dev/null.
185 * Returns 0 if successful, otherwise a positive errno value indicating the
186 * error. If successful, '*pp' is assigned a new struct process that may be
187 * used to query the process's status. On failure, '*pp' is set to NULL. */
189 process_start(char **argv,
190 const int keep_fds[], size_t n_keep_fds,
191 const int null_fds[], size_t n_null_fds,
200 COVERAGE_INC(process_start);
201 error = process_prestart(argv);
207 nullfd = get_null_fd();
215 block_sigchld(&oldsigs);
218 unblock_sigchld(&oldsigs);
219 VLOG_WARN("fork failed: %s", strerror(errno));
222 /* Running in parent process. */
223 *pp = process_register(argv[0], pid);
224 unblock_sigchld(&oldsigs);
227 /* Running in child process. */
228 int fd_max = get_max_fds();
232 unblock_sigchld(&oldsigs);
233 for (fd = 0; fd < fd_max; fd++) {
234 if (is_member(fd, null_fds, n_null_fds)) {
236 } else if (fd >= 3 && fd != nullfd
237 && !is_member(fd, keep_fds, n_keep_fds)) {
242 && !is_member(nullfd, keep_fds, n_keep_fds)
243 && !is_member(nullfd, null_fds, n_null_fds)) {
246 execvp(argv[0], argv);
247 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
248 argv[0], strerror(errno));
253 /* Destroys process 'p'. */
255 process_destroy(struct process *p)
260 block_sigchld(&oldsigs);
261 list_remove(&p->node);
262 unblock_sigchld(&oldsigs);
269 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
270 * positive errno value. */
272 process_kill(const struct process *p, int signr)
274 return (p->exited ? ESRCH
275 : !kill(p->pid, signr) ? 0
279 /* Returns the pid of process 'p'. */
281 process_pid(const struct process *p)
286 /* Returns the name of process 'p' (the name passed to process_start() with any
287 * leading directories stripped). */
289 process_name(const struct process *p)
294 /* Returns true if process 'p' has exited, false otherwise. */
296 process_exited(struct process *p)
301 char buf[_POSIX_PIPE_BUF];
302 ignore(read(fds[0], buf, sizeof buf));
307 /* Returns process 'p''s exit status, as reported by waitpid(2).
308 * process_status(p) may be called only after process_exited(p) has returned
311 process_status(const struct process *p)
318 process_run(char **argv,
319 const int keep_fds[], size_t n_keep_fds,
320 const int null_fds[], size_t n_null_fds,
326 COVERAGE_INC(process_run);
327 retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
334 while (!process_exited(p)) {
338 *status = process_status(p);
343 /* Given 'status', which is a process status in the form reported by waitpid(2)
344 * and returned by process_status(), returns a string describing how the
345 * process terminated. The caller is responsible for freeing the string when
346 * it is no longer needed. */
348 process_status_msg(int status)
350 struct ds ds = DS_EMPTY_INITIALIZER;
351 if (WIFEXITED(status)) {
352 ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
353 } else if (WIFSIGNALED(status)) {
354 ds_put_format(&ds, "killed (%s)", signal_name(WTERMSIG(status)));
355 } else if (WIFSTOPPED(status)) {
356 ds_put_format(&ds, "stopped (%s)", signal_name(WSTOPSIG(status)));
358 ds_put_format(&ds, "terminated abnormally (%x)", status);
360 if (WCOREDUMP(status)) {
361 ds_put_cstr(&ds, ", core dumped");
366 /* Causes the next call to poll_block() to wake up when process 'p' has
369 process_wait(struct process *p)
372 poll_immediate_wake();
374 poll_fd_wait(fds[0], POLLIN);
379 process_search_path(const char *name)
381 char *save_ptr = NULL;
385 if (strchr(name, '/') || !getenv("PATH")) {
386 return stat(name, &s) == 0 ? xstrdup(name) : NULL;
389 path = xstrdup(getenv("PATH"));
390 for (dir = strtok_r(path, ":", &save_ptr); dir;
391 dir = strtok_r(NULL, ":", &save_ptr)) {
392 char *file = xasprintf("%s/%s", dir, name);
393 if (stat(file, &s) == 0) {
403 /* process_run_capture() and supporting functions. */
412 stream_open(struct stream *s, size_t max_size)
414 s->max_size = max_size;
417 VLOG_WARN("failed to create pipe: %s", strerror(errno));
420 set_nonblocking(s->fds[0]);
425 stream_read(struct stream *s)
436 error = read_fully(s->fds[0], buffer, sizeof buffer, &n);
437 ds_put_buffer(&s->log, buffer, n);
439 if (error == EAGAIN || error == EWOULDBLOCK) {
443 VLOG_WARN("error reading subprocess pipe: %s",
448 } else if (s->log.length > s->max_size) {
449 VLOG_WARN("subprocess output overflowed %zu-byte buffer",
459 stream_wait(struct stream *s)
461 if (s->fds[0] >= 0) {
462 poll_fd_wait(s->fds[0], POLLIN);
467 stream_close(struct stream *s)
470 if (s->fds[0] >= 0) {
473 if (s->fds[1] >= 0) {
478 /* Starts the process whose arguments are given in the null-terminated array
479 * 'argv' and waits for it to exit. On success returns 0 and stores the
480 * process exit value (suitable for passing to process_status_msg()) in
481 * '*status'. On failure, returns a positive errno value and stores 0 in
484 * If 'stdout_log' is nonnull, then the subprocess's output to stdout (up to a
485 * limit of 'log_max' bytes) is captured in a memory buffer, which
486 * when this function returns 0 is stored as a null-terminated string in
487 * '*stdout_log'. The caller is responsible for freeing '*stdout_log' (by
488 * passing it to free()). When this function returns an error, '*stdout_log'
491 * If 'stderr_log' is nonnull, then it is treated like 'stdout_log' except
492 * that it captures the subprocess's output to stderr. */
494 process_run_capture(char **argv, char **stdout_log, char **stderr_log,
495 size_t max_log, int *status)
497 struct stream s_stdout, s_stderr;
502 COVERAGE_INC(process_run_capture);
510 error = process_prestart(argv);
515 error = stream_open(&s_stdout, max_log);
520 error = stream_open(&s_stderr, max_log);
522 stream_close(&s_stdout);
526 block_sigchld(&oldsigs);
531 unblock_sigchld(&oldsigs);
532 VLOG_WARN("fork failed: %s", strerror(error));
534 stream_close(&s_stdout);
535 stream_close(&s_stderr);
539 /* Running in parent process. */
542 p = process_register(argv[0], pid);
543 unblock_sigchld(&oldsigs);
545 close(s_stdout.fds[1]);
546 close(s_stderr.fds[1]);
547 while (!process_exited(p)) {
548 stream_read(&s_stdout);
549 stream_read(&s_stderr);
551 stream_wait(&s_stdout);
552 stream_wait(&s_stderr);
556 stream_read(&s_stdout);
557 stream_read(&s_stderr);
560 *stdout_log = ds_steal_cstr(&s_stdout.log);
563 *stderr_log = ds_steal_cstr(&s_stderr.log);
566 stream_close(&s_stdout);
567 stream_close(&s_stderr);
569 *status = process_status(p);
573 /* Running in child process. */
578 unblock_sigchld(&oldsigs);
580 dup2(get_null_fd(), 0);
581 dup2(s_stdout.fds[1], 1);
582 dup2(s_stderr.fds[1], 2);
584 max_fds = get_max_fds();
585 for (i = 3; i < max_fds; i++) {
589 execvp(argv[0], argv);
590 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
591 argv[0], strerror(errno));
597 sigchld_handler(int signr OVS_UNUSED)
601 COVERAGE_INC(process_sigchld);
602 LIST_FOR_EACH (p, node, &all_processes) {
606 retval = waitpid(p->pid, &status, WNOHANG);
607 } while (retval == -1 && errno == EINTR);
608 if (retval == p->pid) {
611 } else if (retval < 0) {
612 /* XXX We want to log something but we're in a signal
619 ignore(write(fds[1], "", 1));
623 is_member(int x, const int *array, size_t n)
627 for (i = 0; i < n; i++) {
636 sigchld_is_blocked(void)
640 xsigprocmask(SIG_SETMASK, NULL, &sigs);
641 return sigismember(&sigs, SIGCHLD);
645 block_sigchld(sigset_t *oldsigs)
649 sigemptyset(&sigchld);
650 sigaddset(&sigchld, SIGCHLD);
651 xsigprocmask(SIG_BLOCK, &sigchld, oldsigs);
655 unblock_sigchld(const sigset_t *oldsigs)
657 xsigprocmask(SIG_SETMASK, oldsigs, NULL);