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"
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 ovs_fatal(errno, "could not create pipe");
88 set_nonblocking(fds[0]);
89 set_nonblocking(fds[1]);
91 /* Set up child termination signal handler. */
92 memset(&sa, 0, sizeof sa);
93 sa.sa_handler = sigchld_handler;
94 sigemptyset(&sa.sa_mask);
95 sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
96 if (sigaction(SIGCHLD, &sa, NULL)) {
97 ovs_fatal(errno, "sigaction(SIGCHLD) failed");
102 process_escape_args(char **argv)
104 struct ds ds = DS_EMPTY_INITIALIZER;
106 for (argp = argv; *argp; argp++) {
107 const char *arg = *argp;
110 ds_put_char(&ds, ' ');
112 if (arg[strcspn(arg, " \t\r\n\v\\\'\"")]) {
113 ds_put_char(&ds, '"');
114 for (p = arg; *p; p++) {
115 if (*p == '\\' || *p == '\"') {
116 ds_put_char(&ds, '\\');
118 ds_put_char(&ds, *p);
120 ds_put_char(&ds, '"');
122 ds_put_cstr(&ds, arg);
128 /* Prepare to start a process whose command-line arguments are given by the
129 * null-terminated 'argv' array. Returns 0 if successful, otherwise a
130 * positive errno value. */
132 process_prestart(char **argv)
138 /* Log the process to be started. */
139 if (VLOG_IS_DBG_ENABLED()) {
140 char *args = process_escape_args(argv);
141 VLOG_DBG("starting subprocess: %s", args);
145 /* execvp() will search PATH too, but the error in that case is more
146 * obscure, since it is only reported post-fork. */
147 binary = process_search_path(argv[0]);
149 VLOG_ERR("%s not found in PATH", argv[0]);
157 /* Creates and returns a new struct process with the specified 'name' and
160 * This is racy unless SIGCHLD is blocked (and has been blocked since before
161 * the fork()) that created the subprocess. */
162 static struct process *
163 process_register(const char *name, pid_t pid)
168 assert(sigchld_is_blocked());
170 p = xzalloc(sizeof *p);
172 slash = strrchr(name, '/');
173 p->name = xstrdup(slash ? slash + 1 : name);
176 list_push_back(&all_processes, &p->node);
181 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
182 * argv[0] is used as the name of the process. Searches the PATH environment
183 * variable to find the program to execute.
185 * All file descriptors are closed before executing the subprocess, except for
186 * fds 0, 1, and 2 and the 'n_keep_fds' fds listed in 'keep_fds'. Also, any of
187 * the 'n_null_fds' fds listed in 'null_fds' are replaced by /dev/null.
189 * Returns 0 if successful, otherwise a positive errno value indicating the
190 * error. If successful, '*pp' is assigned a new struct process that may be
191 * used to query the process's status. On failure, '*pp' is set to NULL. */
193 process_start(char **argv,
194 const int keep_fds[], size_t n_keep_fds,
195 const int null_fds[], size_t n_null_fds,
204 COVERAGE_INC(process_start);
205 error = process_prestart(argv);
211 nullfd = get_null_fd();
219 block_sigchld(&oldsigs);
222 unblock_sigchld(&oldsigs);
223 VLOG_WARN("fork failed: %s", strerror(errno));
226 /* Running in parent process. */
227 *pp = process_register(argv[0], pid);
228 unblock_sigchld(&oldsigs);
231 /* Running in child process. */
232 int fd_max = get_max_fds();
236 unblock_sigchld(&oldsigs);
237 for (fd = 0; fd < fd_max; fd++) {
238 if (is_member(fd, null_fds, n_null_fds)) {
240 } else if (fd >= 3 && fd != nullfd
241 && !is_member(fd, keep_fds, n_keep_fds)) {
246 && !is_member(nullfd, keep_fds, n_keep_fds)
247 && !is_member(nullfd, null_fds, n_null_fds)) {
250 execvp(argv[0], argv);
251 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
252 argv[0], strerror(errno));
257 /* Destroys process 'p'. */
259 process_destroy(struct process *p)
264 block_sigchld(&oldsigs);
265 list_remove(&p->node);
266 unblock_sigchld(&oldsigs);
273 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
274 * positive errno value. */
276 process_kill(const struct process *p, int signr)
278 return (p->exited ? ESRCH
279 : !kill(p->pid, signr) ? 0
283 /* Returns the pid of process 'p'. */
285 process_pid(const struct process *p)
290 /* Returns the name of process 'p' (the name passed to process_start() with any
291 * leading directories stripped). */
293 process_name(const struct process *p)
298 /* Returns true if process 'p' has exited, false otherwise. */
300 process_exited(struct process *p)
305 char buf[_POSIX_PIPE_BUF];
306 ignore(read(fds[0], buf, sizeof buf));
311 /* Returns process 'p''s exit status, as reported by waitpid(2).
312 * process_status(p) may be called only after process_exited(p) has returned
315 process_status(const struct process *p)
322 process_run(char **argv,
323 const int keep_fds[], size_t n_keep_fds,
324 const int null_fds[], size_t n_null_fds,
330 COVERAGE_INC(process_run);
331 retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
338 while (!process_exited(p)) {
342 *status = process_status(p);
347 /* Given 'status', which is a process status in the form reported by waitpid(2)
348 * and returned by process_status(), returns a string describing how the
349 * process terminated. The caller is responsible for freeing the string when
350 * it is no longer needed. */
352 process_status_msg(int status)
354 struct ds ds = DS_EMPTY_INITIALIZER;
355 if (WIFEXITED(status)) {
356 ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
357 } else if (WIFSIGNALED(status)) {
358 ds_put_format(&ds, "killed (%s)", signal_name(WTERMSIG(status)));
359 } else if (WIFSTOPPED(status)) {
360 ds_put_format(&ds, "stopped (%s)", signal_name(WSTOPSIG(status)));
362 ds_put_format(&ds, "terminated abnormally (%x)", status);
364 if (WCOREDUMP(status)) {
365 ds_put_cstr(&ds, ", core dumped");
370 /* Causes the next call to poll_block() to wake up when process 'p' has
373 process_wait(struct process *p)
376 poll_immediate_wake();
378 poll_fd_wait(fds[0], POLLIN);
383 process_search_path(const char *name)
385 char *save_ptr = NULL;
389 if (strchr(name, '/') || !getenv("PATH")) {
390 return stat(name, &s) == 0 ? xstrdup(name) : NULL;
393 path = xstrdup(getenv("PATH"));
394 for (dir = strtok_r(path, ":", &save_ptr); dir;
395 dir = strtok_r(NULL, ":", &save_ptr)) {
396 char *file = xasprintf("%s/%s", dir, name);
397 if (stat(file, &s) == 0) {
407 /* process_run_capture() and supporting functions. */
415 stream_open(struct stream *s)
419 VLOG_WARN("failed to create pipe: %s", strerror(errno));
422 set_nonblocking(s->fds[0]);
427 stream_read(struct stream *s)
438 error = read_fully(s->fds[0], buffer, sizeof buffer, &n);
439 ds_put_buffer(&s->log, buffer, n);
441 if (error == EAGAIN || error == EWOULDBLOCK) {
445 VLOG_WARN("error reading subprocess pipe: %s",
450 } else if (s->log.length > PROCESS_MAX_CAPTURE) {
451 VLOG_WARN("subprocess output overflowed %d-byte buffer",
452 PROCESS_MAX_CAPTURE);
461 stream_wait(struct stream *s)
463 if (s->fds[0] >= 0) {
464 poll_fd_wait(s->fds[0], POLLIN);
469 stream_close(struct stream *s)
472 if (s->fds[0] >= 0) {
475 if (s->fds[1] >= 0) {
480 /* Starts the process whose arguments are given in the null-terminated array
481 * 'argv' and waits for it to exit. On success returns 0 and stores the
482 * process exit value (suitable for passing to process_status_msg()) in
483 * '*status'. On failure, returns a positive errno value and stores 0 in
486 * If 'stdout_log' is nonnull, then the subprocess's output to stdout (up to a
487 * limit of PROCESS_MAX_CAPTURE bytes) is captured in a memory buffer, which
488 * when this function returns 0 is stored as a null-terminated string in
489 * '*stdout_log'. The caller is responsible for freeing '*stdout_log' (by
490 * passing it to free()). When this function returns an error, '*stdout_log'
493 * If 'stderr_log' is nonnull, then it is treated like 'stdout_log' except
494 * that it captures the subprocess's output to stderr. */
496 process_run_capture(char **argv, char **stdout_log, char **stderr_log,
499 struct stream s_stdout, s_stderr;
504 COVERAGE_INC(process_run_capture);
512 error = process_prestart(argv);
517 error = stream_open(&s_stdout);
522 error = stream_open(&s_stderr);
524 stream_close(&s_stdout);
528 block_sigchld(&oldsigs);
533 unblock_sigchld(&oldsigs);
534 VLOG_WARN("fork failed: %s", strerror(error));
536 stream_close(&s_stdout);
537 stream_close(&s_stderr);
541 /* Running in parent process. */
544 p = process_register(argv[0], pid);
545 unblock_sigchld(&oldsigs);
547 close(s_stdout.fds[1]);
548 close(s_stderr.fds[1]);
549 while (!process_exited(p)) {
550 stream_read(&s_stdout);
551 stream_read(&s_stderr);
553 stream_wait(&s_stdout);
554 stream_wait(&s_stderr);
558 stream_read(&s_stdout);
559 stream_read(&s_stderr);
562 *stdout_log = ds_steal_cstr(&s_stdout.log);
565 *stderr_log = ds_steal_cstr(&s_stderr.log);
568 stream_close(&s_stdout);
569 stream_close(&s_stderr);
571 *status = process_status(p);
575 /* Running in child process. */
580 unblock_sigchld(&oldsigs);
582 dup2(get_null_fd(), 0);
583 dup2(s_stdout.fds[1], 1);
584 dup2(s_stderr.fds[1], 2);
586 max_fds = get_max_fds();
587 for (i = 3; i < max_fds; i++) {
591 execvp(argv[0], argv);
592 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
593 argv[0], strerror(errno));
599 sigchld_handler(int signr OVS_UNUSED)
603 COVERAGE_INC(process_sigchld);
604 LIST_FOR_EACH (p, node, &all_processes) {
608 retval = waitpid(p->pid, &status, WNOHANG);
609 } while (retval == -1 && errno == EINTR);
610 if (retval == p->pid) {
613 } else if (retval < 0) {
614 /* XXX We want to log something but we're in a signal
621 ignore(write(fds[1], "", 1));
625 is_member(int x, const int *array, size_t n)
629 for (i = 0; i < n; i++) {
638 sigchld_is_blocked(void)
641 if (sigprocmask(SIG_SETMASK, NULL, &sigs)) {
642 ovs_fatal(errno, "sigprocmask");
644 return sigismember(&sigs, SIGCHLD);
648 block_sigchld(sigset_t *oldsigs)
651 sigemptyset(&sigchld);
652 sigaddset(&sigchld, SIGCHLD);
653 if (sigprocmask(SIG_BLOCK, &sigchld, oldsigs)) {
654 ovs_fatal(errno, "sigprocmask");
659 unblock_sigchld(const sigset_t *oldsigs)
661 if (sigprocmask(SIG_SETMASK, oldsigs, NULL)) {
662 ovs_fatal(errno, "sigprocmask");