简体   繁体   中英

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"?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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