Search code examples
cfile-descriptorfifoposix-select

FIFO pipe is always readable in select()


In C pseudo-code:

while (1) {
    fifo = open("fifo", O_RDONLY | O_NONBLOCK);
    fd_set read;
    FD_SET(fifo, &read);
    select(nfds, &read, NULL, NULL, NULL);
}

The process sleeps as triggered by select() until another process writes into fifo. Afterwards it will always find fifo as a readable file descriptor.

How to avoid this behavior (that is, after fifo has been read once, how to make it be found as unreadable until it gets another write?)


Solution

  • You opened that FIFO as read only (O_RDONLY), whenever there is no writer to the FIFO, the read end will receive an EOF.

    Select system call will return on EOF and for every EOF you handle there will be a new EOF. This is the reason for the observed behavior.

    To avoid this open that FIFO for both reading and writing (O_RDWR). This ensures that you have at least one writer on the FIFO thus there wont be an EOF and as a result select won't return unless someone writes to that FIFO.