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"
36 #define THIS_MODULE VLM_process
44 /* Modified by signal handler. */
49 /* Pipe used to signal child termination. */
53 static struct list all_processes = LIST_INITIALIZER(&all_processes);
55 static bool sigchld_is_blocked(void);
56 static void block_sigchld(sigset_t *);
57 static void unblock_sigchld(const sigset_t *);
58 static void sigchld_handler(int signr OVS_UNUSED);
59 static bool is_member(int x, const int *array, size_t);
61 /* Initializes the process subsystem (if it is not already initialized). Calls
62 * exit() if initialization fails.
64 * Calling this function is optional; it will be called automatically by
65 * process_start() if necessary. Calling it explicitly allows the client to
66 * prevent the process from exiting at an unexpected time. */
78 /* Create notification pipe. */
80 ovs_fatal(errno, "could not create pipe");
82 set_nonblocking(fds[0]);
83 set_nonblocking(fds[1]);
85 /* Set up child termination signal handler. */
86 memset(&sa, 0, sizeof sa);
87 sa.sa_handler = sigchld_handler;
88 sigemptyset(&sa.sa_mask);
89 sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
90 if (sigaction(SIGCHLD, &sa, NULL)) {
91 ovs_fatal(errno, "sigaction(SIGCHLD) failed");
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,
197 COVERAGE_INC(process_start);
198 error = process_prestart(argv);
203 block_sigchld(&oldsigs);
206 unblock_sigchld(&oldsigs);
207 VLOG_WARN("fork failed: %s", strerror(errno));
210 /* Running in parent process. */
211 *pp = process_register(argv[0], pid);
212 unblock_sigchld(&oldsigs);
215 /* Running in child process. */
216 int fd_max = get_max_fds();
220 unblock_sigchld(&oldsigs);
221 for (fd = 0; fd < fd_max; fd++) {
222 if (is_member(fd, null_fds, n_null_fds)) {
223 /* We can't use get_null_fd() here because we might have
224 * already closed its fd. */
225 int nullfd = open("/dev/null", O_RDWR);
228 } else if (fd >= 3 && !is_member(fd, keep_fds, n_keep_fds)) {
232 execvp(argv[0], argv);
233 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
234 argv[0], strerror(errno));
239 /* Destroys process 'p'. */
241 process_destroy(struct process *p)
246 block_sigchld(&oldsigs);
247 list_remove(&p->node);
248 unblock_sigchld(&oldsigs);
255 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
256 * positive errno value. */
258 process_kill(const struct process *p, int signr)
260 return (p->exited ? ESRCH
261 : !kill(p->pid, signr) ? 0
265 /* Returns the pid of process 'p'. */
267 process_pid(const struct process *p)
272 /* Returns the name of process 'p' (the name passed to process_start() with any
273 * leading directories stripped). */
275 process_name(const struct process *p)
280 /* Returns true if process 'p' has exited, false otherwise. */
282 process_exited(struct process *p)
287 char buf[_POSIX_PIPE_BUF];
288 ignore(read(fds[0], buf, sizeof buf));
293 /* Returns process 'p''s exit status, as reported by waitpid(2).
294 * process_status(p) may be called only after process_exited(p) has returned
297 process_status(const struct process *p)
304 process_run(char **argv,
305 const int keep_fds[], size_t n_keep_fds,
306 const int null_fds[], size_t n_null_fds,
312 COVERAGE_INC(process_run);
313 retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
320 while (!process_exited(p)) {
324 *status = process_status(p);
329 /* Given 'status', which is a process status in the form reported by waitpid(2)
330 * and returned by process_status(), returns a string describing how the
331 * process terminated. The caller is responsible for freeing the string when
332 * it is no longer needed. */
334 process_status_msg(int status)
336 struct ds ds = DS_EMPTY_INITIALIZER;
337 if (WIFEXITED(status)) {
338 ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
339 } else if (WIFSIGNALED(status) || WIFSTOPPED(status)) {
340 int signr = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
341 const char *name = NULL;
342 #ifdef HAVE_STRSIGNAL
343 name = strsignal(signr);
345 ds_put_format(&ds, "%s by signal %d",
346 WIFSIGNALED(status) ? "killed" : "stopped", signr);
348 ds_put_format(&ds, " (%s)", name);
351 ds_put_format(&ds, "terminated abnormally (%x)", status);
353 if (WCOREDUMP(status)) {
354 ds_put_cstr(&ds, ", core dumped");
359 /* Causes the next call to poll_block() to wake up when process 'p' has
362 process_wait(struct process *p)
365 poll_immediate_wake();
367 poll_fd_wait(fds[0], POLLIN);
372 process_search_path(const char *name)
374 char *save_ptr = NULL;
378 if (strchr(name, '/') || !getenv("PATH")) {
379 return stat(name, &s) == 0 ? xstrdup(name) : NULL;
382 path = xstrdup(getenv("PATH"));
383 for (dir = strtok_r(path, ":", &save_ptr); dir;
384 dir = strtok_r(NULL, ":", &save_ptr)) {
385 char *file = xasprintf("%s/%s", dir, name);
386 if (stat(file, &s) == 0) {
396 /* process_run_capture() and supporting functions. */
404 stream_open(struct stream *s)
408 VLOG_WARN("failed to create pipe: %s", strerror(errno));
411 set_nonblocking(s->fds[0]);
416 stream_read(struct stream *s)
427 error = read_fully(s->fds[0], buffer, sizeof buffer, &n);
428 ds_put_buffer(&s->log, buffer, n);
430 if (error == EAGAIN || error == EWOULDBLOCK) {
434 VLOG_WARN("error reading subprocess pipe: %s",
439 } else if (s->log.length > PROCESS_MAX_CAPTURE) {
440 VLOG_WARN("subprocess output overflowed %d-byte buffer",
441 PROCESS_MAX_CAPTURE);
450 stream_wait(struct stream *s)
452 if (s->fds[0] >= 0) {
453 poll_fd_wait(s->fds[0], POLLIN);
458 stream_close(struct stream *s)
461 if (s->fds[0] >= 0) {
464 if (s->fds[1] >= 0) {
469 /* Starts the process whose arguments are given in the null-terminated array
470 * 'argv' and waits for it to exit. On success returns 0 and stores the
471 * process exit value (suitable for passing to process_status_msg()) in
472 * '*status'. On failure, returns a positive errno value and stores 0 in
475 * If 'stdout_log' is nonnull, then the subprocess's output to stdout (up to a
476 * limit of PROCESS_MAX_CAPTURE bytes) is captured in a memory buffer, which
477 * when this function returns 0 is stored as a null-terminated string in
478 * '*stdout_log'. The caller is responsible for freeing '*stdout_log' (by
479 * passing it to free()). When this function returns an error, '*stdout_log'
482 * If 'stderr_log' is nonnull, then it is treated like 'stdout_log' except
483 * that it captures the subprocess's output to stderr. */
485 process_run_capture(char **argv, char **stdout_log, char **stderr_log,
488 struct stream s_stdout, s_stderr;
493 COVERAGE_INC(process_run_capture);
501 error = process_prestart(argv);
506 error = stream_open(&s_stdout);
511 error = stream_open(&s_stderr);
513 stream_close(&s_stdout);
517 block_sigchld(&oldsigs);
522 unblock_sigchld(&oldsigs);
523 VLOG_WARN("fork failed: %s", strerror(error));
525 stream_close(&s_stdout);
526 stream_close(&s_stderr);
530 /* Running in parent process. */
533 p = process_register(argv[0], pid);
534 unblock_sigchld(&oldsigs);
536 close(s_stdout.fds[1]);
537 close(s_stderr.fds[1]);
538 while (!process_exited(p)) {
539 stream_read(&s_stdout);
540 stream_read(&s_stderr);
542 stream_wait(&s_stdout);
543 stream_wait(&s_stderr);
547 stream_read(&s_stdout);
548 stream_read(&s_stderr);
551 *stdout_log = ds_steal_cstr(&s_stdout.log);
554 *stderr_log = ds_steal_cstr(&s_stderr.log);
557 stream_close(&s_stdout);
558 stream_close(&s_stderr);
560 *status = process_status(p);
564 /* Running in child process. */
569 unblock_sigchld(&oldsigs);
571 dup2(get_null_fd(), 0);
572 dup2(s_stdout.fds[1], 1);
573 dup2(s_stderr.fds[1], 2);
575 max_fds = get_max_fds();
576 for (i = 3; i < max_fds; i++) {
580 execvp(argv[0], argv);
581 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
582 argv[0], strerror(errno));
588 sigchld_handler(int signr OVS_UNUSED)
592 COVERAGE_INC(process_sigchld);
593 LIST_FOR_EACH (p, struct process, node, &all_processes) {
597 retval = waitpid(p->pid, &status, WNOHANG);
598 } while (retval == -1 && errno == EINTR);
599 if (retval == p->pid) {
602 } else if (retval < 0) {
603 /* XXX We want to log something but we're in a signal
610 ignore(write(fds[1], "", 1));
614 is_member(int x, const int *array, size_t n)
618 for (i = 0; i < n; i++) {
627 sigchld_is_blocked(void)
630 if (sigprocmask(SIG_SETMASK, NULL, &sigs)) {
631 ovs_fatal(errno, "sigprocmask");
633 return sigismember(&sigs, SIGCHLD);
637 block_sigchld(sigset_t *oldsigs)
640 sigemptyset(&sigchld);
641 sigaddset(&sigchld, SIGCHLD);
642 if (sigprocmask(SIG_BLOCK, &sigchld, oldsigs)) {
643 ovs_fatal(errno, "sigprocmask");
648 unblock_sigchld(const sigset_t *oldsigs)
650 if (sigprocmask(SIG_SETMASK, oldsigs, NULL)) {
651 ovs_fatal(errno, "sigprocmask");