2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 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.
28 #include "dynamic-string.h"
29 #include "fatal-signal.h"
31 #include "poll-loop.h"
33 #include "socket-util.h"
37 VLOG_DEFINE_THIS_MODULE(process);
39 COVERAGE_DEFINE(process_sigchld);
40 COVERAGE_DEFINE(process_start);
47 /* Modified by signal handler. */
52 /* Pipe used to signal child termination. */
56 static struct list all_processes = LIST_INITIALIZER(&all_processes);
58 static bool sigchld_is_blocked(void);
59 static void block_sigchld(sigset_t *);
60 static void unblock_sigchld(const sigset_t *);
61 static void sigchld_handler(int signr OVS_UNUSED);
62 static bool is_member(int x, const int *array, size_t);
64 /* Initializes the process subsystem (if it is not already initialized). Calls
65 * exit() if initialization fails.
67 * Calling this function is optional; it will be called automatically by
68 * process_start() if necessary. Calling it explicitly allows the client to
69 * prevent the process from exiting at an unexpected time. */
81 /* Create notification pipe. */
82 xpipe_nonblocking(fds);
84 /* Set up child termination signal handler. */
85 memset(&sa, 0, sizeof sa);
86 sa.sa_handler = sigchld_handler;
87 sigemptyset(&sa.sa_mask);
88 sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
89 xsigaction(SIGCHLD, &sa, NULL);
93 process_escape_args(char **argv)
95 struct ds ds = DS_EMPTY_INITIALIZER;
97 for (argp = argv; *argp; argp++) {
98 const char *arg = *argp;
101 ds_put_char(&ds, ' ');
103 if (arg[strcspn(arg, " \t\r\n\v\\\'\"")]) {
104 ds_put_char(&ds, '"');
105 for (p = arg; *p; p++) {
106 if (*p == '\\' || *p == '\"') {
107 ds_put_char(&ds, '\\');
109 ds_put_char(&ds, *p);
111 ds_put_char(&ds, '"');
113 ds_put_cstr(&ds, arg);
119 /* Prepare to start a process whose command-line arguments are given by the
120 * null-terminated 'argv' array. Returns 0 if successful, otherwise a
121 * positive errno value. */
123 process_prestart(char **argv)
129 /* Log the process to be started. */
130 if (VLOG_IS_DBG_ENABLED()) {
131 char *args = process_escape_args(argv);
132 VLOG_DBG("starting subprocess: %s", args);
136 /* execvp() will search PATH too, but the error in that case is more
137 * obscure, since it is only reported post-fork. */
138 binary = process_search_path(argv[0]);
140 VLOG_ERR("%s not found in PATH", argv[0]);
148 /* Creates and returns a new struct process with the specified 'name' and
151 * This is racy unless SIGCHLD is blocked (and has been blocked since before
152 * the fork()) that created the subprocess. */
153 static struct process *
154 process_register(const char *name, pid_t pid)
159 ovs_assert(sigchld_is_blocked());
161 p = xzalloc(sizeof *p);
163 slash = strrchr(name, '/');
164 p->name = xstrdup(slash ? slash + 1 : name);
167 list_push_back(&all_processes, &p->node);
172 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
173 * argv[0] is used as the name of the process. Searches the PATH environment
174 * variable to find the program to execute.
176 * All file descriptors are closed before executing the subprocess, except for
177 * fds 0, 1, and 2 and the 'n_keep_fds' fds listed in 'keep_fds'. Also, any of
178 * the 'n_null_fds' fds listed in 'null_fds' are replaced by /dev/null.
180 * Returns 0 if successful, otherwise a positive errno value indicating the
181 * error. If successful, '*pp' is assigned a new struct process that may be
182 * used to query the process's status. On failure, '*pp' is set to NULL. */
184 process_start(char **argv,
185 const int keep_fds[], size_t n_keep_fds,
186 const int null_fds[], size_t n_null_fds,
195 COVERAGE_INC(process_start);
196 error = process_prestart(argv);
202 nullfd = get_null_fd();
210 block_sigchld(&oldsigs);
213 unblock_sigchld(&oldsigs);
214 VLOG_WARN("fork failed: %s", strerror(errno));
217 /* Running in parent process. */
218 *pp = process_register(argv[0], pid);
219 unblock_sigchld(&oldsigs);
222 /* Running in child process. */
223 int fd_max = get_max_fds();
227 unblock_sigchld(&oldsigs);
228 for (fd = 0; fd < fd_max; fd++) {
229 if (is_member(fd, null_fds, n_null_fds)) {
231 } else if (fd >= 3 && fd != nullfd
232 && !is_member(fd, keep_fds, n_keep_fds)) {
237 && !is_member(nullfd, keep_fds, n_keep_fds)
238 && !is_member(nullfd, null_fds, n_null_fds)) {
241 execvp(argv[0], argv);
242 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
243 argv[0], strerror(errno));
248 /* Destroys process 'p'. */
250 process_destroy(struct process *p)
255 block_sigchld(&oldsigs);
256 list_remove(&p->node);
257 unblock_sigchld(&oldsigs);
264 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
265 * positive errno value. */
267 process_kill(const struct process *p, int signr)
269 return (p->exited ? ESRCH
270 : !kill(p->pid, signr) ? 0
274 /* Returns the pid of process 'p'. */
276 process_pid(const struct process *p)
281 /* Returns the name of process 'p' (the name passed to process_start() with any
282 * leading directories stripped). */
284 process_name(const struct process *p)
289 /* Returns true if process 'p' has exited, false otherwise. */
291 process_exited(struct process *p)
296 char buf[_POSIX_PIPE_BUF];
297 ignore(read(fds[0], buf, sizeof buf));
302 /* Returns process 'p''s exit status, as reported by waitpid(2).
303 * process_status(p) may be called only after process_exited(p) has returned
306 process_status(const struct process *p)
308 ovs_assert(p->exited);
312 /* Given 'status', which is a process status in the form reported by waitpid(2)
313 * and returned by process_status(), returns a string describing how the
314 * process terminated. The caller is responsible for freeing the string when
315 * it is no longer needed. */
317 process_status_msg(int status)
319 struct ds ds = DS_EMPTY_INITIALIZER;
320 if (WIFEXITED(status)) {
321 ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
322 } else if (WIFSIGNALED(status)) {
323 char namebuf[SIGNAL_NAME_BUFSIZE];
325 ds_put_format(&ds, "killed (%s)",
326 signal_name(WTERMSIG(status), namebuf, sizeof namebuf));
327 } else if (WIFSTOPPED(status)) {
328 char namebuf[SIGNAL_NAME_BUFSIZE];
330 ds_put_format(&ds, "stopped (%s)",
331 signal_name(WSTOPSIG(status), namebuf, sizeof namebuf));
333 ds_put_format(&ds, "terminated abnormally (%x)", status);
335 if (WCOREDUMP(status)) {
336 ds_put_cstr(&ds, ", core dumped");
341 /* Causes the next call to poll_block() to wake up when process 'p' has
344 process_wait(struct process *p)
347 poll_immediate_wake();
349 poll_fd_wait(fds[0], POLLIN);
354 process_search_path(const char *name)
356 char *save_ptr = NULL;
360 if (strchr(name, '/') || !getenv("PATH")) {
361 return stat(name, &s) == 0 ? xstrdup(name) : NULL;
364 path = xstrdup(getenv("PATH"));
365 for (dir = strtok_r(path, ":", &save_ptr); dir;
366 dir = strtok_r(NULL, ":", &save_ptr)) {
367 char *file = xasprintf("%s/%s", dir, name);
368 if (stat(file, &s) == 0) {
379 sigchld_handler(int signr OVS_UNUSED)
383 COVERAGE_INC(process_sigchld);
384 LIST_FOR_EACH (p, node, &all_processes) {
388 retval = waitpid(p->pid, &status, WNOHANG);
389 } while (retval == -1 && errno == EINTR);
390 if (retval == p->pid) {
393 } else if (retval < 0) {
394 /* XXX We want to log something but we're in a signal
401 ignore(write(fds[1], "", 1));
405 is_member(int x, const int *array, size_t n)
409 for (i = 0; i < n; i++) {
418 sigchld_is_blocked(void)
422 xpthread_sigmask(SIG_SETMASK, NULL, &sigs);
423 return sigismember(&sigs, SIGCHLD);
427 block_sigchld(sigset_t *oldsigs)
431 sigemptyset(&sigchld);
432 sigaddset(&sigchld, SIGCHLD);
433 xpthread_sigmask(SIG_BLOCK, &sigchld, oldsigs);
437 unblock_sigchld(const sigset_t *oldsigs)
439 xpthread_sigmask(SIG_SETMASK, oldsigs, NULL);