使用系統計時器做為制定時器
高階應用程式可以使用系統計時器做為架設程式,使作業系統在無回應時終止並重新啟動該應用程式。 當假設到期時,會產生應用程式無法處理的訊號,進而導致作業系統終止應用程式。 終止後,作業系統會自動重新開機應用程式。
若要使用標準計時器:
- 定義計時器
- 建立計時器並按住不放
- 在計時器到期之前定期重設
若要定義計時器,請建立 itimerspec 結構,並將間隔和初始到期時間設定為固定值,例如一秒。
#include <time.h>
const struct itimerspec watchdogInterval = { { 1, 0 },{ 1, 0 } };
timer_t watchdogTimer;
設定監督者的通知事件、訊號和訊號值、撥 號timer_create 來建立通知,以及撥打 timer_settime 來進行支援。 在此範例中, watchdogTimer
會提出 SIGALRM 事件。 應用程式不會處理事件,因此作業系統會終止應用程式。
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);
}