1 // SPDX-License-Identifier: GPL-2.0
7 #include <linux/string.h>
10 #include "subcmd-util.h"
11 #include "run-command.h"
14 #define STRERR_BUFSIZE 128
16 static inline void close_pair(int fd[2])
22 static inline void dup_devnull(int to)
24 int fd = open("/dev/null", O_RDWR);
29 int start_command(struct child_process *cmd)
31 int need_in, need_out, need_err;
32 int fdin[2], fdout[2], fderr[2];
33 char sbuf[STRERR_BUFSIZE];
36 * In case of errors we must keep the promise to close FDs
37 * that have been passed in via ->in and ->out.
40 need_in = !cmd->no_stdin && cmd->in < 0;
45 return -ERR_RUN_COMMAND_PIPE;
50 need_out = !cmd->no_stdout
51 && !cmd->stdout_to_stderr
54 if (pipe(fdout) < 0) {
59 return -ERR_RUN_COMMAND_PIPE;
64 need_err = !cmd->no_stderr && cmd->err < 0;
66 if (pipe(fderr) < 0) {
75 return -ERR_RUN_COMMAND_PIPE;
102 else if (cmd->stdout_to_stderr)
107 } else if (cmd->out > 1) {
112 if (cmd->dir && chdir(cmd->dir))
113 die("exec %s: cd to %s failed (%s)", cmd->argv[0],
114 cmd->dir, str_error_r(errno, sbuf, sizeof(sbuf)));
116 for (; *cmd->env; cmd->env++) {
117 if (strchr(*cmd->env, '='))
118 putenv((char*)*cmd->env);
125 if (cmd->no_exec_cmd)
126 exit(cmd->no_exec_cmd(cmd));
128 execv_cmd(cmd->argv);
130 execvp(cmd->argv[0], (char *const*) cmd->argv);
147 return err == ENOENT ?
148 -ERR_RUN_COMMAND_EXEC :
149 -ERR_RUN_COMMAND_FORK;
168 static int wait_or_whine(struct child_process *cmd, bool block)
170 bool finished = cmd->finished;
171 int result = cmd->finish_result;
175 pid_t waiting = waitpid(cmd->pid, &status, block ? 0 : WNOHANG);
177 if (!block && waiting == 0)
180 if (waiting < 0 && errno == EINTR)
185 char sbuf[STRERR_BUFSIZE];
187 fprintf(stderr, " Error: waitpid failed (%s)",
188 str_error_r(errno, sbuf, sizeof(sbuf)));
189 result = -ERR_RUN_COMMAND_WAITPID;
190 } else if (waiting != cmd->pid) {
191 result = -ERR_RUN_COMMAND_WAITPID_WRONG_PID;
192 } else if (WIFSIGNALED(status)) {
193 result = -ERR_RUN_COMMAND_WAITPID_SIGNAL;
194 } else if (!WIFEXITED(status)) {
195 result = -ERR_RUN_COMMAND_WAITPID_NOEXIT;
197 code = WEXITSTATUS(status);
200 result = -ERR_RUN_COMMAND_EXEC;
213 cmd->finish_result = result;
218 int check_if_command_finished(struct child_process *cmd)
220 wait_or_whine(cmd, /*block=*/false);
221 return cmd->finished;
224 int finish_command(struct child_process *cmd)
226 return wait_or_whine(cmd, /*block=*/true);
229 int run_command(struct child_process *cmd)
231 int code = start_command(cmd);
234 return finish_command(cmd);
237 static void prepare_run_command_v_opt(struct child_process *cmd,
241 memset(cmd, 0, sizeof(*cmd));
243 cmd->no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
244 cmd->exec_cmd = opt & RUN_EXEC_CMD ? 1 : 0;
245 cmd->stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
248 int run_command_v_opt(const char **argv, int opt)
250 struct child_process cmd;
251 prepare_run_command_v_opt(&cmd, argv, opt);
252 return run_command(&cmd);