在 Linux 中使用 pipe() 链接管道 [英] chained pipes in linux using pipe()

查看:58
本文介绍了在 Linux 中使用 pipe() 链接管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know how to create one pipe in Linux with C that looks like cat /tmp/txt |grep foo, but I have problems implementing multiple chained pipes like this cat /tmp/1.txt | uniq -c | sort. How to do it with C using pipe() in Linux?

更新:我想通了.如果有人有同样的问题,这里是代码:

UPDATE: I've figured it out. Here's the code if anybody ever have the same question:

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

推荐答案

一个管道有两端(读和写)和 pipe() 相应地将两个文件描述符放入您指定的数组中.第一个是读端,第二个是写端.

A pipe has two ends (read and write) and pipe() accordingly puts two file descriptors in the array you specify. The first one is the read end, and the second one the write end.

因此,在您的示例中,您将创建两个管道:

So, in your example, you would create two pipes and:

  • cat的标准输出连接到第一个管道的写端,
  • uniq的标准输入连接到第一个管道的读取端,
  • uniq的标准输出连接到第二个管道的写端,
  • sort 的标准输入连接到第二个管道的读取端.
  • connect the standard output of cat to the write end of the first pipe,
  • connect the standard input of uniq to the read end of the first pipe,
  • connect the standard output of uniq to the write end of the second pipe,
  • connect the standard input of sort to the read end of the second pipe.

这篇关于在 Linux 中使用 pipe() 链接管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆