Have start_command() create a pipe to read the stderr of the child.
This adds another stanza that allocates a pipe that is connected to the child's stderr and that the caller can read from. In order to request this pipe, the caller sets cmd->err to -1. The implementation is not exactly modeled after the stdout case: For stdout the caller can supply an existing file descriptor, but this facility is nowhere needed in the stderr case. Additionally, the caller is required to close cmd->err. Signed-off-by: Johannes Sixt <johannes.sixt@telecom.at> Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
Johannes Sixt committed
Oct 19, 2007 at 21:47 UTC
f3b33f1d220056243d3c1da154d3859410630189
2 files changed
+25
-2
run-command.c
+24
-2
@@ -17,8 +17,8 @@ static inline void dup_devnull(int to)
17
18
int start_command(struct child_process *cmd)
19
{
20
- int need_in, need_out;
21
- int fdin[2], fdout[2];
20
+ int need_in, need_out, need_err;
21
+ int fdin[2], fdout[2], fderr[2];
22
23
need_in = !cmd->no_stdin && cmd->in < 0;
24
if (need_in) {
@@ -41,12 +41,26 @@ int start_command(struct child_process *cmd)
41
cmd->close_out = 1;
42
}
43
44
+ need_err = cmd->err < 0;
45
+ if (need_err) {
46
+ if (pipe(fderr) < 0) {
47
+ if (need_in)
48
+ close_pair(fdin);
49
+ if (need_out)
50
+ close_pair(fdout);
51
+ return -ERR_RUN_COMMAND_PIPE;
52
+ }
53
+ cmd->err = fderr[0];
54
+ }
55
+
56
cmd->pid = fork();
57
if (cmd->pid < 0) {
58
if (need_in)
59
close_pair(fdin);
60
if (need_out)
61
close_pair(fdout);
62
+ if (need_err)
63
+ close_pair(fderr);
64
return -ERR_RUN_COMMAND_FORK;
65
}
66
@@ -73,6 +87,11 @@ int start_command(struct child_process *cmd)
87
close(cmd->out);
88
}
89
90
+ if (need_err) {
91
+ dup2(fderr[1], 2);
92
+ close_pair(fderr);
93
+ }
94
+
95
if (cmd->dir && chdir(cmd->dir))
96
die("exec %s: cd to %s failed (%s)", cmd->argv[0],
97
cmd->dir, strerror(errno));
@@ -102,6 +121,9 @@ int start_command(struct child_process *cmd)
121
else if (cmd->out > 1)
122
close(cmd->out);
123
124
+ if (need_err)
125
+ close(fderr[1]);
126
+
127
return 0;
128
}
129
run-command.h
+1
@@ -16,6 +16,7 @@ struct child_process {
16
pid_t pid;
17
int in;
18
int out;
19
+ int err;
20
const char *dir;
21
const char *const *env;
22
unsigned close_in:1;