The user wants to implement a "watchdog timer" in C.
This is a system-level concept, often involving hardware interaction or specific operating system calls.
1. Understanding the Concept:
What is a Watchdog Timer (WDT)? It's a hardware or software timer that triggers a system reset or corrective action if the main program neglects to refresh it periodically (often called "petting" or "kicking" the dog). It's used to detect and recover from computer malfunctions.
Context: The implementation depends heavily on the environment:
Bare-metal/Embedded: Direct register access.
Linux: Using the /dev/watchdog interface (hardware watchdog) or software watchdogs via signals/timers.
General Algorithm (Software simulation): A separate thread checking a flag updated by the main thread.
2. Determining the Scope of the Answer:
Since the user just asked "Implement a watchdog timer in C" without specifying the platform (embedded vs. Linux vs. generic OS), I should provide the most common and practical approaches:
Approach 1: Linux Hardware Watchdog (The standard userspace interface). This is the most likely scenario for a general C programmer working on a system like Raspberry Pi or an embedded Linux device.
Approach 2: Bare-metal/AVR/STM32 (Embedded). This is crucial for microcontroller developers. I should provide a generic pseudo-code or an AVR example as it's very popular.
Approach 3: Pure Software Simulation (Multithreaded). This demonstrates the logic without needing specific hardware or root permissions, using pthread and signals.
3. Drafting the Content - Section by Section:
Introduction: Briefly explain the concept (Main loop kicks the dog; if it hangs, the dog bites -> reset).
Scenario A: Linux Hardware Watchdog (/dev/watchdog)
Mechanism: Open the device file. Write to it to keep it alive. ioctl for magic closes.
Mechanism: One thread does the work and updates a timestamp. A monitor thread checks the timestamp. If the time difference exceeds the limit, the monitor kills the process (or triggers a callback).
Code Structure:
Shared variable (atomic or mutex-protected).
pthread_create.
Monitor loop: check_time(), exit(1) if failed.
Main loop: update_time().
4. Refining the Code Examples:
Linux Example: Needs error handling. perror is useful. The magic close character 'V' is a specific Linux kernel detail important to mention.
Embedded Example: I'll use AVR (Arduino style logic) as it's the most readable for C beginners, but clarify it depends on the specific MCU registers.
Software Example: Use standard C11 threads (threads.h) or POSIX threads (pthread.h). pthread is more widely available on older systems. Let's stick to pthread as it's the industry standard for C on Unix-like systems. I need a shared time_t or volatile int.
5. Review and Safety Checks:
Safety: Watchdogs cause resets. I should warn the user that running the Linux example might reboot their machine if they have a hardware watchdog loaded.
Permissions: Accessing /dev/watchdog usually requires root.
6. Structuring the Final Output:
Title: Implementation in C.
Category 1: Linux (Userspace Hardware Watchdog). (Detailed code).
Best Practices: Timeout selection, critical sections, magic close.
Self-Correction during drafting:
Initial thought: Should I write a driver?
Correction: No, that's too complex. Stick to userspace implementation.
Initial thought: Should I use signals?
Correction: Signals are tricky. Using SIGALRM is a valid software watchdog approach (alarm goes off, handler kills process). I should mention this as a "Software Watchdog" alternative to threads because it's simpler. Let's provide the thread approach as it separates the "watcher" logic more clearly from the main flow, but maybe mention signals briefly. Actually, the /dev/watchdog approach is the "real" way to do it on Linux systems. I will focus primarily on that.
Final Polish:
Make sure code compiles (mentally check headers: fcntl.h, unistd.h, sys/ioctl.h, linux/watchdog.h).
Let's write the response.
Linux Implementation: Focus on WDIOC_KEEPALIVE.
Embedded: Focus on wdt_reset().
(Self-Correction on Software Watchdog):
The prompt asks to "reset the system".
A software watchdog usually can only kill the process, not the whole system, unless it triggers a kernel panic or hardware interaction.
I must clarify that distinction. The Linux /dev/watchdogdoes reset the system. The software simulation only kills the app.
Plan:
Explain the two main contexts: Hardware (OS managed) vs. Firmware (Bare metal).
Provide a Linux implementation using /dev/watchdog.
Provide an Embedded implementation (Generic/AVR).
Briefly explain a pure software logic (Process monitoring).
Let's go.
The implementation of a watchdog timer (WDT) depends heavily on whether you are writing bare-metal embedded firmware (like for a microcontroller) or a userspace application in an operating system like Linux.
Here are the implementations for both scenarios.
Scenario 1: Linux Userspace (Hardware Watchdog)
In Linux, hardware watchdog timers are exposed as character devices, typically /dev/watchdog. The standard way to interact with them is using ioctl commands defined in <linux/watchdog.h>.
The Logic:
Open the device.
Set a timeout (e.g., 10 seconds).
Start a background thread (the "keeper").
The keeper thread writes a "magic close" character (V) or calls WDIOC_KEEPALIVE periodically (usually half the timeout time) to prevent the reset.
If your main program crashes or hangs, the keeper thread stops writing, the timer expires, and the hardware resets the system.
c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/watchdog.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#define WDT_DEVICE "/dev/watchdog"
#define TIMEOUT_SEC 10
#define KEEPALIVE_INTERVAL 5
// Global flag to stop the watchdog thread on clean exit
static volatile int keep_running = 1;
// Thread function to pet the watchdog
void *watchdog_thread_func(void *arg) {
int fd = *(int *)arg;
while (keep_running) {
// "Pet" the dog. Writing dummy data triggers a keepalive
// in most standard watchdog drivers.
if (write(fd, "\0", 1) < 0) {
perror("Watchdog write failed");
} else {
printf("Watchdog petted successfully.\n");
}
sleep(KEEPALIVE_INTERVAL);
}
return NULL;
}
int main() {
int fd;
int flags;
pthread_t wdt_thread;
// 1. Open the Watchdog device
fd = open(WDT_DEVICE, O_WRONLY);
if (fd == -1) {
perror("Failed to open watchdog device");
exit(EXIT_FAILURE);
}
// 2. Set the Timeout
// Note: Hardware limitations may round this up or down
if (ioctl(fd, WDIOC_SETTIMEOUT, &TIMEOUT_SEC) < 0) {
perror("Could not set timeout");
// Not fatal, maybe the driver uses a default
} else {
printf("Timeout set to %d seconds.\n", TIMEOUT_SEC);
}
// 3. Start the Keepalive Thread
if (pthread_create(&wdt_thread, NULL, watchdog_thread_func, &fd) != 0) {
perror("Failed to create thread");
close(fd);
exit(EXIT_FAILURE);
}
// --- Main Application Logic ---
printf("Application running. Press Ctrl+C to simulate crash (reset).\n");
printf("If the program exits normally, we will close the dog safely.\n");
// Simulate work
for (int i = 0; i < 20; i++) {
printf("Working... %d\n", i);
sleep(1);
}
// ------------------------------
// 4. Clean Shutdown (Magic Close)
// If we don't do this, the driver will assume we crashed and reset
// the system even though we closed the file descriptor.
printf("Shutting down safely...\n");
keep_running = 0;
pthread_join(wdt_thread, NULL);
// Write 'V' to disable the watchdog before closing
if (write(fd, "V", 1) < 0) {
perror("Failed to write magic close character");
}
close(fd);
return 0;
}
On a microcontroller, you interact directly with hardware registers. The concept is the same: initialize a timer counter, and reset it inside your main loop.
Below is a generic example typical of AVR (Arduino) or STM32 HAL libraries.
c
#include <avr/wdt.h> // Specific header for AVR microcontrollers
void setup() {
// 1. Initialize Hardware (Serial, Sensors, etc.)
Serial.begin(9600);
Serial.println("System Starting...");
// 2. Enable the Watchdog Timer
// Configuration: Reset after 2 seconds of inactivity
// This is often a specific register write sequence in datasheets
wdt_enable(WDTO_2S);
}
void loop() {
// --- Task 1: Read Sensor ---
// If this hangs, the loop stops, the dog barks (resets).
read_sensor();
// 3. Pet the Dog
// Resets the timer counter to 0
wdt_reset();
// --- Task 2: Process Data ---
process_data();
// 4. Pet the Dog again if the loop is long
wdt_reset();
delay(100);
}
Important Safety Rules
The "Magic Close" (Linux): If you are testing the Linux code, simply exiting the program or closing the file descriptor is not enough to stop the countdown. You must write the character 'V' (magic close) to the file descriptor before closing it. If you don't, the system will reboot even if your program finished successfully.
Timing: You must pet the dog more frequently than the timeout. A good rule of thumb is to pet it at half the timeout interval (e.g., if timeout is 10s, pet every 5s).
Hardware Limitations: In Linux, the driver creates a /dev/watchdog device. You usually need root permissions (sudo) to run the program.
Simulating a Crash: To test if it works, simply add an infinite while(1); loop in your main code and stop petting the dog. The system should reboot after the timeout expires.