LINUX--看门狗WATCHDOG

        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;
}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值