1 #include <sys/wait.h> 2 #include <stdio.h> 3 #include <errno.h> 4 #include <unistd.h> 5 6 #include "utils.h" 7 8 int cmd_exec(const char *cmd, char **argv, bool do_fork) 9 { 10 fflush(stdout); 11 if (do_fork) { 12 int status; 13 pid_t pid; 14 15 pid = fork(); 16 if (pid < 0) { 17 perror("fork"); 18 exit(1); 19 } 20 21 if (pid != 0) { 22 /* Parent */ 23 if (waitpid(pid, &status, 0) < 0) { 24 perror("waitpid"); 25 exit(1); 26 } 27 28 if (WIFEXITED(status)) { 29 return WEXITSTATUS(status); 30 } 31 32 exit(1); 33 } 34 } 35 36 if (execvp(cmd, argv) < 0) 37 fprintf(stderr, "exec of \"%s\" failed: %s\n", 38 cmd, strerror(errno)); 39 _exit(1); 40 } 41