C – How to write a simple watchdog timer in C on Linux?

How to write a simple watchdog timer in C on Linux?… here is a solution to the problem.

How to write a simple watchdog timer in C on Linux?

THE DEFAULT DURATION OF THE TCP KEEPALIVE TIMER IS 2 HOURS.
Learn as soon as possible what are the best practices for TCP connection/socket closure

  • Is implementing a WatchDog timer the best way to solve the problem?

  • How do I implement a watchdog timer to do this?
    I’ve browsed extensively (probably I’m using the wrong search parameters) but I haven’t seen any such implementation of linux GPOS, all I’ve seen are some hardware-based embedded system timers that are hardware related.

What you usually do after detecting if a socket/connection is dead.

  • Do you want to turn off only socket_descriptor?
  • Does closing socket_descriptor release all kernel resources associated with that connection?
  • How do I release all resources associated/allocated in user space? You write routines, do. If so, how do you keep track of the resources you allocate in user space?

Solution

A

TCP connection drop could not be detected “as soon as possible”. If the host on the other end hangs, it no longer participates in the TCP connection conversation, and the only way to notice this is if the connection times out.

You can shorten the hold event time on the socket to “notice” the problem earlier, but this is usually not a good solution.

If you are trying to monitor the host, send a short “ping” message at a frequency that suits you. If the other person does not answer within the given time interval, you can declare it “dead.”

Once you notice a dead connection, closing the socket is enough to free all kernel resources associated with that socket.

If you also allocate other resources, such as session information, you also need to release them. It’s really a good idea to write a function for this (and allocate those resources when the connection is established) so that all the bookkeeping is in the same place and easy to check.

How you track assigned resources is entirely up to you. Holding references to all “to be released” resources in a struct and keeping that structure in a linked list or hash (e.g. indexed by socket fd) works well.

(The term “watchdog timer,” in Linux anyway, is used for hardware monitoring devices.) This is not a good term for searching for network/TCP related things. )

Related Problems and Solutions