Vivek Sharma
Vivek Sharma

Reputation: 3814

How to write a simple WatchDog Timer in C on linux?

TCP KEEPALIVE timer has a default duration of 2 hrs.
What are the best practices for knowing that a TCP connection/socket is down asap --

Usually what do you do after you detect if the socket/connection has gone dead.

Upvotes: 3

Views: 3050

Answers (1)

Mat
Mat

Reputation: 206719

There is no way to detect that a TCP connection is dead "ASAP". If the host on the other side is dead, it's not participating in the TCP connection dialog anymore, and the only way of noticing that is a timeout on the connection.

You can lower the keepalive time on the socket to "notice" the problem earlier, but that's not a good solution generally.

If you're trying to monitor the host, send short "ping" messages at whatever frequency suits you. If the other side doesn't answer within a given interval, you can declare it "dead".

Once you've noticed a dead connection, closing the socket is sufficient to free all kernel resources associated with that socket.

If you have other resources allocated along side that (session information for instance), you need to free those as well. It's indeed a good idea to write a function for that (and for allocating those resources when you make the connection), so that all that book-keeping is in the same spot and easy to inspect.

How you keep track of the resources allocated is entirely up to you. Holding a reference to all the "to be freed" resources in one struct, and saving that struct in a linked list or hash (indexed by the socket fd for instance) can work out pretty well.

(The term "watchdog timer", in Linux anyway, is used for hardware monitoring devices. That's not a good term to search for for networking/TCP related things.)

Upvotes: 4

Related Questions