【发布时间】:2011-05-26 21:24:20
【问题描述】:
我需要计算通过标准输入向子进程发送了多少字节,以及子进程向标准输出和标准错误写入了多少字节。子进程调用 execvp,因此我无法从进程本身监控这些统计信息。我目前的策略涉及创建 3 个额外的子进程,每个子进程通过管道监视每个 std 流(或者在 stdin 的情况下,仅从 stdin 读取)。
这种策略充其量似乎真的很脆弱,而且我正在做一些奇怪的事情,这使得监控 stdout/err 的进程无法从它们各自的管道末端读取(并使它们无限期挂起)。代码如下。
这会创建三个辅助子进程,并且应该允许它们统计统计信息:
void controles(struct fds *des)
{
int ex[2];
int err[2];
int n_in = 0;
int c_in;
int n_ex = 0;
int c_ex;
int n_err = 0;
int c_err;
pipe(ex);
pipe(err);
/*has two fields, for the write end of the stdout pipe and the stderr pipe. */
des->err = err[1];
des->ex = ex[1];
switch (fork()) {
case 0: /*stdin */
while (read(0, &c_in, 1) == 1)
n_in++;
if (n_in > 0)
printf("%d bytes to stdin\n", n_in);
exit(n_in);
default:
break;
}
switch (fork()) {
case 0: /*stdout */
close(ex[1]);
/*pretty sure this is wrong */
while (read(ex[0], &c_ex, 1) == 1) {
n_ex++;
write(1, &c_ex, 1);
}
if (n_ex > 0)
printf("%d bytes to stdout\n", n_ex);
close(ex[0]);
exit(n_ex);
default:
close(ex[0]);
}
switch (fork()) {
case 0: /*error */
close(err[1]);
/*also probably have a problem here */
while (read(err[0], &c_err, 1) == 1) {
n_err++;
write(2, &c_err, 1);
}
if (n_err > 0)
printf("%d bytes to stderr\n", n_err);
close(err[0]);
exit(n_err);
default:
close(err[0]);
}
}
这是一个代码片段(在子进程中),它从 fds 结构中设置两个 fd,以便子进程应该写入管道而不是 stdin/stderr。
dup2(des.ex, 1);
dup2(des.err, 2);
close(des.ex); close(des.err); /*Is this right?*/
execvp(opts->exec, opts->options); /*sure this is working fine*/
我迷路了,任何帮助将不胜感激。
【问题讨论】:
-
1.您可以从一个进程为所有三个管道提供服务(它甚至可以是一个 shell 脚本,这取决于您希望通过的结果如何) 2. 如果进程挂起,这可能是在工作中缓冲;确保管道没有缓冲(至少对于输入管道)