使用管道捕获stdin,stdout,子进程的stderr

时间:2013-04-08 18:38:04

标签: c unix exec fork stdin

我必须在C(Unix)中编写程序,它捕获在命令行参数中传递的stdin,stdout和stderr命令。

例如,

./capture echo Hi
== stdout ===
Hi
== end of stdout ==
./capture bc -q
== stdin ==
1+2
== end of stdin ==
== stdout ==
3
== end of stdout ==

我已经为stdout和stderr实现了这样的行为:

int pipe_out[2];
int pipe_in[2];
int finished = 0;

void sig_handler(int signo)
{
    if (signo == SIGCHLD)
    {
        finished = 1;
        wait(NULL);
    }
}

void ChildProcess (char * argv[], char * env[])
{

    dup2(pipe_out[1], 1);
    dup2(pipe_out[1], 2);
    dup2(pipe_in[0], 0);

    close(pipe_out[0]);
    close(pipe_out[1]);

    close(pipe_in[0]);
    close(pipe_in[1]);

    int return_code = execvpe(argv[0], argv, env);
    printf("This should not appear: %d\n", return_code);
    printf("Error: %s\n\n", strerror(errno));
}   

void ParentProcess(pid_t pid)
{
    int status;
    char buf[10000];

    fd_set out_fds;
    fd_set in_fds;

    signal(SIGCHLD, sig_handler);

    do
    {
        FD_ZERO(&out_fds);
        FD_ZERO(&in_fds);
        FD_SET(pipe_in[1], &in_fds); 
        FD_SET(pipe_out[0], &out_fds);
        int cnt = select(max(pipe_out[0], pipe_out[0]) + 1, &out_fds, NULL, NULL, NULL);
        if (cnt > 0 && FD_ISSET(pipe_out[0], &out_fds))
        {
            puts("== stdout ==");
            read(pipe_out[0], buf, sizeof(buf));
            printf("%s", buf);
            puts("== end of stdout == ");
            continue;
        }
        if (0 && FD_ISSET(pipe_in[1], &in_fds))
        {
            puts("== stdin ==");
            write(pipe_in[1], "1+2\n", sizeof("1+2\n"));
            puts("== end of stdin ==");
            continue;
        }
    } while (!finished);
}   

据我所知,它以这种方式工作:父进程调用select()并等待子进程的输出。之后,父进程打印其他信息(== stdout ==)和子输出。

当我尝试为stdin实现相同的行为时,我发现in_fds总是准备独立于子进程需要什么。所以capture总是从stdin读取。即使孩子的过程需要输出一些东西。

所以我的问题是如何实现这样的行为?

我认为必须有一个特殊信号指示子进程何时需要输入,但我找不到任何内容。

0 个答案:

没有答案
相关问题