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
);
126 execv_cmd(cmd
->argv
);
128 execvp(cmd
->argv
[0], (char *const*) cmd
->argv
);
145 return err
== ENOENT
?
146 -ERR_RUN_COMMAND_EXEC
:
147 -ERR_RUN_COMMAND_FORK
;
166 static int wait_or_whine(pid_t pid
)
168 char sbuf
[STRERR_BUFSIZE
];
172 pid_t waiting
= waitpid(pid
, &status
, 0);
177 fprintf(stderr
, " Error: waitpid failed (%s)",
178 str_error_r(errno
, sbuf
, sizeof(sbuf
)));
179 return -ERR_RUN_COMMAND_WAITPID
;
182 return -ERR_RUN_COMMAND_WAITPID_WRONG_PID
;
183 if (WIFSIGNALED(status
))
184 return -ERR_RUN_COMMAND_WAITPID_SIGNAL
;
186 if (!WIFEXITED(status
))
187 return -ERR_RUN_COMMAND_WAITPID_NOEXIT
;
188 code
= WEXITSTATUS(status
);
191 return -ERR_RUN_COMMAND_EXEC
;
200 int finish_command(struct child_process
*cmd
)
202 return wait_or_whine(cmd
->pid
);
205 int run_command(struct child_process
*cmd
)
207 int code
= start_command(cmd
);
210 return finish_command(cmd
);
213 static void prepare_run_command_v_opt(struct child_process
*cmd
,
217 memset(cmd
, 0, sizeof(*cmd
));
219 cmd
->no_stdin
= opt
& RUN_COMMAND_NO_STDIN
? 1 : 0;
220 cmd
->exec_cmd
= opt
& RUN_EXEC_CMD
? 1 : 0;
221 cmd
->stdout_to_stderr
= opt
& RUN_COMMAND_STDOUT_TO_STDERR
? 1 : 0;
224 int run_command_v_opt(const char **argv
, int opt
)
226 struct child_process cmd
;
227 prepare_run_command_v_opt(&cmd
, argv
, opt
);
228 return run_command(&cmd
);