使用 fork、execvp 的两个命令的管道,然后将输出重定向到套接字

Pipe of two commands with fork,execvp and then rederict the output to socket

我有两个命令 cmd1 和 cmd2,我必须在 child 中执行 cmd1,将输出重定向到另一个 child,然后使用 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);
    }

澄清一下。问题不在于套接字初始化或管道,这就是为什么我只报告了主要部分

根据我的理解,你想要的应该是下面这样的东西

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);