1. 得到系统中soft dog的信息
# modinfo softdog
filename: /lib/modules/3.2.0-4-686-pae/kernel/drivers/watchdog/softdog.ko
2. 加载模块
# insmod /lib/modules/3.2.0-4-686-pae/kernel/drivers/watchdog/softdog.ko
3. 此刻可见/dev/watchdog, 或创建
# mknod /dev/watchdog c 10 130
4. 查看dev并赋予权限
# ls -l /dev/watchdog
crw------- 1 root root 10, 130 Mar 21 16:27 /dev/watchdog# chmod o+rw /dev/watchdog
5. 测试使用watch dog
简单可写为:
# echo 0 > /dev/watchdog ///从此刻起计时,启用watchdog
# echo -n V > /dev/watchdog ///停用watchdog
6. 硬件与软件watchdog的区别
硬件watchdog必须有硬件电路支持, 设备节点/dev/watchdog对应着真实的物理设备, 不同类型的硬件watchdog设备由相应的硬件驱动管理。软件watchdog由一内核模块softdog.ko 通过定时器机制实现,/dev/watchdog并不对应着真实的物理设备,只是为应用提供了一个与操作硬件watchdog相同的接口。
硬件watchdog比软件watchdog有更好的可靠性。 软件watchdog基于内核的定时器实现,当内核或中断出现异常时,软件watchdog将会失效。而硬件watchdog由自身的硬件电路控制, 独立于内核。无论当前系统状态如何,硬件watchdog在设定的时间间隔内没有被执行写操作,仍会重新启动系统
看门狗是混杂设备,所以主设备号是10,/include/linux/miscdevice.h 中定义他的次设备号为130
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 5 #include <sys/types.h> 6 #include <sys/stat.h> 7 #include <fcntl.h> 8 #include <termios.h> 9 #include <errno.h> 10 #include <signal.h> 11 #include <time.h> 12 #include <pthread.h> 13 #include <sys/time.h> 14 #include <linux/watchdog.h> 15 #include <sys/ioctl.h> 16 17 time_t backTime; 18 struct tm *pBackTime; 19 int wt_fd; 20 21 static void sigAlarm(int sig) 22 { 23 char flag = ‘0‘; 24 (void)time(&backTime); 25 pBackTime= localtime(&backTime); 26 printf("day: %d; hour: %d; min: %d; sec: %d\n", pBackTime->tm_mday, pBackTime->tm_hour, pBackTime->tm_min, pBackTime->tm_sec); 27 28 write(wt_fd, &flag, 1); //Reset Watchdog 喂狗 29 alarm(2); 30 return; 31 } 32 33 34 int main() 35 { 36 char flag = ‘V‘; 37 int ret; 38 int timeout = 42; 39 40 if(SIG_ERR == signal(SIGALRM, sigAlarm)) 41 { 42 perror("signal (SIGALARM) error"); 43 } 44 45 wt_fd = open("/dev/watchdog", O_RDWR); 46 if(wt_fd <= 0) 47 { 48 printf("Fail to open watchdog device!\n"); 49 } 50 else 51 { 52 write(wt_fd,NULL,0); 53 printf("Turn on Watch Dog\n"); 54 ret = ioctl(wt_fd, WDIOC_SETTIMEOUT, &timeout); 55 if(EINVAL == ret) 56 { 57 printf("EINVAL Returned\n"); 58 } 59 else if(EFAULT == ret) 60 { 61 printf("EFAULT Returned\n"); 62 } 63 else if(0 == ret) 64 { 65 printf("Set timeout %d secs success\n", timeout); 66 } 67 else 68 { 69 printf("Ret %d\n", ret); 70 } 71 } 72 73 alarm(3); 74 75 while(1); 76 77 write(wt_fd, &flag, 1); 78 printf("Turned off Watch Dog\n"); 79 close(wt_fd); 80 return 0; 81 }
http://blog.sina.com.cn/s/blog_69a04cf401016gz4.html