Skip to content

Instantly share code, notes, and snippets.

@hacst
Created June 5, 2018 23:18
Show Gist options
  • Save hacst/ee12cd91167aa55b19444fc74c91a8e8 to your computer and use it in GitHub Desktop.
Save hacst/ee12cd91167aa55b19444fc74c91a8e8 to your computer and use it in GitHub Desktop.

Revisions

  1. hacst created this gist Jun 5, 2018.
    5 changes: 5 additions & 0 deletions CMakeLists.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    cmake_minimum_required(VERSION 2.8)
    project(sdnotify)

    add_executable(sdnotify sdnotify.cpp)
    target_link_libraries(sdnotify PUBLIC systemd)
    33 changes: 33 additions & 0 deletions sdnotify.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    #include <systemd/sd-daemon.h>
    #include <stdio.h>
    #include <unistd.h>

    int main()
    {
    setbuf(stdout, NULL);

    uint64_t watchdogIntervalInUs;
    const bool watchdog = sd_watchdog_enabled(0, &watchdogIntervalInUs) > 0; // Service WatchdogSec must be set for this to return > 0
    if (watchdog) {
    printf("Watchdog is enabled with %lu us\n", watchdogIntervalInUs);
    } else {
    printf("Not running in a watchdog env\n");
    return 1;
    }

    // To be able to use sd_notify at all have to set service NotifyAccess (e.g. to main)
    sd_notify(0, "READY=1"); // If service Type=notify the service is only considered ready once we send this (this is independent of watchdog capability)
    printf("Notified as ready. Now sleeping with watchdog\n");

    //usleep(watchdogIntervalInUs * 2); // Should get the process killed

    int i = 0;
    while(true) {
    usleep(watchdogIntervalInUs / 2); // Recommended reporting interval is half the watchdog interval
    sd_notify(0, "WATCHDOG=1");
    sd_notifyf(0, "STATUS=Watchdog notify count %d", i); // Visible in systemctl status
    ++i;
    }

    return 0;
    }
    9 changes: 9 additions & 0 deletions sdnotify.service
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    [Unit]
    Description=Just a test for watchdogs etc

    [Service]
    ExecStart=/path/to/binary/sdnotify
    Type=notify
    NotifyAccess=main
    WatchdogSec=5s
    Restart=on-failure