I’m currently maintaining some web server software and I need to perform a lot of I/O operations. The read(), write(), close() and shutdown() calls, when used on a socket, may sometimes raise an ENOTCONN error. What exactly does this error mean? What are the conditions that would trigger it? I can never seem to reproduce it locally but there are users who can.
Right now I just ignore ENOTCONN when raised by close() and shutdown() because it seems harmless, but I’m not entirely sure.
EDIT:
- I am absolutely sure that the
connect()call succeeded. I check for its return value. ENOTCONNis most often raised byclose()andshutdown(). I’ve only very rarely seen aread()andwrite()raisingENOTCONN.
If you are sure that nothing on your side of the TCP connection is closing the connection, then it sounds to me like the remote side is closing the connection.
ENOTCONN, as others have pointed out, simply means that the socket is not connected. This doesn’t necessarily mean thatconnectfailed. The socket may well have been connected previously, it just wasn’t at the time of the call that resulted inENOTCONN.This differs from:
ECONNRESET: the other end of the connection sent a TCP reset packet. This can happen if the other end is refusing a connection, or doesn’t acknowledge that it is already connected, among other things.ETIMEDOUT: this generally applies only toconnect. This can happen if the connection attempt is not successful within a system-dependent amount of time.EPIPEcan sometimes be returned by some socket-related system calls under conditions that are more or less the same asENOTCONN. For example, on some systems,EPIPEandENOTCONNare synonymous when returned bysend.While it’s not unusual for
shutdownto returnENOTCONN, since this function is supposed to tear down the TCP connection, I would be surprised to seeclosereturnENOTCONN. It really should never do that.Finally, as dwc mentioned,
EBADFshouldn’t apply in your scenario unless you are attempting some operation on a file descriptor that has already beenclosed. Having a socket get disconnected (i.e. the TCP connection has broken) is not the same as closing the file descriptor associated with that socket.