c - 使用 C 实现管道 ("|")(使用 fork )

标签 c gcc pipe fork

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

int main(int argc,char **argv)
{
    int fd[2];
    pid_t childpid;
    pipe(fd);
    childpid=fork();
    if (childpid == -1)
    {
        perror("Error forking...");
        exit(1);
    }
    if (childpid)   /*parent proces*/   //grep .c
    {
        wait(&childpid);        //waits till the child send output to pipe
        close(fd[1]);
        close(0);       //stdin closed
        dup2(fd[0],0);
        execlp(argv[2],argv[2],argv[3],NULL);

    }
    if (childpid==0)  //ls
    {
        close(fd[0]);   /*Closes read side of pipe*/
        close(1);       //STDOUT closed
        dup2(fd[1],1);
        execl(argv[1],NULL);
    }
    return 0;
}

如果我将命令行参数设置为“ls grep .c”,我应该会显示所有“.c”文件。

伪代码:- 我的子进程将运行“ls”,父进程将运行“grep .c”。 父进程等待子进程完成,以便子进程写入管道。

测试运行:-

bash-3.1$ ls | grep .c
1.c
hello.c
bash-3.1$ ./a.out ls grep .c
bash-3.1$

为什么会这样?

最佳答案

一个简单的错误:您的 execl 调用实际上应该是 execlp。此外,您可以去掉 waitclose 语句。然后你应该检查execlp的错误代码。

关于c - 使用 C 实现管道 ("|")(使用 fork ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2191414/

相关文章:

python - Python 子进程在什么情况下获得 SIGPIPE?

python - 管道子流程标准输出到变量

java - Gstreamer Tee/队列多流水线

c - 输出中存在字符的说明

c - 使用 llvm 提示编译器

c - 位字段是否对应于累加器中的寄存器?

linux - 如何在 debian linux 中降级 gcc?

c++ - 如何在 C 代码中访问 C++ 结构的 std::string 成员

c - 为什么 scanf() 会导致此代码中的无限循环?

templates - gcc模板继承问题