1

I've created a FIFO (with mkfifo()) and I need to wait till some process writes data several times into it. I've written the following code: (ignore the bad style, it's to keep the example concise)

int count = 0, read = 0;
while(count < 2) {
    read = read(fd, buf, BUFFER_SIZE);
    if(read > 0) {
        //do work...
        count++;
    }
}

In an attempt to avoid busy waiting, I've added the following line:

int count = 0, read = 0;
while(count < 2) {
    sleep(2);
    read = read(fd, buf, BUFFER_SIZE);
    if(read > 0) {
        //do work...
        count++;
    }
}

(fd is the FIFO's descriptor)
However I really don't like it, it looks artificial. Is there a better way doing it?

sel
  • 483
  • 5
  • 16

1 Answers1

0

Normally, if you have not opened the fifo with the O_NONBLOCK flag, read blocks till data is available for reading. So "sleep(2);" statement is not necessary. Also the "if(read > 0) " check is still required because of situations like the writing end of fifo has been closed or the read call has returned because it has been interrupted by a signal (errno = EINTR).

kjohri
  • 1,166
  • 11
  • 10