LINUX下软件模拟实现看门狗定时器
如果两次调用WDG的时间超过参数S秒,返回0,否则为1。
#include<netinet/in.h> // for sockaddr_in
#include<sys/types.h> // for socket
#include<sys/socket.h> // for socket
#include<stdio.h> // for printf
#include<stdlib.h> // for exit
#include<string.h> // for bzero
#include <sys/stat.h>
#include "svr_uart.c"
/* Subtract the `struct timeval' values X and Y,
storing the result in RESULT.
Return 1 if the difference is negative, otherwise 0. */
int timeval_subtract(struct timeval *result, struct timeval *x,
struct timeval *y)
{
/* Perform the carry for the later subtraction by updating Y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* `tv_usec' is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int wdg( int s ){//0 s <0 feed
// n secondes
int ms = s*1000;
int ret;
static struct timeval st ;
static int inited=0;
if (s<0)inited=0;
if (inited==0){
inited=1;
gettimeofday(&st ,NULL);
return 1 ;
}
struct timeval cur ;
struct timeval diff ;
gettimeofday(&cur ,NULL);
timeval_subtract(&diff,&cur,&st);
double r = diff.tv_sec *1000 + ( diff.tv_usec /1000 ) ;
return (r>=ms)?0:1;
}
这里不是严格意义上的看门狗,不具备使系统复位的本领。我们使用的时候周期的调用wdg(s),其中参数s是想到到上次调用wdg所允许的时间,如果超过这个时间返回0,否则为1。
这个主要用来获悉是否在程序运行期间发生了长时间的阻塞,比如网络不通,再执行wdg(s)检测到就可以做对应的处理。
{{0112444368c89319ae97b8581b36a4f2cf1743da5a786c0da9b03cfeeac11a7b2333c82c924bf442937378c3f61efb31491d82c21e8943c6809a951d36344777a792b9fe76efc2cfb66b944ca7b8ee11239a4f904d5bf09bce74996da122895c2b69e581274c014afa6f439a36d4c67c928bcaf78250f1bd5026b2ad52d2d18232c8b5a458f82bd3427868d9fc3f55b70c3781ba9f8a642fe3f859d4f0a9950619889648a33c40952f650c8ac43b86a009f73801a3adb7d19a8eef28625bc0663fba638b1f839317}}