用fork,execvp管道两个命令,然后将输出重新输出到socket

时间:2017-06-29 08:51:24

标签: c sockets pipe fork exec

我有两个命令cmd1和cmd2,我必须在子节点中执行cmd1,将输出重定向到另一个子节点,然后以cmd1的输出作为参数执行cmd2。然后我必须将输出重定向到与套接字连接的远程客户端(telnet)。我无法弄清楚问题,但我的解决方案没有将cmd1输出重定向到cmd2。

    if(fork() == 0)
    {
        //Process to compute cmd1
        char *arg[2];
        arg[0] = cmd1;
        arg[1] = NULL;
        dup(piped[1]);
        close(piped[0]);
        close(piped[1]);
        execvp(cmd1,arg);

    }
    if(fork() == 0)
    {
        //Process to compute cmd2
        dup2(newsockfd,STDOUT_FILENO);
        dup2(newsockfd,STDERR_FILENO);
        char *arg[2];
        arg[0] = cmd2;
        arg[1] = NULL;
        dup(piped[0]);
        close(piped[0]);
        close(piped[1]);
        execvp(cmd2,arg);
    }

要清楚。问题不在于套接字处理或管道,这就是为什么我只报告主要部分

1 个答案:

答案 0 :(得分:0)

根据我的理解,你想要的是下面的东西

if(fork() == 0)
{
    //Process to compute cmd1
    char *arg[2];
    arg[0] = cmd1;
    arg[1] = NULL;
    dup2(piped[1],STDOUT_FILENO); //Redirect stdout to pipe's write end
    dup2(piped[1],STDERR_FILENO); //Redirect stderr to pipe's write end
    close(piped[0]);
    close(piped[1]);
    close(newsockfd);
    execvp(cmd1,arg);
}

if(fork() == 0)
{
    //Process to compute cmd2
    char *arg[2];
    arg[0] = cmd2;
    arg[1] = NULL;
    dup2(piped[0],STDIN_FILENO); //Redirect pipe's read end to stdin
    dup2(newsockfd,STDOUT_FILENO); //Redirect stdout to socket
    dup2(newsockfd,STDERR_FILENO); //Redirect stderr to socket
    close(piped[0]);
    close(piped[1]);
    close(newsockfd);
    execvp(cmd2,arg);
}

close(piped[0]);
close(piped[1]);
close(newsockfd);