Home > Mobile >  How to determine lost connection with kqueue?
How to determine lost connection with kqueue?

Time:07-26

I know that, here, on SO, are many questions themed like this. I've read through most of the similar questions and can not find an answer for my case.

I use kqueue for server/client socket echo application. The program uses exclusively BSD socket API. The program is work in progress. Now I am at the point of getting EOF from socket.

My setup follows.

  1. Start server, that waits for connections, and accepts one socket.
  2. Start client that connects.
  3. No user data sent by this time. Close the client with SIGINT.
  4. Server kqueue gets EOF flag with no errors.
  5. read system call returns zero with no errors.

The problem is that I get no indication that connection was fully closed. I can not determine if I have to shutdown read end, or completely close a socket. I get no indication of EOF with the write end. And that is expected, since I did not register for the write event(no data were sent by now).

How to properly tell, if the socket was fully closed?

Update

I know that what follows may belong to other post. I think that this update is tightly connected with the question, and the question will benefit as a whole.

To the point. Since I get a read EOF, but not a write EOF(the socket is closed before any data comes in, or out), can I somehow query socket for its state?

What I learned from other network related questions, here, on SO, that network stack may get some packets on a socket. Like FIN, or RST. It will be a sure win for me to just get the socket state, in the particular case.

As a second option, will it help to add one-time write event after I got a read EOF, just to get a write EOF? Will the write EOF event trigger?

I know I will get write error eventually. But, until that time, the socket will be a dead weight.

It will be of a great convenience to getsockopt for the write end close. Or, at least, queuing an event for read endpoint shutdown, after the read returned EOF.

I did not found similar getsockopt options, and I am not sure about queue'ing write event. The source code for kevent, and a network stack in general, is too tough for me. That is why I ask.

CodePudding user response:

If read or recv returns 0 then that means the other end closed the connection. It's at least a half-close for writing (from the other peer), which means there's nothing more to be received from that connection.

Unless the protocol specifies that it's only a half-close and that you can continue to send data, it's generally best to simply do a full closing of the connection from your side.

  • Related