How it works...

We need a mechanism to terminate our application when it hangs. Though we could spawn a special monitoring thread or process, there is another, simpler way to do this—POSIX signals.

Any process running in a POSIX operating system can receive a number of signals. To deliver a signal to the process, the operating system stops the normal execution of the process and invokes a corresponding signal handler. 

One of the signals that can be delivered to the process is called alarm and, by default, its handler just terminates the application. This is exactly what we need to implement a watchdog.

The constructor of our Watchdog class accepts one parameter, seconds:

Watchdog(std::chrono::seconds seconds):

It is a time interval for our watchdog and it is immediately passed into the feed method to activate the watchdog timer:

feed();

The feed method invokes a POSIX function alarm that sets the timer. If the timer is already set, it updates it with a new value:

void feed() {
alarm(seconds.count());
}

Finally, we invoke the same alarm function in the destructor to disable the timer by passing a value of 0:

alarm(0);

Now, each time we invoke the feed function, we shift the time when the process will receive the alarm signal. If, however, we do not invoke this function before the timer expires, it triggers the alarm handler, which terminates our process.

To check it out, we've created a simple example. It is a loop that has 10 iterations. On each iteration, we display a message and sleep for a specific interval. The interval is initially 700 ms and on each iteration, it increases by 300 ms; for example, 700 ms, 1,000 ms, 1,300 ms, and so on:

delay += 300ms;

Our watchdog is set to a 2-second interval:

Watchdog watchdog(2s);

Let's run the application and check how it works. It produces the following output:

As we can see, the application was terminated after the sixth iteration, after the delay exceeded the watchdog interval. Moreover, since it was terminated abnormally, its return code is non-zero. If the application is spawned by another application or script, this is an indicator that the application needs to be restarted.

The watchdog technique is a simple and efficient way to build robust embedded applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.22.169