Debian Codegraph @

lib/exec.c

raw
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #include <sys/wait.h>
3 #include <stdio.h>
4 #include <errno.h>
5 #include <unistd.h>
6
7 #include "utils.h"
8 #include "namespace.h"
9
10 int cmd_exec(const char *cmd, char **argv, bool do_fork,
11 int (*setup)(void *), void *arg)
12 {
13 fflush(stdout);
14 if (do_fork) {
15 int status;
16 pid_t pid;
17
18 pid = fork();
19 if (pid < 0) {
20 perror("fork");
21 exit(1);
22 }
23
24 if (pid != 0) {
25 /* Parent */
26 if (waitpid(pid, &status, 0) < 0) {
27 perror("waitpid");
28 exit(1);
29 }
30
31 if (WIFEXITED(status)) {
32 return WEXITSTATUS(status);
33 }
34
35 exit(1);
36 }
37 }
38
39 if (setup && setup(arg)) {
40 if (do_fork) {
41 /* In child, nothing to do */
42 _exit(1);
43 }
44 return -1;
45 }
46
47 if (execvp(cmd, argv) < 0)
48 fprintf(stderr, "exec of \"%s\" failed: %s\n",
49 cmd, strerror(errno));
50 _exit(1);
51 }