看门狗
1 看门狗是什么
在由单片机构成的微型计算机系统中,由于单片机的工作常常会受到来自外界电磁场的干扰,造成各种寄存器和内存的数据混乱,会导致程序指针错误,不在程序区,取出错误的程序指令等,都有可能会陷入死循环,程序的正常运行被打断,由单片机控制的系统无法继续正常工作,导致整个系统的陷入停滞状态,发生不可预料的后果。
看门狗,又叫 watchdog,从本质上来说就是一个定时器电路,一般有一个输入和一个输出,其中输入叫做喂狗,输出一般连接到另外一个部分的复位端,一般是连接到单片机。 看门狗的功能是定期的查看芯片内部的情况,一旦发生错误就向芯片发出重启信号。看门狗命令在程序的中断中拥有最高的优先级。
2 有什么用
比如程序中存在试调过程中没有发现的BUG,导致系统死机了,看门狗会将系统重启。
3 简单总结
watchdog 是一个定时器,若将其启用(open),则需要每隔一段时间进行一次喂狗指令
例子:
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#define WATCHDOG_FILE_PATH "/dev/watchdog"
#define DEFAULT_TIMEOUT 3
static int feed_time = DEFAULT_TIMEOUT-1; /* 单位:(秒) 每过多久,喂一次狗 */
static int timeout = DEFAULT_TIMEOUT; /* 单位:(秒) 超时时间,多长时间没有喂狗,就会重启 */
static int fd = -1;
static int watchdog_open(void)
{
if(fd >= 0)
{
printf("watch dog have been opened.\n");
return 0;
}
/* 打开设备 */
fd = open(WATCHDOG_FILE_PATH, O_RDONLY);
if(fd < 0)
{
printf("open watch dog fail.");
return -1;
}
/* 设置时间 */
ioctl(wdt_fd, WDIOC_SETTIMEOUT, &timeout);
printf("the watch dog timeout was set to %d seconds\n", timeout);
}
/* 看门狗喂狗线程 */
static void watchdog_thread(void)
{
while(1)
{
if (ioctl(wdt_fd, WDIOC_KEEPALIVE, &feed_time))
{
printf("feed fail.\n");
}
sleep(timeout);
}
}
/*************************************************************************
* @brief 初始化看门狗
**************************************************************************/
int watchdog_init(void)
{
/* 打开设备 */
watchdog_open();
pthread_t watchdog_thread_id;
pthread_create(&watchdog_thread_id, NULL, watchdog_thread, NULL);
}