mikeizbicki / ucr-cs100

open source software construction course
Other
486 stars 407 forks source link

checking if the read end of the pipe is empty or not #1647

Closed mchen046 closed 9 years ago

mchen046 commented 9 years ago

In the man page for pipe(7) man 7 pipe, it states that

If a process attempts to read from an empty pipe, then read(2) will block until data is available.

What exactly does block mean in this context? It seems that my program waits infinitely at the read() syscall. In order to prevent the program from stalling, is there a way to check if the read end of the pipe is empty or not before calling read()?

Update:

I found this response from http://stackoverflow.com/questions/13811614/c-how-to-see-if-a-pipe-is-empty that solved my problem:

Since the pipe() function does not allow you to set non-blocking mode, you have to do that after the pipe >is created with fcntl() and F_GETFL and F_SETFL plus O_NONBLOCK

and from http://pubs.opengroup.org/onlinepubs/007908775/xsh/read.html:

When attempting to read from an empty pipe or FIFO:

  • If some process has the pipe open for writing and O_NONBLOCK is set, read() shall return -1 and set errno to [EAGAIN].`
mikeizbicki commented 9 years ago

All of these assignments were intended to work with blocking IO. I suspect you have bugs if you used non-blocking IO. But if it works, then that's fine.