简体   繁体   English

当多个进程尝试从同一管道读取时会发生什么?

[英]what happens when multiple processes try to read from the same pipe?

#include <unistd.h>
#include <stdio.h>
int main()
{
  char buff[100];
  int pfd[2];
  buff[0] = '\0';
  pipe(pfd);
  if (fork())
    write(pfd[1],"hello world", 12);
  fork();
  read(pfd[0], buff, 100);
  printf("%s\n", buff);
  printf("goodbye\n");
}

I understand that only one process will write to the pipe, but what I don't understand is could it be possible that one process reads from the pipe and reads only a part of the "hello world" and the other processes read the other parts of "hello world"? 我知道只有一个进程会写入管道,但我不了解的是,一个进程可能会从管道中读取并仅读取“ hello world”的一部分,而其他进程会读取其他部分你好世界”?

In other words, what happens when a process tries to read a pipe while another process is reading it? 换句话说,当一个进程试图读取管道而另一个进程正在读取管道时会发生什么呢?

Demons will fly from your nose! 恶魔会从你的鼻子飞出来!

Actually if they're reading from the same pipe, then they're holding file descriptors pointing to the same struct file in the kernel. 实际上,如果它们是从同一管道读取的,那么它们将持有指向内核中相同struct file This means the kernel will determine who gets the data. 这意味着内核将确定谁获取数据。 Only one process will read any given byte. 只有一个进程将读取任何给定的字节。

Most reads and writes to pipes have some guarantees regarding PIPE_BUF , you might like to look into that. 大多数对管道的读取和写入对于PIPE_BUF都有一定的保证,您可能希望对此进行研究。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM