将Ben Voigt的答案纳入代码后,它似乎有效

原始问题:

我正在尝试使用dup2到:

  1. 将“ ls -al”输出作为输入传递给“ grep foo”,
  2. 其输出成为“ grep bar”的输入,
  3. 最终输出到Stdout。

最终输出为(空白),文件“ in” is(空白)和文件“ out”具有“ ls -al”的输出。

有什么想法会发生什么?

int main()
{
    pid_t pid;
    int i;
    int inFileDes,outFileDes;   
    inFileDes=open("in",O_RDWR | O_CREAT,S_IRUSR | S_IWUSR); 
    outFileDes=open("out",O_RDWR | O_CREAT,S_IRUSR | S_IWUSR);  
    for(i=0;i<3;i++)
    {   
        if((pid=fork())==0)
        {
            switch(i)
            {
                case 0:
                dup2(outFileDes,1);
                execl("/bin/ls","ls","-al",0);
                break;
                case 1:
                                                  // originally:
                dup2(outFileDes,0);   // dup2(outFileDes,1);  
                dup2(inFileDes,1);    // dup2(inFileDes,0);

                execl("/bin/grep","grep","foo",0);   //lines having foo
                break;
                case 2:
                dup2(inFileDes,0);
                execl("/bin/grep","grep","bar",0);  //lines having foo & bar
                break;
            }
            exit(-1);  //in error   
        }
        waitpid(pid,NULL,0);
    }
    close(inFileDes);
    close(outFileDes);
    return(0);
}
有帮助吗?

解决方案

您的 open 呼叫创建一个空的文件“在”中,并且没有任何程序写入它,因此可以预期。由于两个实例 grep 从一个空文件中读取,它们的输出也为空。

您真正想要的是使用 pipe 函数以获取一对手柄,这是一个程序,是一个程序,并从下一个程序中读取。您需要将其称为两次,因为您之间有两组连接。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top