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_start);
52 /* Pipe used to signal child termination. */
56 static struct list all_processes = LIST_INITIALIZER(&all_processes);
58 static void sigchld_handler(int signr OVS_UNUSED);
60 /* Initializes the process subsystem (if it is not already initialized). Calls
61 * exit() if initialization fails.
63 * This function may not be called after creating any additional threads.
65 * Calling this function is optional; it will be called automatically by
66 * process_start() if necessary. Calling it explicitly allows the client to
67 * 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);
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 /* Prepare to start a process whose command-line arguments are given by the
121 * null-terminated 'argv' array. Returns 0 if successful, otherwise a
122 * positive errno value. */
124 process_prestart(char **argv)
130 /* Log the process to be started. */
131 if (VLOG_IS_DBG_ENABLED()) {
132 char *args = process_escape_args(argv);
133 VLOG_DBG("starting subprocess: %s", args);
137 /* execvp() will search PATH too, but the error in that case is more
138 * obscure, since it is only reported post-fork. */
139 binary = process_search_path(argv[0]);
141 VLOG_ERR("%s not found in PATH", argv[0]);
149 /* Creates and returns a new struct process with the specified 'name' and
151 static struct process *
152 process_register(const char *name, pid_t pid)
157 p = xzalloc(sizeof *p);
159 slash = strrchr(name, '/');
160 p->name = xstrdup(slash ? slash + 1 : name);
163 list_push_back(&all_processes, &p->node);
168 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
169 * argv[0] is used as the name of the process. Searches the PATH environment
170 * variable to find the program to execute.
172 * This function may not be called after creating any additional threads.
174 * All file descriptors are closed before executing the subprocess, except for
177 * Returns 0 if successful, otherwise a positive errno value indicating the
178 * error. If successful, '*pp' is assigned a new struct process that may be
179 * used to query the process's status. On failure, '*pp' is set to NULL. */
181 process_start(char **argv, struct process **pp)
187 assert_single_threaded();
190 COVERAGE_INC(process_start);
191 error = process_prestart(argv);
198 VLOG_WARN("fork failed: %s", ovs_strerror(errno));
201 /* Running in parent process. */
202 *pp = process_register(argv[0], pid);
205 /* Running in child process. */
206 int fd_max = get_max_fds();
210 for (fd = 3; fd < fd_max; fd++) {
213 execvp(argv[0], argv);
214 fprintf(stderr, "execvp(\"%s\") failed: %s\n",
215 argv[0], ovs_strerror(errno));
224 /* Destroys process 'p'. */
226 process_destroy(struct process *p)
229 list_remove(&p->node);
235 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
236 * positive errno value. */
238 process_kill(const struct process *p, int signr)
241 return (p->exited ? ESRCH
242 : !kill(p->pid, signr) ? 0
249 /* Returns the pid of process 'p'. */
251 process_pid(const struct process *p)
256 /* Returns the name of process 'p' (the name passed to process_start() with any
257 * leading directories stripped). */
259 process_name(const struct process *p)
264 /* Returns true if process 'p' has exited, false otherwise. */
266 process_exited(struct process *p)
271 /* Returns process 'p''s exit status, as reported by waitpid(2).
272 * process_status(p) may be called only after process_exited(p) has returned
275 process_status(const struct process *p)
277 ovs_assert(p->exited);
281 /* Given 'status', which is a process status in the form reported by waitpid(2)
282 * and returned by process_status(), returns a string describing how the
283 * process terminated. The caller is responsible for freeing the string when
284 * it is no longer needed. */
286 process_status_msg(int status)
288 struct ds ds = DS_EMPTY_INITIALIZER;
290 if (WIFEXITED(status)) {
291 ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
292 } else if (WIFSIGNALED(status)) {
293 char namebuf[SIGNAL_NAME_BUFSIZE];
295 ds_put_format(&ds, "killed (%s)",
296 signal_name(WTERMSIG(status), namebuf, sizeof namebuf));
297 } else if (WIFSTOPPED(status)) {
298 char namebuf[SIGNAL_NAME_BUFSIZE];
300 ds_put_format(&ds, "stopped (%s)",
301 signal_name(WSTOPSIG(status), namebuf, sizeof namebuf));
303 ds_put_format(&ds, "terminated abnormally (%x)", status);
305 if (WCOREDUMP(status)) {
306 ds_put_cstr(&ds, ", core dumped");
309 ds_put_cstr(&ds, "function not supported.");
314 /* Executes periodic maintenance activities required by the process module. */
319 char buf[_POSIX_PIPE_BUF];
321 if (!list_is_empty(&all_processes) && read(fds[0], buf, sizeof buf) > 0) {
324 LIST_FOR_EACH (p, node, &all_processes) {
328 retval = waitpid(p->pid, &status, WNOHANG);
329 } while (retval == -1 && errno == EINTR);
330 if (retval == p->pid) {
333 } else if (retval < 0) {
334 VLOG_WARN("waitpid: %s", ovs_strerror(errno));
345 /* Causes the next call to poll_block() to wake up when process 'p' has
348 process_wait(struct process *p)
352 poll_immediate_wake();
354 poll_fd_wait(fds[0], POLLIN);
362 process_search_path(const char *name)
364 char *save_ptr = NULL;
368 if (strchr(name, '/') || !getenv("PATH")) {
369 return stat(name, &s) == 0 ? xstrdup(name) : NULL;
372 path = xstrdup(getenv("PATH"));
373 for (dir = strtok_r(path, ":", &save_ptr); dir;
374 dir = strtok_r(NULL, ":", &save_ptr)) {
375 char *file = xasprintf("%s/%s", dir, name);
376 if (stat(file, &s) == 0) {
387 sigchld_handler(int signr OVS_UNUSED)
389 ignore(write(fds[1], "", 1));