tags:

views:

176

answers:

2

Is there an easy way to check if a pipe is closed before writing to it in C? I have a child and parent process, and the parent has a pipe to write to the child. However, if the child closes the pipe and the parent tries to read - I get a broken pipe error.

So how can I check to make sure I can write to the pipe, so I can handle it as an error if I can't? Thanks!

+2  A: 

How about just try to write and deal with the error? The same way you would for a write to a file or a database. I see no value in the idiom:

check if *this* is going to work
do *this*

You merely introduce a smaller, and harder to catch in testing, window of opportunity:

check if *this* is going to work
   child thinks "Ha, fooled you, I'm off now!"
do *this*, which now fails!
djna
+3  A: 

A simple way to check would be to do a 0 byte write(2) to the pipe and check the return. If you're catching SIGPIPE or checking for EPIPE, you get the error. But that's just the same as if you go ahead and do your real write, checking for the error return. So, just do the write and handle an error either in a signal handler (SIGPIPE) or, if the signal is ignored, by checking the error return from write.

mpez0
this seems to be the easiest way, thanks!
Gary