Documentation
¶
Overview ¶
Package parentdeath detects when a parent process dies so that child processes can clean up and exit, even when the parent is killed violently (SIGKILL) or when children are launched in ways that prevent normal signal delivery (e.g. via sudo systemd-run).
It is a portable alternative to Linux's PR_SET_PDEATHSIG, which only works for direct parent-child relationships within the same pid namespace and doesn't work when the child is reparented.
The parent calls BeParent once at startup. This sets environment variables that children will inherit. The returned ParentInfo contains the extra environment entries for callers that build explicit exec.Cmd.Env slices.
Each child calls Monitor early in its main function, passing a callback to invoke if the parent dies. If the environment variables are not set (the process was not launched by a parentdeath-aware parent), Monitor is a no-op. If the variables are set but the connection or validation fails, Monitor returns an error.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Monitor ¶
func Monitor(onParentDeath func())
Monitor checks the PARENTDEATH_ADDR and PARENTDEATH_SESSION environment variables. If they are not set, it does nothing (this process was not launched by a parentdeath-aware parent).
If they are set, Monitor connects to the parent's TCP listener and verifies the session token. If the connection fails or the token doesn't match, the parent is presumed already dead and onParentDeath is called immediately.
On successful connection, it monitors the connection in a background goroutine; when the connection breaks (parent exits), onParentDeath is called.
Types ¶
type ParentInfo ¶
type ParentInfo struct {
// Env contains the environment variables set via os.Setenv,
// in "KEY=VALUE" form. These are already in the current process's
// environment and will be inherited by children started with
// os/exec. They are provided here for callers that need to pass
// an explicit Env to exec.Cmd.
Env []string
// Addr is the "host:port" listen address.
Addr string
// Session is the random session token.
Session string
}
ParentInfo is returned by BeParent and contains information about the running parent death listener.
func BeParent ¶
func BeParent() *ParentInfo
BeParent starts a background TCP listener on localhost. It sets the PARENTDEATH_ADDR and PARENTDEATH_SESSION environment variables so that child processes can discover and connect to it.
Each accepted connection receives the session token followed by a newline. The connection then stays open until the parent process exits, at which point the OS closes it and the child's read unblocks with an error.
It panics if it cannot listen on localhost.