7

I have a server/client app on a Linux box. If the server is not up when the client attempts to send a request, I get a SIGPIPE and the application terminates.

How can I check if the server is available on the socket before I try to write?

Also of note, I do not want to trap the SIGPIPE because the client is really part of a shared object that is used by many applications that may or may not already define their own signal handling methods.

Thanks

steveo225
  • 11,394
  • 16
  • 62
  • 114
  • You can forbid local unix sockets. SIGPIPE is only generate for this type of socket. But that may hurt performance (a lot). – Šimon Tóth Mar 21 '11 at 20:06
  • 2
    You get SIGPIPE for inet stream sockets as well. – Erik Mar 21 '11 at 20:07
  • Would it be easier to do it "out-of-band", so to speak? E.g. have a `/var/run/server.pid` file or something that the client could check to see if the server was alive. – Ilkka Mar 21 '11 at 20:13
  • 1
    @Ilkka: You'd just introduce a race condition and make the error more rare. – Erik Mar 21 '11 at 20:15
  • 1
    I suggest changing the question title to something more descriptive. Maybe "How to handle SIGPIPE from a library without interfering with the main program" – Zan Lynx Mar 21 '11 at 23:36
  • Another SO post might be useful: http://stackoverflow.com/questions/108183/how-to-prevent-sigpipes-or-handle-them-properly – ukhardy Mar 21 '11 at 20:06

2 Answers2

7

Pass MSG_NOSIGNAL as flags to send()

Erik
  • 88,732
  • 13
  • 198
  • 189
0

This post by kroki describes what seems to be a good method.

To summarize it:

  • Check if SIGPIPE is pending. Record that in a variable. If it is pending before we even start then someone else blocked SIGPIPE. In that case skip all the signal stuff below and just do the write.
  • sigblock SIGPIPE.
  • Do the write.
  • Check if SIGPIPE is pending.
  • If it is pending then sigtimedwait for it with zero timeout.
  • Unblock SIGPIPE.
Zan Lynx
  • 53,022
  • 10
  • 79
  • 131