Using select on FIFO's

Bjorn Larsen blarsen at spider.uio.no
Thu May 30 17:07:32 AEST 1991


Yesterday, I wanted to use select(2) to wait on a number of FIFO's
that were opened for reading. It turned out to be harder than I
expected.

Originally, the program opened the FIFO's with O_NONBLOCK, and tried
to read them occationally. It turns out that select() on such a file
descriptor returns immediately, indicating that the fd was ready.  In
a sense, that is true -- the fd is ready so far that I can take a
read() on it without blocking. But what I expected select() to do was
to tell me wether there was data on the FIFO, not wether it is
possible to issue a read() on the fd.

The program is a deamon, and the FIFO's will be opened and written to
by other programs every once in a while. So opening the FIFO's for
blocking read isn't such a hot idea eigther; it will cause the daemon
to block, waiting for a process to open the FIFO for writing.

So I came up with the following 'solution':

	int fd, wfd;

/* Open the FIFO for nonblocking read */
	fd = open("/tmp/FIFO", O_RDONLY|O_NONBLOCK);

/* Open the FIFO for write (won't hang, since it is open for read) */
	wfd = open("/tmp/FIFO", O_WRONLY);

/* Close the read descriptor */
	close(fd);

/* Open the FIFO for blocking read */
	fd = open("/tmp/FIFO", O_RDONLY);

After these acrobatics, the file descriptor 'fd' can be used with
select().

It seems to work OK, but is this the 'right' way to do this?
Are there any sideeffects of this that I haven't thought about?
And is there a more elegant way to go about it?


---
Bjorn.Larsen at usit.uio.no                        "Specialization is for insects"
University Centre for Information Technology                     - Lazarus Long
University of Oslo, Norway



More information about the Comp.unix.programmer mailing list