views:

115

answers:

4

I am trying to write 2 server/client programs under Linux, in which they communicate through named pipes. The problem is that sometimes when I try to write from the server into a pipe that doesn't exist anymore (the client has stopped), I get a "Resource temporarily unavailable" error and the server stops completely.

I understand that this is caused by using a O_NONBLOCK parameter when opening the fifo chanel, indicating the point where the program would usually wait until it could write again in the file, but is there a way to stop this behavior, and not halt the entire program if a problem occurs (shouldn't the write command return -1 ad the program continue normally)?

And another strange thing is that this error only occurs when running the programs outside the ide (eclipse). If I run both programs inside eclipse, on error the write function just returns -1 and the programs continues normally.

A: 

maybe you can just wrap it into a "try..catch" statement?

zed_0xff
tried it... didn't work
Dumitru Catalin
Linux does not throw C++ exceptions...
Nikko
+1  A: 

The problem with this undefined behaviour is strange, you could have a memory problem somewhere or you missed a test. ( or Eclipse does something special to handle signals? )

Nikko
The problem is definitely with the write function. I've put 2 "perror"'s before and after the write call... and only the first is showing, thus the program exists on the "write" function call. I forgot to mention that when the client closes, it also deletes the file from disk, so the remaining file descriptors from the server points towards... nothing.
Dumitru Catalin
@Dumitru: Without any code to prove what you're saying, this answer seems like the best bet, especially considering all the behaviour you've described in the question.
James Morris
You should test with Platypus solution, but the behaviour is strange
Nikko
+6  A: 

If you wish that write() to returns -1 on error (and set errno to EPIPE) instead of stopping your server completly when the write end of your pipe is unconnected, you must ignore the SIGPIPE signal with signal( SIGPIPE, SIG_IGN ).

Platypus
Thank you... I just tested it and it worked.
Dumitru Catalin
A: 

To quote the section 2 man page for write: "[errno=]EPIPE An attempt is made to write to a pipe or a FIFO that is not open for reading by any process, or that has only one end open (or to a file descriptor created by socket(3SOCKET), using type SOCK_STREAM that is no longer connected to a peer endpoint). A SIGPIPE signal will also be sent to the thread. The process dies unless special provisions were taken to catch or ignore the signal." [Emphasis mine].

As Platypus said you'll need to ignore the SIGPIPE signal: signal(SIGPIPE, SIG_IGN). You could also catch the signal and handle the pipe disconnection in a different way in your server.

Mark B