2 * Copyright (c) 2008, 2009 Nicira Networks.
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
29 #include "dynamic-string.h"
31 #include "poll-loop.h"
32 #include "socket-util.h"
35 #define THIS_MODULE VLM_process
43 /* Modified by signal handler. */
48 /* Pipe used to signal child termination. */
52 static struct list all_processes = LIST_INITIALIZER(&all_processes);
54 static void block_sigchld(sigset_t *);
55 static void unblock_sigchld(const sigset_t *);
56 static void sigchld_handler(int signr UNUSED);
57 static bool is_member(int x, const int *array, size_t);
59 /* Initializes the process subsystem (if it is not already initialized). Calls
60 * exit() if initialization fails.
62 * Calling this function is optional; it will be called automatically by
63 * process_start() if necessary. Calling it explicitly allows the client to
64 * prevent the process from exiting at an unexpected time. */
76 /* Create notification pipe. */
78 ovs_fatal(errno, "could not create pipe");
80 set_nonblocking(fds[0]);
81 set_nonblocking(fds[1]);
83 /* Set up child termination signal handler. */
84 memset(&sa, 0, sizeof sa);
85 sa.sa_handler = sigchld_handler;
86 sigemptyset(&sa.sa_mask);
87 sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
88 if (sigaction(SIGCHLD, &sa, NULL)) {
89 ovs_fatal(errno, "sigaction(SIGCHLD) failed");
94 process_escape_args(char **argv)
96 struct ds ds = DS_EMPTY_INITIALIZER;
98 for (argp = argv; *argp; argp++) {
99 const char *arg = *argp;
102 ds_put_char(&ds, ' ');
104 if (arg[strcspn(arg, " \t\r\n\v\\")]) {
105 ds_put_char(&ds, '"');
106 for (p = arg; *p; p++) {
107 if (*p == '\\' || *p == '\"') {
108 ds_put_char(&ds, '\\');
110 ds_put_char(&ds, *p);
112 ds_put_char(&ds, '"');
114 ds_put_cstr(&ds, arg);
120 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
121 * argv[0] is used as the name of the process. Searches the PATH environment
122 * variable to find the program to execute.
124 * All file descriptors are closed before executing the subprocess, except for
125 * fds 0, 1, and 2 and the 'n_keep_fds' fds listed in 'keep_fds'. Also, any of
126 * the 'n_null_fds' fds listed in 'null_fds' are replaced by /dev/null.
128 * Returns 0 if successful, otherwise a positive errno value indicating the
129 * error. If successful, '*pp' is assigned a new struct process that may be
130 * used to query the process's status. On failure, '*pp' is set to NULL. */
132 process_start(char **argv,
133 const int keep_fds[], size_t n_keep_fds,
134 const int null_fds[], size_t n_null_fds,
143 COVERAGE_INC(process_start);
145 if (VLOG_IS_DBG_ENABLED()) {
146 char *args = process_escape_args(argv);
147 VLOG_DBG("starting subprocess: %s", args);
151 /* execvp() will search PATH too, but the error in that case is more
152 * obscure, since it is only reported post-fork. */
153 binary = process_search_path(argv[0]);
155 VLOG_ERR("%s not found in PATH", argv[0]);
160 block_sigchld(&oldsigs);
163 unblock_sigchld(&oldsigs);
164 VLOG_WARN("fork failed: %s", strerror(errno));
167 /* Running in parent process. */
171 p = xcalloc(1, sizeof *p);
173 slash = strrchr(argv[0], '/');
174 p->name = xstrdup(slash ? slash + 1 : argv[0]);
177 list_push_back(&all_processes, &p->node);
178 unblock_sigchld(&oldsigs);
183 /* Running in child process. */
184 int fd_max = get_max_fds();
187 unblock_sigchld(&oldsigs);
188 for (fd = 0; fd < fd_max; fd++) {
189 if (is_member(fd, null_fds, n_null_fds)) {
190 int nullfd = open("/dev/null", O_RDWR);
193 } else if (fd >= 3 && !is_member(fd, keep_fds, n_keep_fds)) {
197 execvp(argv[0], argv);
198 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
199 argv[0], strerror(errno));
204 /* Destroys process 'p'. */
206 process_destroy(struct process *p)
211 block_sigchld(&oldsigs);
212 list_remove(&p->node);
213 unblock_sigchld(&oldsigs);
220 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
221 * positive errno value. */
223 process_kill(const struct process *p, int signr)
225 return (p->exited ? ESRCH
226 : !kill(p->pid, signr) ? 0
230 /* Returns the pid of process 'p'. */
232 process_pid(const struct process *p)
237 /* Returns the name of process 'p' (the name passed to process_start() with any
238 * leading directories stripped). */
240 process_name(const struct process *p)
245 /* Returns true if process 'p' has exited, false otherwise. */
247 process_exited(struct process *p)
252 char buf[_POSIX_PIPE_BUF];
253 read(fds[0], buf, sizeof buf);
258 /* Returns process 'p''s exit status, as reported by waitpid(2).
259 * process_status(p) may be called only after process_exited(p) has returned
262 process_status(const struct process *p)
269 process_run(char **argv,
270 const int keep_fds[], size_t n_keep_fds,
271 const int null_fds[], size_t n_null_fds,
277 COVERAGE_INC(process_run);
278 retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
285 while (!process_exited(p)) {
289 *status = process_status(p);
294 /* Given 'status', which is a process status in the form reported by waitpid(2)
295 * and returned by process_status(), returns a string describing how the
296 * process terminated. The caller is responsible for freeing the string when
297 * it is no longer needed. */
299 process_status_msg(int status)
301 struct ds ds = DS_EMPTY_INITIALIZER;
302 if (WIFEXITED(status)) {
303 ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
304 } else if (WIFSIGNALED(status) || WIFSTOPPED(status)) {
305 int signr = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
306 const char *name = NULL;
307 #ifdef HAVE_STRSIGNAL
308 name = strsignal(signr);
310 ds_put_format(&ds, "%s by signal %d",
311 WIFSIGNALED(status) ? "killed" : "stopped", signr);
313 ds_put_format(&ds, " (%s)", name);
316 ds_put_format(&ds, "terminated abnormally (%x)", status);
318 if (WCOREDUMP(status)) {
319 ds_put_cstr(&ds, ", core dumped");
324 /* Causes the next call to poll_block() to wake up when process 'p' has
327 process_wait(struct process *p)
330 poll_immediate_wake();
332 poll_fd_wait(fds[0], POLLIN);
337 process_search_path(const char *name)
339 char *save_ptr = NULL;
343 if (strchr(name, '/') || !getenv("PATH")) {
344 return stat(name, &s) == 0 ? xstrdup(name) : NULL;
347 path = xstrdup(getenv("PATH"));
348 for (dir = strtok_r(path, ":", &save_ptr); dir;
349 dir = strtok_r(NULL, ":", &save_ptr)) {
350 char *file = xasprintf("%s/%s", dir, name);
351 if (stat(file, &s) == 0) {
362 sigchld_handler(int signr UNUSED)
366 COVERAGE_INC(process_sigchld);
367 LIST_FOR_EACH (p, struct process, node, &all_processes) {
371 retval = waitpid(p->pid, &status, WNOHANG);
372 } while (retval == -1 && errno == EINTR);
373 if (retval == p->pid) {
376 } else if (retval < 0) {
377 /* XXX We want to log something but we're in a signal
384 write(fds[1], "", 1);
388 is_member(int x, const int *array, size_t n)
392 for (i = 0; i < n; i++) {
401 block_sigchld(sigset_t *oldsigs)
404 sigemptyset(&sigchld);
405 sigaddset(&sigchld, SIGCHLD);
406 if (sigprocmask(SIG_BLOCK, &sigchld, oldsigs)) {
407 ovs_fatal(errno, "sigprocmask");
412 unblock_sigchld(const sigset_t *oldsigs)
414 if (sigprocmask(SIG_SETMASK, oldsigs, NULL)) {
415 ovs_fatal(errno, "sigprocmask");