How to prevent SIGPIPEs (or handle them properly)

前端 未结 10 1704
名媛妹妹
名媛妹妹 2020-11-22 07:27

I have a small server program that accepts connections on a TCP or local UNIX socket, reads a simple command and (depending on the command) sends a reply.

The problem

10条回答
  •  耶瑟儿~
    2020-11-22 08:08

    Handle SIGPIPE Locally

    It's usually best to handle the error locally rather than in a global signal event handler since locally you will have more context as to what's going on and what recourse to take.

    I have a communication layer in one of my apps that allows my app to communicate with an external accessory. When a write error occurs I throw and exception in the communication layer and let it bubble up to a try catch block to handle it there.

    Code:

    The code to ignore a SIGPIPE signal so that you can handle it locally is:

    // We expect write failures to occur but we want to handle them where 
    // the error occurs rather than in a SIGPIPE handler.
    signal(SIGPIPE, SIG_IGN);
    

    This code will prevent the SIGPIPE signal from being raised, but you will get a read / write error when trying to use the socket, so you will need to check for that.

提交回复
热议问题