Skip to the text
KDOS
Menu
kdos.dev KDOS from Scratch KDOS 0.2 · 4dd4a10 · 2026-11-30 Contents Index

386. Writing a service

This page is for an administrator who wants a program of their own to start at boot and be restarted when it dies, and for a developer adding a service to KDOS. KDOS has no systemd units: a service is a script in /etc/init.d that rcS (the boot sequence) starts at boot and that the service command manages, with its daemon kept alive by the supervisor ksvc. It covers the two places such a script can live. On one running machine, you write it into /etc/init.d by hand. In the KDOS tree, it goes into fs/etc/init.d/ when it belongs to the base system, or into a port’s build.sh when it belongs to that port’s package. Managing a service once it exists is on Services.

Installation

Nothing extra is needed. The supervisor is ksvc, from kdos-tools, and /etc/init.d/service_helper, from the base filesystem, gives a script the functions it calls. A daemon from a package you build yourself is installed with kpkg like any other port; see kpkg and Anatomy of a kpkg install.

A script added by hand to a running installed system belongs to no package: kdos why reports that no package owns it, and no package upgrade replaces or removes it. On the live medium it is kept only when a persistence store exists (kdos persist).

Configuration

The contract

rcS, rcK and service agree on what a service script is. Each rule below is read from the code that enforces it:

Rule Enforced by When broken
The file is /etc/init.d/NN_<name>.sh: two digits, an underscore, the name, .sh rcS, rcK, ksvc The script is never run and service does not find it
The file is executable rcS, rcK, service list The script is skipped without a word, and service start fails without a message
It takes start, stop and status, and prints a usage line and exits 1 for anything else the shipped scripts; service passes the verb through service commands do nothing useful
start exits 0 when it started the service or deliberately skipped it, non-zero only on a failure rcS The splash marks the stage failed and shows the last six lines of output
A skip prints [SKIP] <name>: <reason> and exits 0 the shipped scripts The boot log says nothing about why the service is down
A daemon runs in the foreground under supervise ksvc The supervisor sees the parent exit as soon as the daemon forks, and starts it again every five seconds
start returns once the daemon is launched, or, for a daemon that owns a bus name, once it holds the name (wait_bus_name, at most ten seconds) rcS, which waits for each script The boot stops at that stage
The <name> passed to supervise is letters, digits, _, - and ., at most 64 characters ksvc ksvc refuses it: bad service name

NN places the script in the boot order. Pick a number above every script whose service yours needs: above 22_syslog to log through syslog from the first line, above 30_network and 42_networkmanager for the network, above 40_dbus for the system bus.

service_helper

# service_helper - Shared service management functions
# Source this file from individual service scripts via:
#   . /etc/init.d/service_helper
#
# Thin wrappers over ksvc, which is C, and wait_bus_name. The supervisor must
# lead its own process group so that stopping it signals the group and the
# daemon goes with it; a respawn loop in a backgrounded shell subshell leads no
# group, and stopping it leaves the daemon running while reporting success.
#
# The command is an argument vector: `supervise foo /usr/sbin/foo --flag`, not
# one string that a later unquoted expansion would re-split.
#
# `supervise --final-exit N foo ...` names an exit status restarting cannot
# change — "not supported on this machine", "nothing here to watch": on it the
# supervisor stops instead of restarting the daemon every five seconds for ever.
#
# `supervise --facility NAME foo ...` sends the daemon's forwarded output to
# syslog under that facility instead of `daemon`, so syslog.conf files it with
# what the daemon logs itself: 41_polkitd.sh passes `authpriv`.
#
# `supervise --stop-grace SECS foo ...` is how long `stop_service` waits for
# the daemon to exit after SIGTERM before it sends SIGKILL; five seconds when
# not given. A daemon whose clean shutdown writes data out names a longer one.
#
# `supervise --restart-with OTHER foo ...` restarts foo's daemon whenever the
# daemon of the supervised service OTHER is restarted or stopped, and holds
# each start while OTHER's daemon is between two runs. 42_networkmanager.sh
# passes `dbus`: NetworkManager does not exit when its bus goes away.
#
# `supervise` on a name whose supervisor is alive starts nothing and prints
# `[SKIP] <name>: already supervised`, so `service start` on a running service
# is safe to repeat. Nor does it start one beside a daemon whose supervisor
# was killed: it waits for that daemon for the stop grace, then refuses with
# `[FAIL]`, and `stop_service` ends the daemon.

supervise() {
    ksvc supervise "$@"
}

stop_service() {
    ksvc stop-supervised "$1"
}

check_status() {
    ksvc check "$1"
}

# `wait_bus_name NAME` returns 0 once NAME has an owner on the system bus, or
# 1 after ten seconds, saying so. A script whose daemon owns a bus name calls
# it after `supervise`, so the scripts after it in the order find the name
# taken. A daemon the supervisor runs ships no D-Bus activation file — the bus
# would otherwise start a second, unsupervised copy for a caller that came
# early, and the supervised one could then never take its name — so a call
# made before the name is owned is refused with ServiceUnknown instead.
# org.freedesktop.DBus has an owner as soon as the bus accepts connections.
wait_bus_name() {
    local i
    for ((i = 0; i < 100; i++)); do
        dbus-send --system --print-reply --dest=org.freedesktop.DBus / \
            org.freedesktop.DBus.NameHasOwner "string:$1" 2>/dev/null |
            grep -q 'boolean true' && return 0
        sleep 0.1
    done
    echo "[WARN] $1 is not on the system bus after 10 seconds"
    return 1
}

fs/etc/init.d/service_helper

supervise takes an argument vector, not a string: write supervise mydaemon /usr/sbin/mydaemon --foreground, each word its own argument. The options of ksvc supervise, --final-exit among them, are in ksvc and service.

A script in the base system

fs/etc/init.d/52_smartd.sh is the base system’s pattern with one addition, the exit statuses the supervisor is not to restart:

. /etc/init.d/service_helper

NAME="smartd"
DAEMON="/usr/sbin/smartd"

# THE DISK-HEALTH WATCHER. smartd polls every SATA, SAS and NVMe disk that
# answers SMART every thirty minutes and logs to the system log a failing
# health check, pending or uncorrectable sectors, new entries in the drive's
# error log and failed self-tests. /etc/smartd.conf is upstream's and ships
# as a bare DEVICESCAN; a `-m` or `-M exec` line there adds a route beyond the
# log.
#
# -n keeps it in the foreground, which is what `supervise` needs.
#
# THREE EXITS ARE FINAL. 17 is "no devices to monitor" — a virtual machine, or
# a machine whose disks do not answer SMART — and 2 and 6 are a smartd.conf it
# cannot parse or cannot read. Restarting changes none of them, and without
# `--final-exit` the supervisor would log each one every five seconds.

case "$1" in
    start)
        if [ ! -x "$DAEMON" ]; then
            echo "[SKIP] $NAME: $DAEMON not found"
            exit 0
        fi
        echo "[KDOS] Starting $NAME..."
        supervise --final-exit 2 --final-exit 6 --final-exit 17 "$NAME" \
            "$DAEMON" -n
        ;;
    stop)
        stop_service "$NAME"
        ;;
    status)
        check_status "$NAME"
        ;;
    *)
        echo "Usage: $0 {start|stop|status}"
        exit 1
        ;;
esac

fs/etc/init.d/52_smartd.sh

A script in a port

A port writes its script from build.sh, in a quoted heredoc whose delimiter is KDOS_SH, so the script is part of the recipe and testing/preflight.sh can check it. The ngircd port’s script skips until the server has a configuration file and an account, and runs the daemon as that account:

install -d "$PKG/etc/init.d"
cat > "$PKG/etc/init.d/79_ngircd.sh" <<'KDOS_SH'
#!/bin/bash
. /etc/init.d/service_helper

NAME="ngircd"
DAEMON="/usr/sbin/ngircd"
CONF="/etc/ngircd.conf"

case "$1" in
    start)
        [ ! -x "$DAEMON" ] && { echo "[SKIP] $NAME: $DAEMON not found"; exit 0; }
        if [ ! -s "$CONF" ]; then
            echo "[SKIP] $NAME: no $CONF (/usr/share/doc/ngircd/sample-ngircd.conf is the template)"
            exit 0
        fi
        if ! getent passwd ngircd >/dev/null; then
            echo "[SKIP] $NAME: no ngircd account (the port's postinstall makes it)"
            exit 0
        fi
        echo "[KDOS] Starting $NAME..."
        supervise "$NAME" setpriv --reuid=ngircd --regid=ngircd \
            --init-groups "$DAEMON" -n -f "$CONF"
        ;;
    stop)   stop_service "$NAME" ;;
    status) check_status "$NAME" ;;
    *)      echo "Usage: $0 {start|stop|status}"; exit 1 ;;
esac
KDOS_SH
chmod 755 "$PKG/etc/init.d/79_ngircd.sh"

ports/core/servers/ngircd/build.sh, lines 22–51

The account comes from the port’s postinstall.sh, which runs on the target at every install and writes under PKG_ROOT:

root="${PKG_ROOT:-/}"
grep -q '^ngircd:' "$root/etc/group" 2>/dev/null || groupadd -R "$root" -r ngircd
grep -q '^ngircd:' "$root/etc/passwd" 2>/dev/null || \
	useradd -R "$root" -r -g ngircd -d /nonexistent -s /sbin/nologin ngircd

ports/core/servers/ngircd/postinstall.sh, lines 20–23

Why a script lives in the recipe and not beside it, and the rules a postinstall.sh keeps, are in Shipping a script the port carries and postinstall.sh.

Usage

Adding a service to one machine

  1. Choose the number and the name. List what is there:

    ls /etc/init.d
  2. Write the script as root. This one starts a daemon at /usr/local/sbin/mydaemon that stays in the foreground when given --foreground; replace the three names with yours:

    #!/bin/bash
    . /etc/init.d/service_helper
    
    NAME="mydaemon"
    DAEMON="/usr/local/sbin/mydaemon"
    
    case "$1" in
        start)
            if [ ! -x "$DAEMON" ]; then
                echo "[SKIP] $NAME: $DAEMON not found"
                exit 0
            fi
            echo "[KDOS] Starting $NAME..."
            supervise "$NAME" "$DAEMON" --foreground
            ;;
        stop)
            stop_service "$NAME"
            ;;
        status)
            check_status "$NAME"
            ;;
        *)
            echo "Usage: $0 {start|stop|status}"
            exit 1
            ;;
    esac

    Save it as /etc/init.d/90_mydaemon.sh.

  3. Make it executable:

    sudo chmod 755 /etc/init.d/90_mydaemon.sh
  4. Start it and check it:

    sudo service start mydaemon
    service status mydaemon
    sudo cat /run/kdos-svc.mydaemon.log

    On the first start the log’s first line is the supervisor’s [KDOS] (mydaemon) Starting: /usr/local/sbin/mydaemon.

  5. Stop it, and check that the daemon is gone with the supervisor:

    sudo service stop mydaemon
    pgrep -a mydaemon

    pgrep should print nothing.

  6. The service starts at every boot from here on. To keep it installed but off, run sudo service disable mydaemon.

Adding a service to the tree

  1. Base system. Put the script at fs/etc/init.d/NN_<name>.sh and make it executable in git (mode 100755). Copy it into the build root and repack the image, on your machine:

    make build BUILD_ARGS="--phases 10_bootstrap,70_image --steps 10_bootstrap:000_file_system.sh"

    See The file system.

  2. A port. Write the script into the port’s build.sh as above, install -d "$PKG/etc/init.d" first and chmod 755 after, and an account, if it needs one, into postinstall.sh. Rebuild the port and repack:

    make build BUILD_ARGS="--phases <phase>,70_image --rebuild <port>"
  3. Check the wiring, on your machine:

    testing/preflight.sh

    It refuses a script under fs/etc/init.d that is not executable or not recorded in git as 100755, and one whose DAEMON= line names a kdos-* program that no build.sh installs. In a port, it reads every heredoc opened with <<'KDOS_SH', refuses one that does not parse under bash -n and, when a build tree exists, one whose commands are on no image.

  4. A service that listens on the network also needs a firewall rule; see Adding your own rules.

Tips

Troubleshooting

service says Error: Service '<name>' not found. The file name is wrong: it must be two digits, _, the name and .sh.

rcS never runs the script, service list does not show it, and service start prints nothing. The file is not executable. ls -l /etc/init.d/ must show -rwxr-xr-x.

The boot stops at the script’s stage. start did not return. Either the daemon was started in the foreground without supervise, or the script waits on a pipe that a process it backgrounded still holds open. Boot with emergency (see Init and runlevels), make the script non-executable with chmod -x, and reboot.

The supervisor’s log shows Exited with code 127. The supervisor could not execute the command: the path is wrong or the file is not executable. supervise runs the command through execvp, so a bare name is looked up in PATH.

The daemon exits at once and restarts every five seconds. Most often it forked into the background and the supervisor saw the parent exit: the log repeats [KDOS] (<name>) Exited with code 0. Restarting in 5s..., a clean exit, after each Starting: line. Add the daemon’s foreground switch. Otherwise read its own complaint in /run/kdos-svc.<name>.log (sudo less; the file is root’s, mode 0640).

service stop reports Stopped, but a process of the daemon keeps running. A child of the daemon left the supervisor’s process group (one that calls setsid itself does): stop signals the group and the daemon’s own pid, never such a child. While the service runs, compare the process groups:

cat /run/kdos-svc.<name>.pid
ps -eo pid,pgid,args | grep <daemon>

The first number is the supervisor’s, and every process of the service should show it in the PGID column.

After the system bus restarts, the daemon runs on but answers nothing on the bus. It does not exit when its bus connection closes, so its supervisor never restarts it, and service status still says [ OK ]. Supervise it with supervise --restart-with dbus <name> …, as 42_networkmanager.sh does: the supervisor then restarts it once the new bus is up.

testing/preflight.sh reports KDOS_SH heredoc: and a syntax error. The script inside the port’s heredoc does not parse under bash -n; the message after the colon is bash’s, and its line number counts from the first line after <<'KDOS_SH'. Keep the delimiter quoted, <<'KDOS_SH': an unquoted one lets $1 and $PATH expand while the recipe runs, and preflight.sh does not read such a heredoc at all.

testing/preflight.sh reports KDOS_SH heredoc runs '<command>', which is on no image. A line of the script starts with a program that is in no bin or sbin directory of the build tree. Add the port that installs it to the recipe’s depends, or call a program the image has.

Known gaps

Known gaps lists nothing for this topic. For a script added to the tree: A clone does not check what it pushes unless you enable the hook.

See also