
Recall first from Reliability and watchdogs
- Graceful degradation preserves useful functions within defined limits.
- Fail-safe design defines what outputs do when normal control is unavailable.
- WatchdogSec supervises a service, while RuntimeWatchdogSec configures the system manager to feed a watchdog device.
Detect a hang from missing progress
3 min readA watchdog needs to know the service is actually alive; this lesson covers hang detection and reading core dumps.
A service blocked on a mutex can still have a PID and appear in ps while every request waits. Linux can report whether a process exists and expose thread states, but a thread sleeping while healthy can look much like a thread waiting indefinitely. The service knows what progress means. For a gateway, a useful test is whether the event loop completes an iteration and whether any outstanding request has exceeded its deadline. An idle gateway can pass both tests without receiving a packet.
Set WatchdogSec= in the service unit to specify the maximum interval between accepted notifications. Once startup completes, systemd expects the service to send WATCHDOG=1 repeatedly. A service can read the interval from the WATCHDOG_USEC environment variable and aim to notify at half that interval, leaving time for scheduling delays. Choose a timeout that allows for measured delays under normal load and still detects a stall soon enough for the application.
Here is a service configuration for a shell-based lab. Install the script below at /usr/local/bin/watchdog-demo, make it executable, and save the unit as /etc/systemd/system/watchdog-demo.service.
[Service]
Type=notify
ExecStart=/usr/local/bin/watchdog-demo
NotifyAccess=all
WatchdogSec=6s
#!/bin/bash
systemd-notify READY=1 || exit 1
for tick in 1 2 3; do
sleep 2 || exit 1
printf 'Completed cycle %s\n' "$tick"
systemd-notify WATCHDOG=1 || exit 1
done
# Simulate a work cycle that does not finish in time.
sleep 30
READY=1 tells systemd that startup is complete. The script invokes systemd-notify WATCHDOG=1 after each simulated cycle. NotifyAccess=all allows notifications from processes in the service, including the helper. In an application that sends notifications directly from its main process, NotifyAccess=main suffices. Send the notification after a meaningful health check. A separate timer thread that reports unconditionally can keep the watchdog satisfied while the worker handling requests is stuck.
After creating the unit, reload systemd's unit definitions and start the service. Inspect it after the last cycle message and the watchdog interval have elapsed.
sudo systemctl daemon-reload
sudo systemctl start watchdog-demo.service
sudo journalctl -u watchdog-demo.service -b
systemctl show watchdog-demo.service -p Result
Systemd records watchdog as the service result when the deadline expires. Its default watchdog signal is SIGABRT, which can produce a core dump if capture is available. This demo leaves the service failed so the result is easy to inspect. In a service configured with Restart=on-failure, a watchdog timeout can also trigger a restart, subject to systemd's start rate limits. When diagnosing a restarted service, use the journal to identify the failure in the earlier invocation. An abort signal in a core record can come from a watchdog or from the application itself.
Generate and read a core dump
4 min readA snapshot of selected process memory and execution state, including thread registers lets GDB inspect a process after it dies. The kernel can create one when a process terminates with the default action for a core-dumping signal such as SIGABRT or SIGSEGV. The notification in the service journal tells you why systemd acted. The dump can show where the process was executing or waiting when it received the signal.
Before running the lab, check the active routing on your Ubuntu 24.04 environment. Read /proc/sys/kernel/core_pattern with cat. A pattern beginning with | sends the dump to a user-space helper, identified by the command that follows. A file pattern directs the kernel to write a file. Ubuntu installations can be configured with a different collector, so for the coredumpctl lab use a systemd-enabled environment with the systemd-coredump package installed and confirm that the pattern names systemd-coredump. Installing the gdb package provides GDB. A saved journal record and the dump bytes have separate lifetimes, so a listed crash can outlast its stored core.
For kernel-written core files, ulimit -c shows the shell's soft core size limit, which child processes inherit. ulimit -c unlimited raises it if the hard limit permits. A system service takes its limits from systemd, where LimitCORE= can set the core size limit. Linux ignores the kernel's RLIMIT_CORE limit when piping dumps to a helper. The collector can still apply its own limits and policy, so raising the shell limit alone cannot make a piped dump appear in coredumpctl.
Save this program as crash-demo.c. The call to abort() deliberately triggers a crash while the application call chain is still present.
#include <stdlib.h>
static void fatal_error(void)
{
abort();
}
static void process_sample(void)
{
fatal_error();
}
int main(void)
{
process_sample();
return EXIT_SUCCESS;
}
gcc -Wall -Wextra -std=c17 -g -O0 -o crash-demo crash-demo.c
./crash-demo
coredumpctl list "$PWD/crash-demo"
coredumpctl info "$PWD/crash-demo"
coredumpctl debug "$PWD/crash-demo"
Run these commands from the directory containing the executable. -g records debugging information, and -O0 makes this small demo easier to trace at source level. coredumpctl info shows the matching crash metadata, including the terminating signal. coredumpctl debug opens the latest matching dump in GDB by default. Compare the time and PID with the run you intend to inspect, especially if you have crashed several builds. When the core is unavailable, check whether the collector kept the dump and whether your account can read it. A pre-existing entry for the same path can otherwise make a failed capture look successful.
At the GDB prompt, enter bt to print the selected thread's the sequence of stack frames from the current execution point back through its callers. Frame #0 is the innermost frame. For this demo, expect library frames associated with the abort. Find fatal_error, then read down through process_sample to main. Select the application frame using frame followed by its displayed number. Use list to see nearby source and info locals to inspect available local variables. In a multithreaded service, thread apply all bt shows the other stacks. For a watchdog timeout, those stacks may reveal a worker waiting on a lock or blocked in I/O. A frame identifies where execution was captured. To establish why a thread stopped making progress, relate the frame to the code and to the other threads.
Going deeperSymbols and cores from another machine
Systemd-coredump records metadata and may include a backtrace in its journal entry. GDB can use debuginfod to fetch missing debug information and source by build ID when it has debuginfod support and an appropriate server is configured. In GDB, set debuginfod enabled on enables queries to the servers configured through DEBUGINFOD_URLS. A server can only supply builds it indexes. Keep the exact application binary and matching debug information for your own builds even when a public server can resolve Ubuntu library frames.
For a board that uses systemd-coredump, select the crash on the board with coredumpctl list and run coredumpctl dump PID --output=crash.core, substituting the recorded PID and checking that the match is the intended crash. Transfer the exported file with scp, together with the exact executable or its matching unstripped build. Open them on the workstation with gdb-multiarch /path/to/executable crash.core when analysing a different supported target architecture. In GDB, set set sysroot /path/to/target-rootfs to resolve shared libraries against a copy of the target's filesystem. Use libraries from the image that produced the dump. A matching filename alone does not identify a build. Core files can contain credentials and other process data, so limit access to the exported file.
Print a backtrace before a controlled abort
2 min readSometimes the application itself detects a fatal condition, such as an invariant violation in decoded data. It can deliberately enter a crash handler while it still has ordinary control flow. That handler can print a short stack trace to standard error and then call abort(). For a systemd service whose standard error goes to the journal, the trace can be read alongside the unit's failure messages. The core remains useful for inspecting other threads and memory.
For the demo, add <execinfo.h> and <unistd.h> and replace fatal_error with the function below. backtrace() fills a bounded array with return addresses and returns the number it stored. backtrace_symbols_fd() writes those entries to the file descriptor and returns no status. Check the count before printing and call abort() even if there are no frames to print.
static void fatal_error(void)
{
void *frames[16];
int count = backtrace(frames, (int)(sizeof frames / sizeof frames[0]));
if (count > 0)
backtrace_symbols_fd(frames, count, STDERR_FILENO);
abort();
}
gcc -Wall -Wextra -std=c17 -g -O0 -rdynamic -o crash-demo crash-demo.c
./crash-demo
On Ubuntu these functions are provided by glibc. -rdynamic makes eligible executable symbols available by exporting them into the dynamic symbol table. The static functions in this demo can still appear as addresses or offsets in the printed trace. GDB can name them from the debugging information generated by -g. Compare the order of the printed entries and the application frames in bt. They capture related locations at different moments. One trace is collected inside fatal_error, and the other reflects the process at termination.
{{< callout type="warning" >}}
Call this handler directly from ordinary program code when the program detects a fatal condition. Keep backtrace() and backtrace_symbols_fd() out of asynchronous signal handlers. Their first use can load unwinding support and allocate memory.
{{< /callout >}}
“Field crash capture and signal handling” follows this lesson and explains how to collect evidence when a failure arrives as a signal, outside a controlled fatal-error path.
Key takeaways
- A systemd watchdog expires when the service stops sending accepted watchdog notifications within its configured interval.
- The kernel uses core_pattern to decide where to send a core dump.
- GDB needs the original executable and matching symbols to resolve application frames accurately.
- A controlled fatal-error handler can print a backtrace before calling abort.
Reflect
- Explain to a colleague, in two sentences: configure a systemd service to report progress with watchdog notifications.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pagecore(5): core dump files and kernel routing
- Man pageabort(3): abnormal process termination
- Man pagebacktrace(3): capture a stack backtrace
- Man pagesystemd.service(5)
- Man pagesystemd-notify(1)
Official documentation first. Links checked when the lesson was published.