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 "ovs-thread.h"
32 #include "poll-loop.h"
34 #include "socket-util.h"
38 VLOG_DEFINE_THIS_MODULE(process);
40 COVERAGE_DEFINE(process_sigchld);
41 COVERAGE_DEFINE(process_start);
53 /* Pipe used to signal child termination. */
57 static struct list all_processes = LIST_INITIALIZER(&all_processes);
59 static void sigchld_handler(int signr OVS_UNUSED);
61 /* Initializes the process subsystem (if it is not already initialized). Calls
62 * exit() if initialization fails.
64 * This function may not be called after creating any additional threads.
66 * Calling this function is optional; it will be called automatically by
67 * process_start() if necessary. Calling it explicitly allows the client to
68 * prevent the process from exiting at an unexpected time. */
75 assert_single_threaded();
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
150 static struct process *
151 process_register(const char *name, pid_t pid)
156 p = xzalloc(sizeof *p);
158 slash = strrchr(name, '/');
159 p->name = xstrdup(slash ? slash + 1 : name);
162 list_push_back(&all_processes, &p->node);
167 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
168 * argv[0] is used as the name of the process. Searches the PATH environment
169 * variable to find the program to execute.
171 * This function may not be called after creating any additional threads.
173 * All file descriptors are closed before executing the subprocess, except for
176 * Returns 0 if successful, otherwise a positive errno value indicating the
177 * error. If successful, '*pp' is assigned a new struct process that may be
178 * used to query the process's status. On failure, '*pp' is set to NULL. */
180 process_start(char **argv, struct process **pp)
185 assert_single_threaded();
188 COVERAGE_INC(process_start);
189 error = process_prestart(argv);
196 VLOG_WARN("fork failed: %s", ovs_strerror(errno));
199 /* Running in parent process. */
200 *pp = process_register(argv[0], pid);
203 /* Running in child process. */
204 int fd_max = get_max_fds();
208 for (fd = 3; fd < fd_max; fd++) {
211 execvp(argv[0], argv);
212 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
213 argv[0], ovs_strerror(errno));
218 /* Destroys process 'p'. */
220 process_destroy(struct process *p)
223 list_remove(&p->node);
229 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
230 * positive errno value. */
232 process_kill(const struct process *p, int signr)
234 return (p->exited ? ESRCH
235 : !kill(p->pid, signr) ? 0
239 /* Returns the pid of process 'p'. */
241 process_pid(const struct process *p)
246 /* Returns the name of process 'p' (the name passed to process_start() with any
247 * leading directories stripped). */
249 process_name(const struct process *p)
254 /* Returns true if process 'p' has exited, false otherwise. */
256 process_exited(struct process *p)
261 /* Returns process 'p''s exit status, as reported by waitpid(2).
262 * process_status(p) may be called only after process_exited(p) has returned
265 process_status(const struct process *p)
267 ovs_assert(p->exited);
271 /* Given 'status', which is a process status in the form reported by waitpid(2)
272 * and returned by process_status(), returns a string describing how the
273 * process terminated. The caller is responsible for freeing the string when
274 * it is no longer needed. */
276 process_status_msg(int status)
278 struct ds ds = DS_EMPTY_INITIALIZER;
279 if (WIFEXITED(status)) {
280 ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
281 } else if (WIFSIGNALED(status)) {
282 char namebuf[SIGNAL_NAME_BUFSIZE];
284 ds_put_format(&ds, "killed (%s)",
285 signal_name(WTERMSIG(status), namebuf, sizeof namebuf));
286 } else if (WIFSTOPPED(status)) {
287 char namebuf[SIGNAL_NAME_BUFSIZE];
289 ds_put_format(&ds, "stopped (%s)",
290 signal_name(WSTOPSIG(status), namebuf, sizeof namebuf));
292 ds_put_format(&ds, "terminated abnormally (%x)", status);
294 if (WCOREDUMP(status)) {
295 ds_put_cstr(&ds, ", core dumped");
300 /* Executes periodic maintenance activities required by the process module. */
304 char buf[_POSIX_PIPE_BUF];
306 if (!list_is_empty(&all_processes) && read(fds[0], buf, sizeof buf) > 0) {
309 LIST_FOR_EACH (p, node, &all_processes) {
313 retval = waitpid(p->pid, &status, WNOHANG);
314 } while (retval == -1 && errno == EINTR);
315 if (retval == p->pid) {
318 } else if (retval < 0) {
319 VLOG_WARN("waitpid: %s", ovs_strerror(errno));
329 /* Causes the next call to poll_block() to wake up when process 'p' has
332 process_wait(struct process *p)
335 poll_immediate_wake();
337 poll_fd_wait(fds[0], POLLIN);
342 process_search_path(const char *name)
344 char *save_ptr = NULL;
348 if (strchr(name, '/') || !getenv("PATH")) {
349 return stat(name, &s) == 0 ? xstrdup(name) : NULL;
352 path = xstrdup(getenv("PATH"));
353 for (dir = strtok_r(path, ":", &save_ptr); dir;
354 dir = strtok_r(NULL, ":", &save_ptr)) {
355 char *file = xasprintf("%s/%s", dir, name);
356 if (stat(file, &s) == 0) {
367 sigchld_handler(int signr OVS_UNUSED)
369 ignore(write(fds[1], "", 1));