使用 pipe() 在 linux 中链接管道

标签 c linux pipe

我知道如何在 Linux 中使用 C 创建一个看起来像 cat/tmp/txt |grep foo 的管道,但是我在实现多个链式管道时遇到了问题,例如 cat/tmp/1.txt | uniq-c |排序。如何在 Linux 中使用 pipe() 用 C 实现?

更新:我已经弄明白了。如果有人有同样的问题,这里是代码:

enum PIPES {
    READ, WRITE
};


 int filedes[2];
    int filedes2[2];
    pipe(filedes);
    pipe(filedes2); 

    pid_t pid = fork();
    if (pid == 0) {
        dup2(filedes[WRITE], 1);
    char *argv[] = {"cat", "/tmp/1.txt", NULL};
        execv("/bin/cat", argv); 
        exit(0);
    } 
    else {
        close(filedes[1]);
    }

    pid = fork();
    if (pid == 0) {
    dup2(filedes[READ], 0);
    dup2(filedes2[WRITE], 1);
        char *argv[] = {"uniq", "-c", NULL};
        execv("/usr/bin/uniq", argv);       
    }
    else {
        close(filedes2[1]);
    }

    pid = fork();
    if (pid == 0) {
        dup2(filedes2[READ], 0);
        char *argv1[] = {"sort", NULL};
            execv("/usr/bin/sort", argv1);
    }

    waitpid(pid);

最佳答案

你得到一对文件描述符 - 我们称它们为 ab。对 pipe 的后续调用会为您提供文件描述符 cd

因此,您将 b 连接到 c 以链接这两个进程。创建另一对文件描述符并将 d 连接到 e,等等。

关于使用 pipe() 在 linux 中链接管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8300301/

相关文章:

c - 如果 parent 不调用 wait(),则同一 parent 的两个 child 不会使用管道进行通信

Python、管道和命令行中的 "-c"选项

c - 如何在输入端检测破损的管道?

php - 防止程序执行其他程序

php - 如何保护 PHP 文件的敏感信息?

检查字符串是否存在于未初始化的字符串数组中

c - 生成的 shell 在缓冲区溢出后迅速终止

Linux 邮件命令密件抄送多个地址?

javascript - ffi 模块 node.js 错误未捕获错误 : Dynamic Linking Error: Win32 error 193

c - 使用具有结构的指针 C 的选择排序