LINUX--看门狗WATCHDOG
程序员文章站
2022-07-12 10:20:08
...
linux硬件看门狗,只需打开/dev/watchdog设备操作就可以。如果dev目录下没有看门狗设备,则需要去内核配置打开看门狗相应功能。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/signal.h>
#define WATCHDOG_IOCTL_BASE 'W'
#define WDIOC_SETOPTIONS _IOR(WATCHDOG_IOCTL_BASE, 4, int)
#define WDIOC_SETTIMEOUT _IOWR(WATCHDOG_IOCTL_BASE, 6, int)
#define WDIOC_KEEPALIVE _IOR(WATCHDOG_IOCTL_BASE, 5, int)
#define WDIOC_GETTIMEOUT _IOR(WATCHDOG_IOCTL_BASE, 7, int)
#define WDIOS_DISABLECARD 0x0001 /* Turn off the watchdog timer */
#define WDIOS_ENABLECARD 0x0002 /* Turn on the watchdog timer */
int wdt_fd = -1;
int WatchdogStop(void)
{
if (wdt_fd == -1){
printf("WatchdogStop fail to open watchdog device\n");
return -1;
}
int option = WDIOS_DISABLECARD;
ioctl(wdt_fd, WDIOC_SETOPTIONS, &option);
if (wdt_fd != -1){
close(wdt_fd);
wdt_fd = -1;
}
return 0;
}
int WatchdogOpen(void)
{
wdt_fd = open("/dev/watchdog", O_WRONLY);
if (wdt_fd == -1){
printf("fail to open watchdog device %d\n",wdt_fd);
}
return wdt_fd;
}
int WatchdogSetTimeout(int time)
{
if (wdt_fd == -1){
printf("WatchdogSetTimeout fail to open watchdog device\n");
return -1;
}
ioctl(wdt_fd, WDIOC_SETTIMEOUT, &time);
return 0;
}
int WatchdogSetKeepAlive(void)
{
if (wdt_fd == -1){
printf("WatchdogKeepAlive fail to open watchdog device\n");
return -1;
}
ioctl(wdt_fd, WDIOC_KEEPALIVE, 0);
return 0;
}
void psdk_watch_dog_get_timeout(int *time)
{
ioctl(wdt_fd, WDIOC_GETTIMEOUT, &time);
}
void *WatchdogExit(void)
{
WatchdogStop();
exit(0) ;
}
int main(int argc, char* argv[])
{
int time=5;
long long itime=0;
char ctrltype[32]={0};
if(argc > 1){
strcpy(ctrltype,argv[1]);
printf("ctrl:%s\n",ctrltype);
}else{
printf("===================\n");
printf("watchdog [start/stop] [time]\n");
printf("===================\n");
return -1;
}
signal(SIGINT, WatchdogExit);
if(strcmp("stop",ctrltype)==0){
WatchdogOpen();
WatchdogStop();
return 0;
}else if(strcmp("start",ctrltype)==0){
if(argc == 3)
{
char times[32]={0};
strcpy(times,argv[2]);
time = atoi(times);
}
printf("timeout:%ds\n",time);
}else{
printf("===================\n");
printf("watchdog [start/stop] [time]\n");
printf("===================\n");
return -1;
}
WatchdogOpen();
if(time > 0){
WatchdogSetTimeout(time);
}else{
printf("WatchdogSetTimeout err\n");
return -1;
}
itime = (time*1000*1000)/2;
while(1)
{
WatchdogSetKeepAlive();
usleep(itime);
}
return 0;
}