watchdog
看门狗,又叫watchdog timer,是一个定时器电路,一般有一个输入,叫喂狗或踢狗;一个输出到MCU 的 RST 端,MCU 正常工作的时候,每隔一段时间输出一个信号到喂狗端,给 WDT 清零,如果超过规定的时间不喂狗(一般在程序跑飞时),WDT 定时超过,就会给出一个复位信号到 MCU,使 MCU 复位。防止 MCU 死机。
整体思路
- 内核模块初始化watchdog控制寄存器并使能watchdog
- 用户看门狗进程定时踢狗
一、用户空间代码分析
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <sys/time.h> #include <signal.h> #include <errno.h> #include <stdarg.h> static void die(const char *msg, ...) { va_list ap; va_start(ap, msg); fprintf(stderr, "%s: ERROR: ", "watchdog"); vfprintf(stderr, msg, ap); va_end(ap); exit(1); } static void watchdog_write_pidfile(void) { char pidfile[80]; char pidbuf[16]; int fd; int ret; snprintf(pidfile, sizeof(pidfile), "/var/run/%s.pid", "watchdog"); fd = open(pidfile, O_RDONLY); if (fd < 0) { if (errno != ENOENT) { die("watchdog_write_pidfile: opening pidfile %s for read: %s ", pidfile, strerror(errno)); } /* ENOENT is good: the pidfile doesn't exist */ } else { /* the pidfile exists: read it and check whether the named pid is still around */ int pid; char *end; ret = read(fd, pidbuf, sizeof(pidbuf)); if (ret < 0) { die("watchdog_write_pidfile: read of pre-existing %s failed: %s ", pidfile, strerror(errno)); } pid = strtol(pidbuf, &end, 10); if (*end != '