Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 796
Matoe Avatar asked Jan 30 '13 00:01

Matoe


People also ask

Is a pipe bidirectional?

Portability notes On some systems (but not Linux), pipes are bidirectional: data can be transmitted in both directions between the pipe ends. POSIX. 1 requires only unidirectional pipes. Portable applications should avoid reliance on bidirectional pipe semantics.

What does Mkfifo create named pipe?

The named pipe is created with the mkfifo system call. A named pipe is much like a traditional pipe, created with the pipe system call. However, while pipe provides access via two file descriptors, the named pipe is accessed via the filesystem at a path. #include <sys/types.


1 Answers

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.

like image 87
Fox Avatar answered Oct 31 '22 11:10

Fox