@matheusbsbs / matheus-bagliano / commits / 4919bf0354
Fork 0

Teach run_command how to setup a stdin pipe

Sometimes callers trying to use run_command to execute a child process will want to setup a pipe or file descriptor to redirect into the child's stdin. This idea is completely stolen from builtin-bundle's fork_with_pipe, written by Johannes Schindelin. All credit (and blame) should lie with Dscho. ;-) Signed-off-by: Shawn O. Pearce <spearce@spearce.org> Signed-off-by: Junio C Hamano <junkio@cox.net>

Shawn O. Pearce committed Mar 10, 2007 at 03:28 UTC 4919bf0354e2a1cfb948c320d45d51319ada30eb
2 files changed +37 -1
run-command.c
+34 -1
@@ -4,15 +4,39 @@
4
5 int start_command(struct child_process *cmd)
6 {
7 + int need_in = !cmd->no_stdin && cmd->in < 0;
8 + int fdin[2];
9 +
10 + if (need_in) {
11 + if (pipe(fdin) < 0)
12 + return -ERR_RUN_COMMAND_PIPE;
13 + cmd->in = fdin[1];
14 + cmd->close_in = 1;
15 + }
16 +
17 cmd->pid = fork();
8 - if (cmd->pid < 0)
18 + if (cmd->pid < 0) {
19 + if (need_in) {
20 + close(fdin[0]);
21 + close(fdin[1]);
22 + }
23 return -ERR_RUN_COMMAND_FORK;
24 + }
25 +
26 if (!cmd->pid) {
27 if (cmd->no_stdin) {
28 int fd = open("/dev/null", O_RDWR);
29 dup2(fd, 0);
30 close(fd);
31 + } else if (need_in) {
32 + dup2(fdin[0], 0);
33 + close(fdin[0]);
34 + close(fdin[1]);
35 + } else if (cmd->in) {
36 + dup2(cmd->in, 0);
37 + close(cmd->in);
38 }
39 +
40 if (cmd->stdout_to_stderr)
41 dup2(2, 1);
42 if (cmd->git_cmd) {
@@ -22,11 +46,20 @@ int start_command(struct child_process *cmd)
46 }
47 die("exec %s failed.", cmd->argv[0]);
48 }
49 +
50 + if (need_in)
51 + close(fdin[0]);
52 + else if (cmd->in)
53 + close(cmd->in);
54 +
55 return 0;
56 }
57
58 int finish_command(struct child_process *cmd)
59 {
60 + if (cmd->close_in)
61 + close(cmd->in);
62 +
63 for (;;) {
64 int status, code;
65 pid_t waiting = waitpid(cmd->pid, &status, 0);
run-command.h
+3
@@ -4,6 +4,7 @@
4 enum {
5 ERR_RUN_COMMAND_FORK = 10000,
6 ERR_RUN_COMMAND_EXEC,
7 + ERR_RUN_COMMAND_PIPE,
8 ERR_RUN_COMMAND_WAITPID,
9 ERR_RUN_COMMAND_WAITPID_WRONG_PID,
10 ERR_RUN_COMMAND_WAITPID_SIGNAL,
@@ -13,6 +14,8 @@ enum {
14 struct child_process {
15 const char **argv;
16 pid_t pid;
17 + int in;
18 + unsigned close_in:1;
19 unsigned no_stdin:1;
20 unsigned git_cmd:1; /* if this is to be git sub-command */
21 unsigned stdout_to_stderr:1;