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. */
85 xpipe_nonblocking(fds);
87 /* Set up child termination signal handler. */
88 memset(&sa, 0, sizeof sa);
89 sa.sa_handler = sigchld_handler;
90 sigemptyset(&sa.sa_mask);
91 sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
92 xsigaction(SIGCHLD, &sa, NULL);
96 process_escape_args(char **argv)
98 struct ds ds = DS_EMPTY_INITIALIZER;
100 for (argp = argv; *argp; argp++) {
101 const char *arg = *argp;
104 ds_put_char(&ds, ' ');
106 if (arg[strcspn(arg, " \t\r\n\v\\\'\"")]) {
107 ds_put_char(&ds, '"');
108 for (p = arg; *p; p++) {
109 if (*p == '\\' || *p == '\"') {
110 ds_put_char(&ds, '\\');
112 ds_put_char(&ds, *p);
114 ds_put_char(&ds, '"');
116 ds_put_cstr(&ds, arg);
122 /* Prepare to start a process whose command-line arguments are given by the
123 * null-terminated 'argv' array. Returns 0 if successful, otherwise a
124 * positive errno value. */
126 process_prestart(char **argv)
132 /* Log the process to be started. */
133 if (VLOG_IS_DBG_ENABLED()) {
134 char *args = process_escape_args(argv);
135 VLOG_DBG("starting subprocess: %s", args);
139 /* execvp() will search PATH too, but the error in that case is more
140 * obscure, since it is only reported post-fork. */
141 binary = process_search_path(argv[0]);
143 VLOG_ERR("%s not found in PATH", argv[0]);
151 /* Creates and returns a new struct process with the specified 'name' and
154 * This is racy unless SIGCHLD is blocked (and has been blocked since before
155 * the fork()) that created the subprocess. */
156 static struct process *
157 process_register(const char *name, pid_t pid)
162 assert(sigchld_is_blocked());
164 p = xzalloc(sizeof *p);
166 slash = strrchr(name, '/');
167 p->name = xstrdup(slash ? slash + 1 : name);
170 list_push_back(&all_processes, &p->node);
175 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
176 * argv[0] is used as the name of the process. Searches the PATH environment
177 * variable to find the program to execute.
179 * All file descriptors are closed before executing the subprocess, except for
180 * fds 0, 1, and 2 and the 'n_keep_fds' fds listed in 'keep_fds'. Also, any of
181 * the 'n_null_fds' fds listed in 'null_fds' are replaced by /dev/null.
183 * Returns 0 if successful, otherwise a positive errno value indicating the
184 * error. If successful, '*pp' is assigned a new struct process that may be
185 * used to query the process's status. On failure, '*pp' is set to NULL. */
187 process_start(char **argv,
188 const int keep_fds[], size_t n_keep_fds,
189 const int null_fds[], size_t n_null_fds,
198 COVERAGE_INC(process_start);
199 error = process_prestart(argv);
205 nullfd = get_null_fd();
213 block_sigchld(&oldsigs);
216 unblock_sigchld(&oldsigs);
217 VLOG_WARN("fork failed: %s", strerror(errno));
220 /* Running in parent process. */
221 *pp = process_register(argv[0], pid);
222 unblock_sigchld(&oldsigs);
225 /* Running in child process. */
226 int fd_max = get_max_fds();
230 unblock_sigchld(&oldsigs);
231 for (fd = 0; fd < fd_max; fd++) {
232 if (is_member(fd, null_fds, n_null_fds)) {
234 } else if (fd >= 3 && fd != nullfd
235 && !is_member(fd, keep_fds, n_keep_fds)) {
240 && !is_member(nullfd, keep_fds, n_keep_fds)
241 && !is_member(nullfd, null_fds, n_null_fds)) {
244 execvp(argv[0], argv);
245 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
246 argv[0], strerror(errno));
251 /* Destroys process 'p'. */
253 process_destroy(struct process *p)
258 block_sigchld(&oldsigs);
259 list_remove(&p->node);
260 unblock_sigchld(&oldsigs);
267 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
268 * positive errno value. */
270 process_kill(const struct process *p, int signr)
272 return (p->exited ? ESRCH
273 : !kill(p->pid, signr) ? 0
277 /* Returns the pid of process 'p'. */
279 process_pid(const struct process *p)
284 /* Returns the name of process 'p' (the name passed to process_start() with any
285 * leading directories stripped). */
287 process_name(const struct process *p)
292 /* Returns true if process 'p' has exited, false otherwise. */
294 process_exited(struct process *p)
299 char buf[_POSIX_PIPE_BUF];
300 ignore(read(fds[0], buf, sizeof buf));
305 /* Returns process 'p''s exit status, as reported by waitpid(2).
306 * process_status(p) may be called only after process_exited(p) has returned
309 process_status(const struct process *p)
316 process_run(char **argv,
317 const int keep_fds[], size_t n_keep_fds,
318 const int null_fds[], size_t n_null_fds,
324 COVERAGE_INC(process_run);
325 retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
332 while (!process_exited(p)) {
336 *status = process_status(p);
341 /* Given 'status', which is a process status in the form reported by waitpid(2)
342 * and returned by process_status(), returns a string describing how the
343 * process terminated. The caller is responsible for freeing the string when
344 * it is no longer needed. */
346 process_status_msg(int status)
348 struct ds ds = DS_EMPTY_INITIALIZER;
349 if (WIFEXITED(status)) {
350 ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
351 } else if (WIFSIGNALED(status)) {
352 ds_put_format(&ds, "killed (%s)", signal_name(WTERMSIG(status)));
353 } else if (WIFSTOPPED(status)) {
354 ds_put_format(&ds, "stopped (%s)", signal_name(WSTOPSIG(status)));
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. */
410 stream_open(struct stream *s, size_t max_size)
412 s->max_size = max_size;
415 VLOG_WARN("failed to create pipe: %s", strerror(errno));
418 set_nonblocking(s->fds[0]);
423 stream_read(struct stream *s)
434 error = read_fully(s->fds[0], buffer, sizeof buffer, &n);
435 ds_put_buffer(&s->log, buffer, n);
437 if (error == EAGAIN || error == EWOULDBLOCK) {
441 VLOG_WARN("error reading subprocess pipe: %s",
446 } else if (s->log.length > s->max_size) {
447 VLOG_WARN("subprocess output overflowed %zu-byte buffer",
457 stream_wait(struct stream *s)
459 if (s->fds[0] >= 0) {
460 poll_fd_wait(s->fds[0], POLLIN);
465 stream_close(struct stream *s)
468 if (s->fds[0] >= 0) {
471 if (s->fds[1] >= 0) {
476 /* Starts the process whose arguments are given in the null-terminated array
477 * 'argv' and waits for it to exit. On success returns 0 and stores the
478 * process exit value (suitable for passing to process_status_msg()) in
479 * '*status'. On failure, returns a positive errno value and stores 0 in
482 * If 'stdout_log' is nonnull, then the subprocess's output to stdout (up to a
483 * limit of 'log_max' bytes) is captured in a memory buffer, which
484 * when this function returns 0 is stored as a null-terminated string in
485 * '*stdout_log'. The caller is responsible for freeing '*stdout_log' (by
486 * passing it to free()). When this function returns an error, '*stdout_log'
489 * If 'stderr_log' is nonnull, then it is treated like 'stdout_log' except
490 * that it captures the subprocess's output to stderr. */
492 process_run_capture(char **argv, char **stdout_log, char **stderr_log,
493 size_t max_log, int *status)
495 struct stream s_stdout, s_stderr;
500 COVERAGE_INC(process_run_capture);
508 error = process_prestart(argv);
513 error = stream_open(&s_stdout, max_log);
518 error = stream_open(&s_stderr, max_log);
520 stream_close(&s_stdout);
524 block_sigchld(&oldsigs);
529 unblock_sigchld(&oldsigs);
530 VLOG_WARN("fork failed: %s", strerror(error));
532 stream_close(&s_stdout);
533 stream_close(&s_stderr);
537 /* Running in parent process. */
540 p = process_register(argv[0], pid);
541 unblock_sigchld(&oldsigs);
543 close(s_stdout.fds[1]);
544 close(s_stderr.fds[1]);
545 while (!process_exited(p)) {
546 stream_read(&s_stdout);
547 stream_read(&s_stderr);
549 stream_wait(&s_stdout);
550 stream_wait(&s_stderr);
554 stream_read(&s_stdout);
555 stream_read(&s_stderr);
558 *stdout_log = ds_steal_cstr(&s_stdout.log);
561 *stderr_log = ds_steal_cstr(&s_stderr.log);
564 stream_close(&s_stdout);
565 stream_close(&s_stderr);
567 *status = process_status(p);
571 /* Running in child process. */
576 unblock_sigchld(&oldsigs);
578 dup2(get_null_fd(), 0);
579 dup2(s_stdout.fds[1], 1);
580 dup2(s_stderr.fds[1], 2);
582 max_fds = get_max_fds();
583 for (i = 3; i < max_fds; i++) {
587 execvp(argv[0], argv);
588 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
589 argv[0], strerror(errno));
595 sigchld_handler(int signr OVS_UNUSED)
599 COVERAGE_INC(process_sigchld);
600 LIST_FOR_EACH (p, node, &all_processes) {
604 retval = waitpid(p->pid, &status, WNOHANG);
605 } while (retval == -1 && errno == EINTR);
606 if (retval == p->pid) {
609 } else if (retval < 0) {
610 /* XXX We want to log something but we're in a signal
617 ignore(write(fds[1], "", 1));
621 is_member(int x, const int *array, size_t n)
625 for (i = 0; i < n; i++) {
634 sigchld_is_blocked(void)
638 xsigprocmask(SIG_SETMASK, NULL, &sigs);
639 return sigismember(&sigs, SIGCHLD);
643 block_sigchld(sigset_t *oldsigs)
647 sigemptyset(&sigchld);
648 sigaddset(&sigchld, SIGCHLD);
649 xsigprocmask(SIG_BLOCK, &sigchld, oldsigs);
653 unblock_sigchld(const sigset_t *oldsigs)
655 xsigprocmask(SIG_SETMASK, oldsigs, NULL);