Linux comes with a watchdog implementation for monitoring system running, including a kernel watchdog module and a user space watchdog program. The kernel watchdog module communicates with the user space through the/dev/watchdog character device. Once a user space program opens the/dev/watchdog device (also known as "Open the door and put the dog"), it will enable a one-minute timer (default system time) in the kernel. After that, the user space program needs to ensure that data is written to the device within one minute (commonly known as "regular dog Feed"), and each write operation will lead to a reset of the timer. If the user space program does not write in 1 minute, the timer will cause a system
Reboot operation ). Through this mechanism, we can ensure that the core processes of the system are running for most of the time. Even if the process crashes in certain circumstances, the system cannot "Feed the dog" regularly ", the Linux system restarts (reboot) with a watchdog, and the core process runs again. Mostly used in embedded systems.
Open the/dev/watchdog device ("open the door and open the dog "):
int fd_watchdog = open("/dev/watchdog", O_WRONLY);if(fd_watchdog == -1) {int err = errno;printf("\n!!! FAILED to open /dev/watchdog, errno: %d, %s\n", err, strerror(err));syslog(LOG_WARNING, "FAILED to open /dev/watchdog, errno: %d, %s", err, strerror(err));}
Write Data to the/dev/watchdog device at intervals ("regular dog Feed "):
//feed the watchdogif(fd_watchdog >= 0) {static unsigned char food = 0;ssize_t eaten = write(fd_watchdog, &food, 1);if(eaten != 1) {puts("\n!!! FAILED feeding watchdog");syslog(LOG_WARNING, "FAILED feeding watchdog");}}
Disable the/dev/watchdog device. Generally, this step is not required:
close(fd_watchdog);
Required header file:
#include <unistd.h>#include <sys/stat.h>#include <syslog.h>#include <errno.h>