Should a read from FIFO block after all the data w

2019-08-11 23:33发布

问题:

I'm learning about pipe programming in Linux, and am having trouble understanding pipe / FIFO management.

I wrote a small program which opens a FIFO I created (I did mkfifo newfifo in my terminal before executing the program). I then repeatedly read and dump my character buffer. I'm filling the FIFO using echo "message" > newfifo from another terminal's cmd line.

The problem is that when I write to the FIFO, I can read that data in the buffer, but then the read doesn't block anymore. My understanding was that after I read the data from the FIFO, the FIFO should be empty and the read should block. Am I thinking about this wrong, or am I incorrectly managing the FIFO?

Code is below:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>

#define NEWPIPE "./newfifo"

void main()
{
  int great_success = 0; 
  int fd;
  char buffer[20];

  fd = open(NEWPIPE, O_RDONLY);

  while (1) {
    great_success = read(fd, buffer, 20);

    if (great_success < 0) {
      printf("pipe failed\n");
    } else {
      printf("buffer : %s\n", buffer);
      printf("great_success = %d\n", great_success);
      great_success = 0;
    }
  }
}

回答1:

Your understanding of how fifos works is incorrect. They are much like pipes: if the write end is closed (the echo command has terminated), the read end will read end-of-file (EOF), i.e. return 0.

Note that when you open the fifo, it isn't read that is blocking. The blocking system call is the open() system call, as explained in http://linux.die.net/man/4/fifo



回答2:

Because the process(echo "message" > newfifo) is a short program, it terminated quickly. Once the process terminated, there is no write end for the pipe, so the read end in another process gets an EOF.



标签: c linux pipe