使用系统计时器作为看门程序
高级应用程序可以使用系统计时器作为监视程序,使 OS 在应用程序无响应时终止并重启该应用程序。 当监视器过期时,它会引发一个信号,指示应用程序无法处理,这反过来又会导致 OS 终止应用程序。 终止后,OS 会自动重启应用程序。
若要使用监视器计时器,请:
- 定义计时器
- 创建并武装计时器
- 在计时器过期之前定期重置计时器
若要定义计时器,请创建 itimerspec 结构,并将间隔和初始到期时间设置为固定值,例如 1 秒。
#include <time.h>
const struct itimerspec watchdogInterval = { { 1, 0 },{ 1, 0 } };
timer_t watchdogTimer;
设置监视程序的通知事件、信号和信号值,调用 timer_create 创建它,并调用 timer_settime 来武装它。 在此示例中, watchdogTimer
引发 SIGALRM 事件。 应用程序不处理事件,因此 OS 终止应用程序。
void SetupWatchdog(void)
{
struct sigevent alarmEvent;
alarmEvent.sigev_notify = SIGEV_SIGNAL;
alarmEvent.sigev_signo = SIGALRM;
alarmEvent.sigev_value.sival_ptr = &watchdogTimer;
int result = timer_create(CLOCK_MONOTONIC, &alarmEvent, &watchdogTimer);
result = timer_settime(watchdogTimer, 0, &watchdogInterval, NULL);
}
在应用程序代码中的其他位置,定期重置监视器。 一种方法是使用第二个计时器(其周期短于 watchdogInterval
),以验证应用程序是否按预期运行,如果是,则重置监视器计时器。
// Must be called periodically
void ExtendWatchdogExpiry(void)
{
//check that application is operating normally
//if so, reset the watchdog
timer_settime(watchdogTimer, 0, &watchdogInterval, NULL);
}