03e00ce1abcdbb0a3a7bfded63c8e8f5da65264c
[sliver-openvswitch.git] / lib / process.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
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:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <config.h>
18 #include "process.h"
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <signal.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
26 #include <unistd.h>
27 #include "coverage.h"
28 #include "dynamic-string.h"
29 #include "fatal-signal.h"
30 #include "list.h"
31 #include "poll-loop.h"
32 #include "signals.h"
33 #include "socket-util.h"
34 #include "util.h"
35 #include "vlog.h"
36
37 VLOG_DEFINE_THIS_MODULE(process);
38
39 COVERAGE_DEFINE(process_sigchld);
40 COVERAGE_DEFINE(process_start);
41
42 struct process {
43     struct list node;
44     char *name;
45     pid_t pid;
46
47     /* State. */
48     bool exited;
49     int status;
50 };
51
52 /* Pipe used to signal child termination. */
53 static int fds[2];
54
55 /* All processes. */
56 static struct list all_processes = LIST_INITIALIZER(&all_processes);
57
58 static void sigchld_handler(int signr OVS_UNUSED);
59
60 /* Initializes the process subsystem (if it is not already initialized).  Calls
61  * exit() if initialization fails.
62  *
63  * This function may not be called after creating any additional threads.
64  *
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. */
68 void
69 process_init(void)
70 {
71     static bool inited;
72     struct sigaction sa;
73
74     if (inited) {
75         return;
76     }
77     inited = true;
78
79     /* Create notification pipe. */
80     xpipe_nonblocking(fds);
81
82     /* Set up child termination signal handler. */
83     memset(&sa, 0, sizeof sa);
84     sa.sa_handler = sigchld_handler;
85     sigemptyset(&sa.sa_mask);
86     sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
87     xsigaction(SIGCHLD, &sa, NULL);
88 }
89
90 char *
91 process_escape_args(char **argv)
92 {
93     struct ds ds = DS_EMPTY_INITIALIZER;
94     char **argp;
95     for (argp = argv; *argp; argp++) {
96         const char *arg = *argp;
97         const char *p;
98         if (argp != argv) {
99             ds_put_char(&ds, ' ');
100         }
101         if (arg[strcspn(arg, " \t\r\n\v\\\'\"")]) {
102             ds_put_char(&ds, '"');
103             for (p = arg; *p; p++) {
104                 if (*p == '\\' || *p == '\"') {
105                     ds_put_char(&ds, '\\');
106                 }
107                 ds_put_char(&ds, *p);
108             }
109             ds_put_char(&ds, '"');
110         } else {
111             ds_put_cstr(&ds, arg);
112         }
113     }
114     return ds_cstr(&ds);
115 }
116
117 /* Prepare to start a process whose command-line arguments are given by the
118  * null-terminated 'argv' array.  Returns 0 if successful, otherwise a
119  * positive errno value. */
120 static int
121 process_prestart(char **argv)
122 {
123     char *binary;
124
125     process_init();
126
127     /* Log the process to be started. */
128     if (VLOG_IS_DBG_ENABLED()) {
129         char *args = process_escape_args(argv);
130         VLOG_DBG("starting subprocess: %s", args);
131         free(args);
132     }
133
134     /* execvp() will search PATH too, but the error in that case is more
135      * obscure, since it is only reported post-fork. */
136     binary = process_search_path(argv[0]);
137     if (!binary) {
138         VLOG_ERR("%s not found in PATH", argv[0]);
139         return ENOENT;
140     }
141     free(binary);
142
143     return 0;
144 }
145
146 /* Creates and returns a new struct process with the specified 'name' and
147  * 'pid'. */
148 static struct process *
149 process_register(const char *name, pid_t pid)
150 {
151     struct process *p;
152     const char *slash;
153
154     p = xzalloc(sizeof *p);
155     p->pid = pid;
156     slash = strrchr(name, '/');
157     p->name = xstrdup(slash ? slash + 1 : name);
158     p->exited = false;
159
160     list_push_back(&all_processes, &p->node);
161
162     return p;
163 }
164
165 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
166  * argv[0] is used as the name of the process.  Searches the PATH environment
167  * variable to find the program to execute.
168  *
169  * This function may not be called after creating any additional threads.
170  *
171  * All file descriptors are closed before executing the subprocess, except for
172  * fds 0, 1, and 2.
173  *
174  * Returns 0 if successful, otherwise a positive errno value indicating the
175  * error.  If successful, '*pp' is assigned a new struct process that may be
176  * used to query the process's status.  On failure, '*pp' is set to NULL. */
177 int
178 process_start(char **argv, struct process **pp)
179 {
180     pid_t pid;
181     int error;
182
183     *pp = NULL;
184     COVERAGE_INC(process_start);
185     error = process_prestart(argv);
186     if (error) {
187         return error;
188     }
189
190     pid = fork();
191     if (pid < 0) {
192         VLOG_WARN("fork failed: %s", strerror(errno));
193         return errno;
194     } else if (pid) {
195         /* Running in parent process. */
196         *pp = process_register(argv[0], pid);
197         return 0;
198     } else {
199         /* Running in child process. */
200         int fd_max = get_max_fds();
201         int fd;
202
203         fatal_signal_fork();
204         for (fd = 3; fd < fd_max; fd++) {
205             close(fd);
206         }
207         execvp(argv[0], argv);
208         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
209                 argv[0], strerror(errno));
210         _exit(1);
211     }
212 }
213
214 /* Destroys process 'p'. */
215 void
216 process_destroy(struct process *p)
217 {
218     if (p) {
219         list_remove(&p->node);
220         free(p->name);
221         free(p);
222     }
223 }
224
225 /* Sends signal 'signr' to process 'p'.  Returns 0 if successful, otherwise a
226  * positive errno value. */
227 int
228 process_kill(const struct process *p, int signr)
229 {
230     return (p->exited ? ESRCH
231             : !kill(p->pid, signr) ? 0
232             : errno);
233 }
234
235 /* Returns the pid of process 'p'. */
236 pid_t
237 process_pid(const struct process *p)
238 {
239     return p->pid;
240 }
241
242 /* Returns the name of process 'p' (the name passed to process_start() with any
243  * leading directories stripped). */
244 const char *
245 process_name(const struct process *p)
246 {
247     return p->name;
248 }
249
250 /* Returns true if process 'p' has exited, false otherwise. */
251 bool
252 process_exited(struct process *p)
253 {
254     return p->exited;
255 }
256
257 /* Returns process 'p''s exit status, as reported by waitpid(2).
258  * process_status(p) may be called only after process_exited(p) has returned
259  * true. */
260 int
261 process_status(const struct process *p)
262 {
263     ovs_assert(p->exited);
264     return p->status;
265 }
266
267 /* Given 'status', which is a process status in the form reported by waitpid(2)
268  * and returned by process_status(), returns a string describing how the
269  * process terminated.  The caller is responsible for freeing the string when
270  * it is no longer needed. */
271 char *
272 process_status_msg(int status)
273 {
274     struct ds ds = DS_EMPTY_INITIALIZER;
275     if (WIFEXITED(status)) {
276         ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
277     } else if (WIFSIGNALED(status)) {
278         char namebuf[SIGNAL_NAME_BUFSIZE];
279
280         ds_put_format(&ds, "killed (%s)",
281                       signal_name(WTERMSIG(status), namebuf, sizeof namebuf));
282     } else if (WIFSTOPPED(status)) {
283         char namebuf[SIGNAL_NAME_BUFSIZE];
284
285         ds_put_format(&ds, "stopped (%s)",
286                       signal_name(WSTOPSIG(status), namebuf, sizeof namebuf));
287     } else {
288         ds_put_format(&ds, "terminated abnormally (%x)", status);
289     }
290     if (WCOREDUMP(status)) {
291         ds_put_cstr(&ds, ", core dumped");
292     }
293     return ds_cstr(&ds);
294 }
295
296 /* Executes periodic maintenance activities required by the process module. */
297 void
298 process_run(void)
299 {
300     char buf[_POSIX_PIPE_BUF];
301
302     if (!list_is_empty(&all_processes) && read(fds[0], buf, sizeof buf) > 0) {
303         struct process *p;
304
305         LIST_FOR_EACH (p, node, &all_processes) {
306             if (!p->exited) {
307                 int retval, status;
308                 do {
309                     retval = waitpid(p->pid, &status, WNOHANG);
310                 } while (retval == -1 && errno == EINTR);
311                 if (retval == p->pid) {
312                     p->exited = true;
313                     p->status = status;
314                 } else if (retval < 0) {
315                     VLOG_WARN("waitpid: %s", strerror(errno));
316                     p->exited = true;
317                     p->status = -1;
318                 }
319             }
320         }
321     }
322 }
323
324
325 /* Causes the next call to poll_block() to wake up when process 'p' has
326  * exited. */
327 void
328 process_wait(struct process *p)
329 {
330     if (p->exited) {
331         poll_immediate_wake();
332     } else {
333         poll_fd_wait(fds[0], POLLIN);
334     }
335 }
336
337 char *
338 process_search_path(const char *name)
339 {
340     char *save_ptr = NULL;
341     char *path, *dir;
342     struct stat s;
343
344     if (strchr(name, '/') || !getenv("PATH")) {
345         return stat(name, &s) == 0 ? xstrdup(name) : NULL;
346     }
347
348     path = xstrdup(getenv("PATH"));
349     for (dir = strtok_r(path, ":", &save_ptr); dir;
350          dir = strtok_r(NULL, ":", &save_ptr)) {
351         char *file = xasprintf("%s/%s", dir, name);
352         if (stat(file, &s) == 0) {
353             free(path);
354             return file;
355         }
356         free(file);
357     }
358     free(path);
359     return NULL;
360 }
361 \f
362 static void
363 sigchld_handler(int signr OVS_UNUSED)
364 {
365     ignore(write(fds[1], "", 1));
366 }