您的位置:首页 > 其它

添加看门狗程序

2016-07-21 09:25 309 查看
在嵌入式系统中,为了防止主应用程序因为不明的原因无故死掉或者程序跑飞,需要加入一个看门狗程序保证系统能够重启(reboot)。

//Linux watch dog test

//http://www.cnblogs.com/zengjfgit/p/5396041.html

/***********************************************************************
*                  Linux Watchdog Test Program
* 说明:
*     由于之前的reset一直没有得到解决,所以这个Watchdog功能一直没有处理,
* 现在问题解决了,于是需要加入这个测试程序。
*
**********************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/watchdog.h>

#define  ZERO 0
#define  SUCCESS 0
#define  FAIL   1

#define     DDBUG                                 1
#undef      DDBUG
#if DDBUG
#define DEBUG_PRINT(fmt, args...) fprintf(stdout, fmt, ##args)
#else
#define DEBUG_PRINT(fmt, args...)
#endif

// watchdog 只要一直打开设备节点不喂,然后等待设定的时间结束引发reset。
int main(void)
{

int fd_watchdog;
fd_watchdog = open("/dev/watchdog", O_WRONLY); //open device
if (fd_watchdog == -1) {
fprintf(stderr, "Watchdog device not enabled.\n");
fflush(stderr);
exit(-1);
}

int timeout = 60;  //60seconds
const int wdt_enable = WDIOS_ENABLECARD;
ioctl(fd_watchdog, WDIOC_SETOPTIONS, (void*)&wdt_enable);  //open watchdog
ioctl(fd_watchdog, WDIOC_SETTIMEOUT, &timeout);
DEBUG_PRINT("The timeout was set to %d seconds\n", timeout);

while(1){

{
ioctl(fd_watchdog, WDIOC_GETTIMEOUT, &timeout);
printf("The timeout was is %d seconds.\n", timeout);
}

int timeleft = timeout - 10;
//while((timeleft--) >= 0) {
//    //DEBUG_PRINT("The timeout left %d seconds\n", timeleft);
//    sleep(1);
//}

mysleep(timeleft);

if( SUCCESS == checkProcessExist("miniTerminal")) // Only when miniTerminal is running, will we feed the watchdog
{
////feed the watchdog
if(fd_watchdog >= 0) {
feeddog(fd_watchdog);
}
}

sleep(10);
}
}

void mysleep(int timelength){
while((timelength--) >= 0) {
//DEBUG_PRINT("The timeout left %d seconds\n", timeleft);
sleep(1);
}

return;
}

void feeddog(int fd_watchdog)
{
//ioctl(fd_watchdog, WDIOC_KEEPALIVE, 0);
static unsigned char food = 0;
ssize_t eaten = write(fd_watchdog, &food, 1);
if(eaten != 1) {
DEBUG_PRINT("\n!!! FAILED feeding watchdog\n");
//syslog(LOG_WARNING, "FAILED feeding watchdog");
}

fsync(fd_watchdog);  // if you don't fsync fd_watchdog, then the write won't function normally.
return;
}

int checkProcessExist(char *name)
{
//char *Name = "miniTerminal";
FILE *pstr;
char cmd[100];
char number[10];

int ret = SUCCESS;

memset(cmd, 0 , sizeof(cmd));
sprintf(cmd,"ps | grep %s | grep -v grep | wc -l",name);
pstr=popen(cmd,"r");

fgets(number,9, pstr);
DEBUG_PRINT("number is %d\n",atoi(number));

if( ZERO == atoi(number))
{
DEBUG_PRINT("process - %s not exist!\n",name);
ret = FAIL;
}
else
{
DEBUG_PRINT("process - %s exist!\n",name);
ret = SUCCESS;
}

pclose(pstr);
return ret;

}


设置看门狗的超时时间为80秒,如果在80秒以内检测到程序存在,则喂狗;否则,不喂狗,等待系统reboot。测试,OK。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: