When my code is in a blocking recv call, if the other side reboots, then this side recv call doesn’t get to know about it and just goes into a hung state.
How to avoid this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
By default, if the other side of the connection disappears without terminating the connection properly, the OS on your side has no way of knowing that no further data will be coming. That’s why
recv()will block forever in this situation.If you want to have a timeout, then set the socket to non-blocking and use
select()to wait for it to become readable.select()allows you to specify a timeout.Alternatively, you can set the
SO_KEEPALIVEsocket option withsetsockopt(). This will enable the sending of TCP “keepalives”, that will allow your side to detect a stale connection. (Do note that with the default settings, it can take a long time to detect that the connection has gone).