You can and it's quite easy. RPi has a Linux module that implements the standard Linux watchdog API. You can find documentation of this here.
Now, if you read this, you will know that there is a special device file called /dev/watchdog
and in order to use watchdog
you have to open this file and write some data (one byte, it's best to write something other than 'V' which I'm explaining later) to it from time to time. If you won't write anything to this file for long enough, watchdog
will trigger a reboot. You can find an example program (very simple) here.
Note that in a normal situation, if you close /dev/watchdog
, watchdog
can be disabled. There is a special mode called 'Magic Close feature' which seems to be implemented by a RPi driver but AFAIK it's not enabled in the default kernel configuration (CONFIG_WATCHDOG_NOWAYOUT option). In this case, reboot will be triggered even if you close /dev/watchdog
unless you write 'V' to it just before quitting the app.
You should test yourself if it is indeed disabled (I don't have a RPi here right now to test), but if it isn't, it's not good for you. If your application crashes, the watchdog device file will be closed and reboot won't be triggered and this is why you want it. In this situation, you can either change the kernel configuration and rebuild it or write a customized application that is going to monitor if your main application is working (using some IPC method for example).
There is also the ioctl API which allows you to do some more with watchdog
. You can, for example, set a different timeout - IOCTL with WDIOC_SETTIMEOUT (seems to be supported by the RPI driver) or get timeout - IOCTL with WDIOC_GETTIMEOUT (which also seems to be supported). You may want to use it to modify the default timeout (10 seconds). There is hard limit to 16 seconds however. Here's an example:
int timeout = 15;
int fd = open("/dev/watchdog", O_WRONLY);
ioctl(fd, WDIOC_SETTIMEOUT, &timeout);
You can also use IOCTL with WDIOC_KEEPALIVE instead of writing a character if you want. Both methods are valid.