Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 717
gimmeamilk Avatar asked Feb 09 '12 14:02

gimmeamilk


People also ask

How do you test whether a socket is ready to be read or written?

To test whether any sockets are ready for reading, use either FD_ZERO() or memset(), if the function was dynamically allocated, to initialize the fdset bit set in readlist and invoke FD_SET() for each socket to test. A socket is ready for writing if there is buffer space for outgoing data.

What is Brokenpipe error?

A broken Pipe Error is generally an Input/Output Error, which is occurred at the Linux System level. The error has occurred during the reading and writing of the files and it mainly occurs during the operations of the files.

What causes a broken pipe error in Linux?

Answer: The Linux error 32 broken pipe indicates that the listener process could not create a dedicated server process to hand the client request. This error is caused by a resource exhaustion issue, either within the OS or within the Oracle instance.

How do you fix a broken pipe error?

This kind of error can easily be fixed with a command like “sudo apt install –f”. On rare occasions, you may have experienced a broken pipe error. A pipe in Linux / Unix connects two processes, one of them has read-end of the file and the other one has the write-end of the file.


1 Answers

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).

like image 131
jørgensen Avatar answered Sep 23 '22 00:09

jørgensen