I build a system that runs agents on remote machines. The resident daemon on each machine updates itself and starts child processes such as git. This post looks at when those children actually die, in three places.
The clearest case is the self-update. The daemon downloads a new version and starts a small update helper. The helper restarts the service, checks the new process, and rolls back if it is broken. The helper is detached with setsid. Written this way, the new process starts fine, but the helper’s log has only its first line, “start”. No error, no crash.
The lesson: what decides when a child dies is not the parent-child relationship or the session. systemd looks at the cgroup, launchd at the process group, and Go’s exec.CommandContext only at the direct child.
1. systemd cleans up a service by cgroup
In systemd.kill(5), the default is KillMode=control-group: when the unit stops, every process remaining in its control group is killed. setsid changes the process group and session, not the cgroup. A helper started by the service stays in the service’s cgroup even after setsid.
I ran a real systemd 257 as PID 1 inside throwaway namespaces and tried four approaches with a one-file service. The service treats SIGUSR1 as “update requested”, and the helper restarts the service and then writes “restart finished”.
| Trial | How the helper starts | Helper’s cgroup | “restart finished” |
|---|---|---|---|
| A | Popen(start_new_session=True) (same as setsid) | demo-app.service | missing |
| B | Same as A, with KillMode=process | demo-app.service | present |
| C | systemd-run --unit=demo-updater | demo-updater.service | present |
| D | No helper. The app exits and Restart=always starts it | (none) | (new instance starts) |
The log from A:
22:24:36 [app pid=93] update requested, starting the updater via popen
22:24:36 [updater pid=96] start; cgroup=/system.slice/demo-app.service
22:24:36 [app pid=93] SIGTERM received, exiting
22:24:36 [app pid=102] started
The helper’s cgroup was the service’s own. The old app exited on SIGTERM and the new one started, but the helper never wrote its last line and was gone from the process list. With a trap added to the helper, it showed the same SIGTERM arriving at the same moment as the main process.
In B the helper survives, but a different problem appears. I made the helper sleep for 30 seconds and looked at the service in the meantime:
● demo-app.service - demo app
Active: active (running) since Tue 2026-10-06 22:25:00 JST; 2s ago
Main PID: 271 (python3)
CGroup: /system.slice/demo-app.service
├─265 /bin/bash /run/demo/updater.sh
├─271 /usr/bin/python3 /run/demo/app.py popen
└─272 sleep 30
The previous instance’s helper is inside the new instance’s cgroup. After a systemctl stop, the helper and sleep 30 were still running. The systemd documentation marks KillMode=process “not recommended!”.
There are two fixes. If a helper has to verify and roll back from the outside, give it its own unit with systemd-run, as in C. If the new version can check its own health at startup, drop the helper as in D: exit and let Restart= start the new version. A helper that decides whether to roll back must not live inside the thing it stops.
Replacing a service without stopping it (socket activation and other approaches) is tested in the post on keeping connections waiting during a systemd restart.
Files used in the trials (app.py, updater.sh, unit.sh, trial.sh)
#!/usr/bin/env python3
"""A tiny daemon that can update itself. SIGUSR1 = "update requested".
usage: app.py <how> how = popen | systemd-run | exit
"""
import os, signal, subprocess, sys, time
HOW = sys.argv[1]
LOG = "/run/demo/log"
def log(msg):
with open(LOG, "a") as f: f.write(f"{time.strftime('%H:%M:%S')} [app pid={os.getpid()}] {msg}\n")
def on_usr1(*_):
log(f"update requested, starting the updater via {HOW}")
if HOW == "popen": # the obvious way: detach into a new session so nothing can touch it
subprocess.Popen(["/run/demo/updater.sh"], start_new_session=True,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
elif HOW == "systemd-run": # hand the updater to the service manager as its own unit
subprocess.run(["systemd-run", "--unit=demo-updater", "--collect", "/run/demo/updater.sh"], check=True)
else: # no helper at all: leave, and let the supervisor (Restart=) start the new version
log("exiting; the supervisor restarts me"); os._exit(0)
signal.signal(signal.SIGUSR1, on_usr1)
signal.signal(signal.SIGTERM, lambda *_: (log("SIGTERM received, exiting"), sys.exit(0)))
log("started")
while True: time.sleep(1)
#!/bin/bash
log() { echo "$(date +%H:%M:%S) [updater pid=$$] $*" >> /run/demo/log; }
log "start; cgroup=$(cut -d: -f3 /proc/self/cgroup)"
systemctl restart demo-app.service
sleep "${UPDATER_SLEEP:-1}"
log "restart finished; the post-restart verification runs now"
#!/bin/bash
# usage: unit.sh <popen|systemd-run|exit> [extra [Service] lines...]
HOW=$1; shift
cat > /run/systemd/system/demo-app.service <<EOT
[Unit]
Description=demo app
[Service]
ExecStart=/usr/bin/python3 /run/demo/app.py $HOW
$(printf '%s\n' "$@")
EOT
systemctl daemon-reload
#!/bin/bash
# usage: trial.sh <label> <popen|systemd-run|exit> [extra [Service] lines]
label=$1; shift
echo "=== $label"
systemctl stop demo-app.service demo-updater.service 2>/dev/null; : > /run/demo/log
/run/demo/unit.sh "$@"
systemctl start demo-app.service; sleep 1
systemctl kill -s SIGUSR1 --kill-whom=main demo-app.service
sleep 4
cat /run/demo/log
echo "--- processes still around:"; ps -eo pid,cgroup:40,cmd | grep -E 'updater.sh|app.py' | grep -v grep
On a throwaway VM where systemd is PID 1 and you have root, put the four files in /run/demo/ and run sudo /run/demo/trial.sh A popen, sudo /run/demo/trial.sh B popen KillMode=process, sudo /run/demo/trial.sh C systemd-run and sudo /run/demo/trial.sh D exit Restart=always.
2. launchd: bootout returns early, and cleanup is by process group
Updating a macOS LaunchAgent means rewriting the plist and registering the service again. Run launchctl bootstrap right after launchctl bootout, and it sometimes fails with Bootstrap failed: 5: Input/output error.
bootout returns before cleanup has finished. launchd sends SIGTERM, waits up to the job’s ExitTimeOut, escalates to SIGKILL, and removes the service from the domain asynchronously. Bootstrapping the same label in the meantime returns EIO. The worse part comes after: bootout itself succeeded, so launchd considers the job cleanly unloaded, and KeepAlive does not bring it back. An update that should have been a restart leaves the service stopped.
So wait for the label to disappear, then retry a bounded number of times:
func bootout(target string) {
_ = exec.Command("launchctl", "bootout", target).Run() // not loaded is fine
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
// print exits non-zero once the label is gone from the domain.
if exec.Command("launchctl", "print", target).Run() != nil {
return
}
time.Sleep(200 * time.Millisecond)
}
}
func bootstrap(domain, plist string) error {
var out []byte
var err error
for attempt := 1; attempt <= 6; attempt++ {
if out, err = exec.Command("launchctl", "bootstrap", domain, plist).CombinedOutput(); err == nil {
return nil
}
time.Sleep(time.Duration(attempt) * 300 * time.Millisecond) // linear backoff
}
return fmt.Errorf("launchctl bootstrap %s: %w: %s", plist, err, bytes.TrimSpace(out))
}
The retries are bounded because EIO is not unique to this race. A broken plist produces the same error. Validate the plist beforehand with plutil -lint, and include the last output in the error.
launchd does not decide cleanup by parentage either. According to launchd.plist(5), when a job dies, launchd kills the remaining processes in the same process group unless AbandonProcessGroup is true. Since the rule is about process groups, a child that called setsid may be treated differently than under systemd. That is my reading of the documentation, and I did not test it.
systemd does not have this bootout race. systemctl stop and restart wait for the job to finish unless you pass --no-block.
3. Go’s CommandContext only kills the direct child
When its context ends, exec.CommandContext calls cmd.Cancel. By default that is Process.Kill, which is SIGKILL on Unix, and it reaches only the direct child. git fetch starts ssh or a credential helper, and those grandchildren survive. If a grandchild inherited the child’s standard output, Wait does not return either: the goroutine copying the pipe waits for EOF, and EOF only comes when every process holding the write end has exited.
I made a grandchild with sh -c "sleep 5.1 & sleep 5.1" and cancelled after 200 ms:
//go:build unix
// What does cancelling exec.CommandContext stop? Run: go run .
package main
import (
"bytes"
"context"
"fmt"
"os/exec"
"syscall"
"time"
)
// commandInGroup puts the child in its own process group and, on cancel,
// signals the whole group, so grandchildren die too.
func commandInGroup(ctx context.Context, name string, args ...string) *exec.Cmd {
cmd := exec.CommandContext(ctx, name, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) // negative pid = the group
}
cmd.WaitDelay = 2 * time.Second
return cmd
}
func run(label string, mk func(context.Context, string) *exec.Cmd, grandchild string) {
script := grandchild + " & " + grandchild // sh starts one sleep in the background
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
cmd := mk(ctx, script)
cmd.Stdout = &bytes.Buffer{} // not an *os.File, so os/exec copies from a pipe
start := time.Now()
_ = cmd.Start()
err := cmd.Wait()
time.Sleep(100 * time.Millisecond)
alive := exec.Command("pgrep", "-xf", grandchild).Run() == nil
fmt.Printf("%-24s Wait returned after %4.1fs, err=%v, grandchild alive=%v\n",
label, time.Since(start).Seconds(), err, alive)
}
func main() {
run("CommandContext", func(ctx context.Context, s string) *exec.Cmd {
return exec.CommandContext(ctx, "sh", "-c", s)
}, "sleep 5.1")
run("+ WaitDelay", func(ctx context.Context, s string) *exec.Cmd {
cmd := exec.CommandContext(ctx, "sh", "-c", s)
cmd.WaitDelay = 2 * time.Second
return cmd
}, "sleep 5.2")
run("process group + Cancel", func(ctx context.Context, s string) *exec.Cmd {
return commandInGroup(ctx, "sh", "-c", s)
}, "sleep 5.3")
}
CommandContext Wait returned after 5.2s, err=signal: killed, grandchild alive=false
+ WaitDelay Wait returned after 2.3s, err=signal: killed, grandchild alive=true
process group + Cancel Wait returned after 0.3s, err=signal: killed, grandchild alive=false
With CommandContext alone, the child was killed but Wait did not return until the grandchild finished on its own, about 5 seconds later. WaitDelay caps how long Wait waits and then closes the pipes. Wait returned after 2 seconds, but the grandchild was still alive: what it guarantees is that Wait returns, not that the processes are gone. With the child in its own process group and the whole group killed, Wait returned at once and the grandchild was gone too. (Cancel and WaitDelay need Go 1.20 or later.)
Which children to stop, and when, depends on what the command does:
- Read-only commands (
status,log,diffand so on) follow the caller’s context. If the caller is gone, nobody is waiting for the result. - Commands that change state (
commit,checkout,worktree addand so on) run to completion under their own timeout. A caller going away is no reason to leave a half-made worktree or a staleindex.lock. - Every command gets a separate upper-bound timeout, so a stuck child becomes a reportable error instead of a goroutine that never returns.
Setpgid has a cost. The child leaves the terminal’s foreground process group, so an interactive Ctrl-C no longer reaches it. That is right for a daemon and wrong for a CLI that relays a TTY. On Windows the same guarantee needs a Job Object.
Which to use
- Under systemd, a watcher has to verify and roll back across the restart. Give the watcher its own unit with
systemd-run. - The new version can check its own health at startup and exit non-zero if broken. Exit and let
Restart=handle it, with a sensible limit. - A package manager or an external deploy tool does the update. Do not have the service restart itself.
- You start children from Go and want a cancel to stop them. Put them in their own process group and stop the group. Not for a CLI that relays a TTY.
systemd --user, containers without systemd, macOS. Not tested here. Check that platform’s rules.
Common mistakes
- Treating
setsid,nohupor a double fork as “detached”. They change process and session relationships, not the cgroup. I reproducedsetsidabove and did not test the others. - Fixing it with
KillMode=process. The helper ends up inside the next instance and survives a stop. - Logging only inside the cgroup that is about to die. You see the first line and never the last. Write somewhere that survives before the risky step.
- Treating “the service restarted” as “the update succeeded”. That check is exactly what A lost.
- Testing the update only from a terminal. Run from a terminal, there is no unit cgroup to clean up. Test under the real service manager.
- Assuming cleanup is done because
bootoutreturned.bootstrapfails withEIO, and the service stays down. - Assuming
CommandContextalone stops the child. Grandchildren remain, andWaitmay not return.
Units decide lifetimes, not parents
Whether a child lives or dies looks like the parent’s decision, but it is actually decided by the units of the service manager and the kernel. Give anything that must outlive a restart its own unit, and stop anything that a cancel should stop together with its whole process group.