c - 使用管道的两个进程的环

标签 c unix pipe

我有这个管道和 dup 使用的例子。它应该创建一个由管道连接的两个进程组成的环。这是代码:

#include <unistd.h>

#define READ 0
#define WRITE 1

main (int argc, char *argv[]) {
 int fd[2];
 pipe(fd); //first call to pipe
 dup2(fd[READ],0);
 dup2(fd[WRITE],1);
 close(fd[READ]);
 close(fd[WRITE]);
 pipe(fd); //second call to pipe

 if (fork()==0) {
    dup2(fd[WRITE],1);
 } else
    dup2(fd[READ],0);

 close(fd[READ]);
 close(fd[WRITE]);
}

从“两个进程的环”我了解到,进程A的输出连接到进程B的输入,进程B的输出连接到进程A的输入。

在第一次调用 pipe 和连续两次调用 dup2 之后,我认为标准输入和输出被重定向到我的新管道的输入和输出。

然后,第二次调用 pipe 使我感到困惑,因为我认为它覆盖了我以前的 fd 值。此时标准输入输出是怎么回事?

最后,fork 调用:

child 是否将标准输出重定向到管道?

父级是否将标准输入重定向到管道?

我在这里看不到戒指。

我希望我说清楚了,因为我真的很困惑。

非常感谢!!

最佳答案

好吧,让我们假设您是从终端启动这件事的。那么你有:

file 0 (stdin)  = terminal keyboard
file 1 (stdout) = terminal screen
file 2 (stderr) = terminal screen

现在你运行 pipe(fd),你有:

file 0-2 = as before
file 3 (fd[0]) = read end of pipe 1
file 4 (fd[1]) = write end of pipe 1

现在运行前两个 dup2 和前两个 close:

file 0 = read end of pipe 1
file 1 = write end of pipe 1
file 2 = still terminal screen
file 3-4 = now closed

现在你制作一个新的管道:

file 0-2 as before
file 3 (fd[0]) = read end of pipe 2
file 4 (fd[1]) = write end of pipe 2

现在你 fork 了。在子进程中,您调用 dup2(fd[1],1) 并关闭两个 fd(您的来源在这里不太正确):

file 0: read end of pipe 1
file 1: write end of pipe 2
file 2: terminal screen
file 3-4: closed

在您调用 dup2(fd[0],0) 的父进程中,再次关闭两个 fd 给它:

file 0: read end of pipe 2
file 1: write end of pipe 1
file 2: terminal screen
file 3-4: closed

所以我们让父进程将其标准输出写入管道 1,子进程从中读取其标准输入。类似地,我们让父进程从管道 2 读取其标准输入,子进程将其标准输出写入管道 2。即,两个进程的环。

我总是被告知这种安排很容易出现死锁。我不知道更现代的 Unix 是否也是如此,但值得一提。

关于c - 使用管道的两个进程的环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6288241/

相关文章:

在 C 中创建一个管道

c - 在带有结构数组的结构内部使用 qsort() 不会访问正确的元素而是 0

linux - 符号 -、< 和 > 是什么意思?

c - 尝试将 char[] 存储到 char* 时出现问题

linux - $*在shell脚本中是什么意思

c - 无法通过 unix tcp 套接字发送二进制数据

linux - find -exec mv 命令发生了什么

c - UNIX 编程、fork 分屏、exec 以及与管道通信

c - 删除数组中元素的函数如何工作?

c - 在哪里使用 volatile ?