#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #include <errno.h> #include <sys/time.h> #include <unistd.h> #include <time.h> #include <getopt.h> #include <sys/signal.h> #include <termios.h> struct watchdog_info{ unsigned int options; //options the card/driver supprots 19 unsigned int firmware_version; //firmcard version of the card unsigned char identity[32]; //identity of the board 21 }; #define WATCHDOG_IOCTL_BASE 'W' #define WDIOC_GETSUPPORT _IOR(WATCHDOG_IOCTL_BASE, 0, struct watchdog_info) #define WDIOC_SETTIMEOUT _IOWR(WATCHDOG_IOCTL_BASE, 6, int) #define WDIOC_GETTIMEOUT _IOR(WATCHDOG_IOCTL_BASE, 7, int) 27 #define WDIOS_DISABLECARD 0x0001 /* Turn off the watchdog timer */ #define WDIOS_ENABLECARD 0x0002 /* Turn on the watchdog timer */ #define WDIOC_SETOPTIONS _IOR(WATCHDOG_IOCTL_BASE, 4, int) #define WDIOC_KEEPALIVE _IOR(WATCHDOG_IOCTL_BASE, 5, int) int Getch (void) //無回顯的從屏幕輸入字符,來達到喂狗的目的 { int ch; struct termios oldt, newt; //終端設備結構體 tcgetattr(STDIN_FILENO, &oldt); //獲得終端屬性 newt = oldt; newt.c_lflag &= ~(ECHO|ICANON); //設置無回顯屬性 tcsetattr(STDIN_FILENO, TCSANOW, &newt); //設置新的終端屬性 ch = getchar(); //從鍵盤輸入一個數據 tcsetattr(STDIN_FILENO, TCSANOW, &oldt); //恢復終端設備初始設置 return ch; } //suspend some seconds int zsleep(int millisecond) { unsigned long usec; usec=1000*millisecond; usleep(usec); //睡眠usec秒 } int Init() { int fd; //open device file fd = open("/dev/watchdog",O_RDWR); //打開看門狗設備 if(fd < 0) { printf("device open fail\n"); return -1; } return fd; } int main(int argc,char **argv) { int fd,ch; int i,j; char c; struct watchdog_info wi; fd=Init(); //打開終端看門狗設備 //讀板卡信息,但不常用 ioctl(fd,WDIOC_GETSUPPORT,&wi); printf("%d,%s\n",wi.options,wi.identity); //讀看門狗溢出時間,默認是5s //重新設置時間為10s i=5; printf("%d\n",ioctl(fd,WDIOC_SETTIMEOUT,&i)); //讀新的設置時間 printf("%d\n",ioctl(fd,WDIOC_GETTIMEOUT,&i)); printf("%d\n",i); //看門狗開始和停止工作,打開和關閉設備具有同樣的功能 //關閉 i=WDIOS_DISABLECARD; printf("%d\n",ioctl(fd,WDIOC_SETOPTIONS,&i)); //打開 i=WDIOS_ENABLECARD; printf("%d\n",ioctl(fd,WDIOC_SETOPTIONS,&i)); while(1) { zsleep(100); if((c=Getch())!=27){ //輸入如果不是ESC,就喂狗,否則不喂狗,到時間后系統重啟 ioctl(fd,WDIOC_KEEPALIVE,NULL); //write(fd,NULL,1); //同樣是喂狗 } } close(fd); //關閉設備 return 0; }
