Skip to content
Visual explainer 3h to learn 5 steps

Running programs as systemd services

Ship a foreground program as a systemd service with logging, restarts and sandboxing.

By Invicly Tech, , in Linux System Programming. About 12 minutes to read.

Topic 39 of 42

In short

systemd starts, supervises and restarts services described by unit files. Modern daemons simply run in the foreground, log to stdout or stderr, and leave backgrounding, journaling, restarts and sandboxing to systemd. Type=notify lets your program tell systemd exactly when it is ready.

Explained simply

systemd is the first program Linux starts at boot, and it manages every service after that. You describe your program in a small text file called a unit file: what command to run, which user to run as, when to restart it. systemd does the rest.

This makes your program simpler. It does not need to fork into the background, write a PID file or manage log files. It just runs normally and prints messages to standard output. systemd keeps it in the background and sends every line to the journal, where journalctl can search it.

If the program crashes, systemd can start it again after a short pause. If you change the config, systemctl reload can tell the program to re-read it. And with a few extra lines in the unit file, systemd can lock the program inside a sandbox: read-only system folders, no access to home directories, no way to gain more privileges.

Your program can also tell systemd exactly when it is ready to serve, so other services that depend on it start at the right moment.

Press Play on a diagram to walk through it one step at a time.

SequenceService lifecycle under systemd
Admin
systemd
Your service
journald
  1. 1systemctl start chatd
    Admin to systemd: systemctl start chatd
  2. 2fork and exec ExecStart inside a cgroup
    systemd to Your service: fork and exec ExecStart inside a cgroup
  3. 3sd_notify READY=1 (Type=notify)
    Your service to systemd: sd_notify READY=1 (Type=notify)
  4. 4stdout and stderr lines become journal entries
    Your service to journald: stdout and stderr lines become journal entries
  5. 5systemctl reload chatd
    Admin to systemd: systemctl reload chatd
  6. 6SIGHUP: re-read configuration
    systemd to Your service: SIGHUP: re-read configuration
  7. 7systemctl stop chatd
    Admin to systemd: systemctl stop chatd
  8. 8SIGTERM, then SIGKILL after the timeout
    systemd to Your service: SIGTERM, then SIGKILL after the timeout
LayersWhat a hardened unit takes away
  1. 1
    Your program

    Runs in the foreground, logs to stdout

  2. 2
    Identity

    DynamicUser, no new privileges, few capabilities

  3. 3
    Filesystem

    ProtectSystem=strict, ProtectHome, PrivateTmp

  4. 4
    Kernel interface

    Address families and system call filter

  5. 5
    Resources

    MemoryMax, TasksMax, CPU limits in the cgroup

In depth

Choosing the service Type

Type= tells systemd how to know your service has started. Type=simple (the default when ExecStart is set) treats the service as started right after the fork, before your program even runs. If the binary is missing, systemctl start still reports success. Type=exec waits until execve has succeeded, so a typo in the path makes start fail visibly; it is a good default for new units (systemd 240 and later).

Type=notify waits until the program sends READY=1 over the notification socket. Use it when startup takes time (loading data, opening a port) and other units must not start too early. Type=notify-reload (systemd 253 and later) also uses notifications for reloads.

Type=forking is for classic daemons that fork themselves: systemd waits for the parent to exit and finds the main process, ideally from PIDFile=. Type=oneshot is for scripts that run and finish, like a migration step; combine it with RemainAfterExit=yes if the unit should count as active afterwards.

MapWhen does systemd consider the service started?
Type=
  • simple
    • Right after fork
    • Missing binary still looks started
  • exec
    • After execve succeeds
    • Good default for new units
  • notify
    • When the program sends READY=1
    • Best for slow startups
  • forking
    • When the parent process exits
    • Legacy daemons, use PIDFile=
  • oneshot
    • When the command finishes
    • Setup scripts and jobs

Logging to the journal

systemd connects the service's stdout and stderr to journald. Each line becomes one journal entry, tagged with the unit name, PID and time. No log files, no rotation code. Read them with journalctl -u chatd, follow live with -f, filter by level with -p warning, or by time with --since "10 min ago".

To give a line a priority, start it with a syslog level in angle brackets: a line beginning with <3> is logged as an error, <4> as a warning, <6> as info. Lines without a prefix get the default level, info.

One trap catches almost everyone: when stdout is not a terminal, C stdio switches to full buffering. Your log lines then sit in a 4 KiB buffer and appear in the journal minutes late, or are lost when the process is killed. Call setvbuf(stdout, NULL, _IOLBF, 0) at startup for line buffering, or write logs to stderr, which is unbuffered.

  • journalctl -u chatd -f follows the log
  • journalctl -u chatd -p err -b shows errors since boot
  • setvbuf(stdout, NULL, _IOLBF, 0) or log to stderr

Restarts, reload and stop

Restart=on-failure restarts the service when it exits with a non-zero code, is killed by a signal, or times out; Restart=always also restarts after a clean exit. RestartSec=2 waits 2 seconds before each attempt. To avoid endless crash loops, systemd stops trying when a unit starts more than StartLimitBurst times (default 5) within StartLimitIntervalSec (default 10 s); these two go in the [Unit] section.

For reload, set ExecReload=/bin/kill -HUP $MAINPID and handle SIGHUP in the program: set a flag in the handler (or use signalfd) and re-read the configuration in the main loop. If the new config is invalid, keep the old one and log an error.

systemctl stop sends SIGTERM to every process in the service's cgroup (the default KillMode=control-group), waits TimeoutStopSec (90 seconds by default), and then sends SIGKILL. So handle SIGTERM: stop accepting, finish or drop in-flight work, flush, and exit 0 quickly.

FlowWhat systemctl stop does
  1. 1
    ExecStop, if set

    Optional command to ask nicely

  2. 2
    SIGTERM

    Sent to the service's processes

  3. 3
    Wait

    Up to TimeoutStopSec, default 90 s

  4. 4
    SIGKILL

    Anything still running is killed

  5. 5
    Unit inactive

    cgroup is empty, ExecStopPost runs

Sandboxing with a few lines

systemd can apply many kernel security features without changing your code. DynamicUser=yes runs the service as a temporary user that exists only while it runs. ProtectSystem=strict makes the whole filesystem read-only for the service, except API filesystems like /dev, /proc and /sys; grant write access only where needed with StateDirectory=chatd (creates /var/lib/chatd), RuntimeDirectory=chatd (/run/chatd), LogsDirectory= or ReadWritePaths=. ProtectHome=yes hides /home, /root and /run/user, and PrivateTmp=yes gives the service its own /tmp.

NoNewPrivileges=yes stops setuid programs from raising privileges. CapabilityBoundingSet= removes capabilities, and AmbientCapabilities=CAP_NET_BIND_SERVICE lets a non-root service bind port 80. RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX blocks other socket types, and SystemCallFilter=@system-service allows only the system calls a typical service needs. MemoryMax= and TasksMax= cap resources.

systemd-analyze security chatd scores the unit from 0 (locked down) to 10 (exposed) and lists what is still open. Add options one by one and test after each.

  • ProtectSystem=strict + StateDirectory= for writable data
  • AmbientCapabilities=CAP_NET_BIND_SERVICE for ports below 1024
  • systemd-analyze security name.service shows the exposure score

Readiness with sd_notify

With Type=notify, systemd sets the NOTIFY_SOCKET environment variable to the path of a Unix datagram socket. The program sends short text messages to it. The easiest way is libsystemd: include systemd/sd-daemon.h, link with -lsystemd, and call sd_notify(0, "READY=1") once the program can really serve, for example after bind and listen succeeded. It returns a positive number on success, 0 if NOTIFY_SOCKET is not set (so the same binary works outside systemd), and a negative error code on failure.

Other useful messages: STATUS=Serving 42 clients shows up in systemctl status. STOPPING=1 says shutdown has begun. RELOADING=1 marks a reload in progress. With WatchdogSec=30 in the unit, the program must send WATCHDOG=1 regularly (at least every 30 seconds, ideally every 15); if it hangs and stops sending, systemd treats the service as failed and can restart it.

The protocol is simple enough to implement without the library, and the systemd-notify command does the same from shell scripts.

SequenceType=notify startup and watchdog
systemd
Service
Dependent unit
  1. 1exec with NOTIFY_SOCKET set
    systemd to Service: exec with NOTIFY_SOCKET set
  2. 2load config, bind, listen
    Service to Service: load config, bind, listen
  3. 3READY=1
    Service to systemd: READY=1
  4. 4start units ordered After= this one
    systemd to Dependent unit: start units ordered After= this one
  5. 5STATUS=Serving 42 clients
    Service to systemd: STATUS=Serving 42 clients
  6. 6WATCHDOG=1 every 15 s
    Service to systemd: WATCHDOG=1 every 15 s

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Write a simple service unit file~35m
  2. 2
    Log to stdout for journald~35m
  3. 3
    Configure Restart and reload on SIGHUP~35m
  4. 4
    Add sandboxing like ProtectSystem~35m
  5. 5
    Notify readiness with sd_notify~35m

Key points

  • Do not fork in your program; use Type=simple, exec or notify.
  • Restart=on-failure with RestartSec gives automatic recovery.
  • Handle SIGTERM for a clean shutdown within TimeoutStopSec.
  • Sandboxing options like ProtectSystem=strict, PrivateTmp and NoNewPrivileges cut the attack surface.
  • systemd-analyze security rates how exposed a unit is.

Key terms

Tap a card to flip it. 0/6 known

Examples

ini
[Unit]
Description=Chat server
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/usr/local/bin/chatd --port 7000
Restart=on-failure
DynamicUser=yes
ProtectSystem=strict
NoNewPrivileges=yes

[Install]
WantedBy=multi-user.target

/etc/systemd/system/chatd.service; enable with systemctl enable --now chatd.

A hardened, restartable notify service

This extends the explainer's unit. Type=notify makes start wait for READY=1. Restart and RestartSec recover from crashes, and the [Unit] start limit stops crash loops. ExecReload sends SIGHUP. DynamicUser=yes also switches on ProtectSystem=strict, ProtectHome=read-only, PrivateTmp and NoNewPrivileges, so the service gets a read-only system with one writable state directory, plus the right to bind port 80 and only the usual socket types and system calls. After installing it: systemctl daemon-reload, systemctl enable --now chatd, then systemd-analyze security chatd.

ini
[Unit]
StartLimitIntervalSec=60
StartLimitBurst=5

[Service]
Type=notify
ExecStart=/usr/local/bin/chatd --port 80 --data /var/lib/chatd
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=2
DynamicUser=yes
StateDirectory=chatd
AmbientCapabilities=CAP_NET_BIND_SERVICE
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
SystemCallFilter=@system-service

[Install]
WantedBy=multi-user.target

The C side: ready, reload and clean stop

The program matches the unit above. Step 1: install SIGHUP and SIGTERM handlers that only set flags, which is async-signal-safe. Step 2: make stdout line-buffered so each log line reaches the journal at once. Step 3: after setup, send READY=1. Step 4: in the main loop, reload on the flag and exit cleanly on SIGTERM. Build with gcc chatd.c -lsystemd. In a real server the loop is epoll_wait, which returns EINTR when a signal arrives.

c
#include <signal.h>
#include <stdio.h>
#include <systemd/sd-daemon.h>
#include <unistd.h>
static volatile sig_atomic_t reload, stop;
static void on_sig(int s) { if (s == SIGHUP) reload = 1; else stop = 1; }
int main(void) {
  struct sigaction sa = { .sa_handler = on_sig }; sigemptyset(&sa.sa_mask);
  if (sigaction(SIGHUP, &sa, NULL) < 0 || sigaction(SIGTERM, &sa, NULL) < 0) return 1;
  setvbuf(stdout, NULL, _IOLBF, 0);               /* one journal entry per line, now */
  sd_notify(0, "READY=1");                        /* after load_config, bind, listen */
  while (!stop) {
    if (reload) { reload = 0; puts("reloading config"); /* load_config(); */ }
    sleep(1);                                       /* stands in for epoll_wait */
  }
  sd_notify(0, "STOPPING=1"); puts("stopped cleanly"); return 0;
}

Quick reference

  • Unit files go in /etc/systemd/system; run systemctl daemon-reload after edits
  • systemctl enable --now name starts it and enables it at boot
  • Type=exec reports a bad ExecStart path; Type=notify waits for READY=1
  • Restart=on-failure + RestartSec=2; crash-loop limits live in [Unit]
  • ExecReload=/bin/kill -HUP $MAINPID and handle SIGHUP in the program
  • journalctl -u name -f -p warning follows warnings and worse
  • systemd-analyze security name rates exposure from 0 (safe) to 10
  • systemctl edit name creates a drop-in override without touching the original

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1With Type=simple and a typo in the ExecStart path, what does systemctl start report?

Question 2

2A service prints log lines with printf, but they show up in the journal late or not at all. Why?

Question 3

3What happens if a service ignores SIGTERM during systemctl stop?

Question 4

4Your service runs with ProtectSystem=strict and fails to write /var/lib/chatd/db. What is the cleanest fix?

Question 5

5What does sd_notify return when the program is started from a shell, not by systemd?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a unit for a shell loop that prints the date every 5 seconds, start it, and follow its log with journalctl.

  2. Exercise 2medium

    Make a service restart on failure, then kill its main process with SIGKILL and watch systemd restart it. Find the restart in the journal and the NRestarts counter.

  3. Exercise 3hard

    Harden a unit for your capstone server: get systemd-analyze security below 3.0 while the service still works. Record which options you added and which ones broke it.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Where do I put my unit file?
Your own units go in /etc/systemd/system/. Packages install theirs in /usr/lib/systemd/system/ (or /lib/systemd/system/), and you override those with systemctl edit instead of editing them.
What is the difference between restart and reload?
restart stops the process and starts a new one, dropping connections. reload runs ExecReload, usually sending SIGHUP, so the running process re-reads its config and keeps its connections.
Can a normal user run services?
Yes. Put units in ~/.config/systemd/user/ and use systemctl --user. Run loginctl enable-linger USER if they should keep running after logout.
How do I pass environment variables or secrets?
Environment=KEY=value or EnvironmentFile=/etc/chatd/env set variables. For secrets, LoadCredential= is better, because it exposes the file only to that service under $CREDENTIALS_DIRECTORY.

Go deeper

ShareXLinkedInWhatsApp