Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 831 of 93611. Introduction to Embedded LinuxFree lesson

Implementing Watchdog Timers for System Reliability

Integrate watchdog system calls to automatically reset the embedded system in the event of software hangs or hardware freezes.

In this lesson, you will learn how to leverage the Linux Watchdog API to create a "fail-safe" mechanism that automatically reboots your system if your application stops responding.

The Watchdog Philosophy

In embedded Linux, the watchdog is a hardware timer that expects a "heartbeat" from user space. If your application hangs due to a deadlock, infinite loop, or resource exhaustion, it stops sending this heartbeat. Once the timer reaches zero, the hardware triggers a system reset. This is critical for remote or inaccessible devices where a manual power cycle isn't possible.

Integrating the Watchdog Interface

In Linux, the watchdog is exposed as a character device, usually located at /dev/watchdog. To integrate this into your system, your application must perform three distinct operations using the ioctl system call:

  1. Opening the Device: You open /dev/watchdog like any other file. As long as this file descriptor remains open, the kernel monitors your process.
  2. Setting the Timeout: You define how long the system can go without a heartbeat before a reset occurs.
  3. The "Kicking" Process: You must periodically write to the device to "kick" or "ping" the dog, resetting the timer.

Here is a simplified implementation:

#include <fcntl.h>
#include <unistd.h>
#include <linux/watchdog.h>
#include <sys/ioctl.h>

int main() {
    int fd = open("/dev/watchdog", O_WRONLY);
    
    // Set timeout to 15 seconds
    int timeout = 15;
    ioctl(fd, WDIOC_SETTIMEOUT, &timeout);

    while (1) {
        // Feed the watchdog
        ioctl(fd, WDIOC_KEEPALIVE, NULL);
        sleep(5); // Sleep shorter than timeout
    }
    close(fd);
    return 0;
}

Critical Considerations

Notice the use of WDIOC_KEEPALIVE. If your main loop hangs, the sleep function will never finish, the ioctl will never be called, and the system will reboot once the timer expires.

It is vital that you do not call the "kick" command inside a signal handler or a thread that might also become blocked. The best practice is to ensure your heartbeat is tied directly to the health of your primary application logic, confirming that all critical tasks have completed their cycle before refreshing the timer.

Key Takeaway: A watchdog timer acts as a hardware-level safety net, ensuring your system recovers from software freezes by requiring a periodic heartbeat signal via the /dev/watchdog character device.