Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C check before writing to closed pipe

Tags:

c

pipe

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!

like image 409
Gary Avatar asked Dec 28 '22 18:12

Gary


2 Answers

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.

like image 154
mpez0 Avatar answered Jan 10 '23 08:01

mpez0


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!
like image 30
djna Avatar answered Jan 10 '23 08:01

djna