daemon

package
v0.166.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package daemon turns a foreground gofer process (serve / worker) into a detached background process. Go cannot fork() safely (the runtime owns multiple threads), so the "-d" path re-execs the SAME binary with an env sentinel (EnvSentinel) set: the parent spawns the detached child and exits; the child sees the sentinel, skips daemonization and runs the real command. A pidfile records the child PID for duplicate-start detection and for the `serve stop` / `worker stop` subcommands. The platform-specific detach / signal mechanics live in daemon_unix.go and daemon_windows.go.

Index

Constants

View Source
const EnvSentinel = "GOFER_DAEMONIZED"

EnvSentinel marks that the current process is already the detached child, so re-exec is not attempted again (would otherwise fork-bomb). The parent sets it to "1" on the child's environment; Daemonized() reads it.

Variables

View Source
var ErrAlreadyRunning = errors.New("already running")

ErrAlreadyRunning is returned by Spawn when the pidfile points at a live process — a second `-d` start is refused rather than spawning a duplicate.

Functions

func Claim

func Claim(pidPath string) (release func(), owned bool)

Claim records the current process in pidPath so `serve stop` / `worker stop` and the worker scan (runningWorkerIDs) can find it, whether it was started detached (-d) or in the foreground (a supervisor / a terminal).

A pidfile already held by ANOTHER live process is left untouched: owned is false and the returned release is a no-op, so a second instance (a different config dir, or a stale-looking pidfile) never steals or deletes the record. The caller only warns in that case — a pidfile clash must not refuse startup (a real conflict shows up as a bind error).

release re-reads the file and removes it only while it still holds our pid, so a successor that already claimed the pidfile is not deleted by our shutdown.

func Daemonized

func Daemonized() bool

Daemonized reports whether the current process is the detached child (the env sentinel is set). The command layer calls this to decide whether to re-exec (parent) or run the real command (child).

func KillDetached

func KillDetached(p *os.Process) error

KillDetached hard-kills a process started by StartDetached together with whatever it spawned: Setsid made it the leader of its own process group, so the group is signalled as a whole (a candidate that hung before registering may have children).

func KillHint

func KillHint(pid int) string

KillHint is the manual command an operator can run when a graceful stop timed out (printed by stopDaemon).

func NotifyReload

func NotifyReload(chan<- os.Signal)

NotifyReload is a no-op on Unix because RequestReload sends a real SIGHUP.

func NotifyStop

func NotifyStop(chan<- os.Signal)

NotifyStop is a no-op on unix: the stop signal IS a real SIGTERM, which the caller already receives through its own signal.Notify, so there is no second delivery mechanism to install here (Windows needs one because a detached process there has no console and therefore no signal to receive).

func PIDAlive

func PIDAlive(pid int) bool

PIDAlive reports whether a process with pid exists. signal 0 performs error checking without delivering a signal: nil → alive; EPERM → exists but owned by another user (still alive); ESRCH → no such process.

func ReadPIDFile

func ReadPIDFile(path string) (int, error)

ReadPIDFile reads and parses the PID stored in path. A missing file or non-numeric content is an error (callers treat any error as "not running").

func RemovePIDFile

func RemovePIDFile(path string)

RemovePIDFile deletes the pidfile, ignoring a missing file. The detached child calls this on graceful shutdown so a stale pidfile never lingers.

func RequestReload

func RequestReload(pid int) error

RequestReload asks a Unix gofer process to reload through SIGHUP.

func SameExecutable

func SameExecutable(a, b string) bool

func Spawn

func Spawn(o Options) (int, error)

Spawn re-execs the current binary as a detached background child and returns its PID. It refuses to start when the pidfile already points at a live process (ErrAlreadyRunning). A stale pidfile (dead PID) is silently overwritten. Only the PARENT calls Spawn; the child (Daemonized()==true) never reaches here.

func StartDetached

func StartDetached(exe string, args, env []string, logPath string) (*exec.Cmd, error)

StartDetached starts exe fully detached (new session) with stdin closed and stdout/stderr appended to logPath, in the environment env. The caller owns the returned Cmd (it should Wait to reap the child if it outlives it).

func StartDetachedStrict

func StartDetachedStrict(string, []string, []string, string) (*exec.Cmd, error)

StartDetachedStrict is deliberately unavailable on Unix: Setsid only leaves the terminal/session, not the service's systemd cgroup. Upgrade helpers must be launched in a separate transient unit by the Linux service backend.

func Takeover

func Takeover(pidPath string) (release func())

Takeover points pidPath at the current process unconditionally and returns the matching release. It is the pidfile half of a binary upgrade handover: the new process is started while the old one still holds the file (so Claim leaves it alone), and once the new process has registered it must become the recorded one — the old process's own release then sees a foreign pid and removes nothing.

func Terminate

func Terminate(pid int) error

Terminate sends SIGTERM to pid for graceful shutdown (used by `serve stop` / `worker stop`).

func WritePIDFile

func WritePIDFile(path string, pid int) error

WritePIDFile writes pid to path atomically (write temp + rename) so a reader never observes a half-written file.

Types

type Options

type Options struct {
	Name    string // diagnostic label, e.g. "serve" / "worker-<id>"
	PIDPath string // pidfile absolute path
	LogPath string // child stdout/stderr sidecar output target (for example *.out.log)
}

Options describes one daemonization: a diagnostic name plus the runtime file locations (resolved by the caller, typically config.RuntimeFilePath).

type ProcessIdentity

type ProcessIdentity struct {
	PID     int    `json:"pid,omitempty"`
	Exe     string `json:"exe,omitempty"`
	Owner   string `json:"owner,omitempty"`
	StartID string `json:"start_id,omitempty"`
}

ProcessIdentity binds a PID to its image, OS owner and creation identity. StartID prevents a reused PID from matching a previously recorded process.

func CurrentProcessIdentity

func CurrentProcessIdentity() (ProcessIdentity, error)

func InspectProcess

func InspectProcess(pid int) (ProcessIdentity, error)

type Session

type Session struct {
	ID          uint32
	Interactive bool
	Console     bool
}

Session reports which OS session a process runs in and whether that is a session a user can reach. On Windows two separate questions are answered, because they are NOT the same one (W2 measured it on an RDP-only host): Interactive means "this process sits on a user desktop" — any session but the service session 0, RDP sessions included, which is what decides whether GUI automation can work at all; Console narrows that to the session attached to the PHYSICAL console, which an RDP login does not use (there interactive=true, console=false is normal, because the console session is the idle one). On unix it is the zero value, there being no equivalent concept.

func SessionInfo

func SessionInfo() Session

SessionInfo has no unix equivalent: a unix process runs in whatever environment its parent gave it, so the zero value (Interactive=false) is the honest answer.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL