Alex Rivera | Logout

Linux: Checking if a socket/pipe is broken without doing a read()/write()

Asked 2012-02-09T14:02:16.030
9

I have a simple piece of code that periodically writes data to a fd that's passed to it. The fd will most likely be a pipe or socket but could potentially be anything. I can detect when the socket/pipe is closed/broken whenever I write() to it, since I get an EPIPE error (I'm ignoring SIGPIPE). But I don't write to it all the time, and so might not detect a closed socket for a long time. I need to react to the closure asap. Is there a method of checking the fd without having to do a write()? I could then do this periodically if I'm not writing anything.

Edit
Report

1 Answer

10
struct pollfd pfd = {.fd = yourfd, .events = POLLERR};
if (poll(&pfd, 1, whatever) < 0) abort();
if (pfd.revents & POLLERR) printf("pipe is broken\n");

This does work for me. Note that sockets are not exactly pipes and thus show different behavior (-> use POLLRDHUP).

answered 2012-02-09T15:22:46.020

Your Answer