background

package
v0.33.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: AGPL-3.0 Imports: 15 Imported by: 1 module, 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 background starts a program as a background process that is detached from the terminal and session of the starter, hands it optional bytes through an inherited pipe, and waits for the report the process gives once it runs.

The caller supplies the program, its arguments and its environment; the arguments typically select a hidden subcommand of the same binary. The started process uses Inherit to read the handover and to report. Start returns a Process handle: its Done channel closes when the process ends, and Kill ends it, as a process that hands its state to a successor needs.

Always enforced

Nothing is put on the command line or in the environment on the package's behalf, so a handover never appears there. It travels through an inherited pipe, and ReadHandover requires a size limit, fails above it, and clears what it read when it fails. Any report other than ReportReady or ReportRunning ends the process before Start returns an error, and so does a context or timeout that ends first. A report is read only up to 4096 bytes and a failure reason is cut to one line. A negative timeout is refused.

The process gets the null device as its standard streams and a fixed working directory (the root directory on Unix, the system directory on Windows). On Linux and macOS it also leads a session of its own. On Windows it has no console and its own process group; its standard input and output are the handover and report pipes, and it leaves the job object of the starter where the job allows that.

Limits: detaching from the session does not protect the process from a service manager that ends it with the user's login session; see LogoutBehavior. A Windows job that forbids breakaway still ends the process with the job. Neither side protects against a process of the same user or an administrator.

Options

  • Command.Program: the file to run. Default: the running program (os.Executable).
  • Command.Args: the arguments after the program name. Default: none.
  • Command.Env: the environment as key=value pairs. Default: the environment of the starter.
  • Options.Timeout: bounds the wait for the report; the context can end it sooner. Default: DefaultTimeout, 10 seconds.

Index

Constants

View Source
const (
	ReportReady   = "ready"
	ReportRunning = "running"
)

The words a started process reports with. Any other report is the reason it did not start.

View Source
const DefaultTimeout = 10 * time.Second

DefaultTimeout bounds how long Start waits for the report if Options.Timeout is zero.

Variables

View Source
var (
	// ErrTimeout means the started process did not report before the timeout passed.
	ErrTimeout = errors.New("the background process did not report in time")

	// ErrEnded means the started process ended before it reported.
	ErrEnded = errors.New("the background process ended before it reported")

	// ErrHandoverNotTaken means the started process did not take the handover.
	ErrHandoverNotTaken = errors.New("the background process did not take the handover")

	// ErrStartFailed means the system could not start the process. It is followed by the cause, which
	// errors.Is and errors.As still reach.
	ErrStartFailed = errors.New("cannot start the background process")

	// ErrProgramNotFound means the running program could not be found to start it again. It is followed by
	// the cause, which errors.Is and errors.As still reach.
	ErrProgramNotFound = errors.New("cannot find this program to start it in the background")
)
View Source
var ErrUnsupported = fmt.Errorf("background processes are unsupported on this platform: %w", errors.ErrUnsupported)

ErrUnsupported means the platform cannot run detached background processes.

Functions

This section is empty.

Types

type Child

type Child struct {
	// contains filtered or unexported fields
}

Child is the side of a started process: the handover it was given and the report pipe to the starter.

func Inherit

func Inherit() (*Child, bool)

Inherit returns the handover and report the process inherited from Start. It reports false if the process was not started by Start, for instance when a person ran the subcommand by hand; it then touches nothing.

func (*Child) Close

func (c *Child) Close()

Close reports a failure if nothing was reported yet and releases both pipes. Defer it right after Inherit so the starter never waits for a process that ended silently.

func (*Child) Fail

func (c *Child) Fail(reason string)

Fail reports why the process did not start. The reason must not contain secrets; it is shortened to one line.

func (*Child) ReadHandover

func (c *Child) ReadHandover(limit int) ([]byte, error)

ReadHandover reads the whole handover and closes the pipe. It fails if the handover is longer than limit bytes. The caller owns the returned bytes and should clear them after use; errors never quote them.

func (*Child) Ready

func (c *Child) Ready()

Ready reports ReportReady to the starter. Only the first report of a Child counts.

func (*Child) Running

func (c *Child) Running()

Running reports ReportRunning: another instance already runs, so this process is about to end.

type Command

type Command struct {
	// Program is the file to run. Empty means the running program (os.Executable).
	Program string
	// Args are the arguments after the program name.
	Args []string
	// Env is the environment as key=value pairs. Nil means the environment of the starter.
	Env []string
}

Command describes the process to start. The zero value starts the running program without arguments.

type LogoutOutcome

type LogoutOutcome int

LogoutOutcome says whether a process survives the end of the login session that started it.

const (
	// LogoutUnknown means the platform or its configuration does not tell.
	LogoutUnknown LogoutOutcome = iota
	// LogoutKills means the system ends the user's processes when the last session closes.
	LogoutKills
	// LogoutSpares means the system leaves a detached process running at logout.
	LogoutSpares
)

func LogoutBehavior

func LogoutBehavior() LogoutOutcome

LogoutBehavior reports whether systemd-logind would end a background process when the user's session closes (KillUserProcesses=yes, minus the user exceptions). It only reads the files logind reads. It is LogoutUnknown without systemd or with a setting it cannot parse. It does not cover a process started from a service unit.

func (LogoutOutcome) String

func (o LogoutOutcome) String() string

type Options

type Options struct {
	// Timeout bounds the wait for the report; zero means DefaultTimeout. The context can end it sooner.
	Timeout time.Duration
}

Options tune Start. The zero value is valid.

type Process

type Process struct {
	// contains filtered or unexported fields
}

Process is a started background process as its starter sees it. The process keeps running independently of the handle.

func (*Process) Done

func (p *Process) Done() <-chan struct{}

Done is closed once the process ended.

func (*Process) Kill

func (p *Process) Kill() error

Kill ends the process at once. It returns nil if the process already ended.

func (*Process) PID

func (p *Process) PID() int

PID returns the process id.

type ReportError

type ReportError struct{ Reason string }

ReportError means the started process reported a reason instead of ReportReady or ReportRunning.

func (*ReportError) Error

func (e *ReportError) Error() string

type Result

type Result struct {
	// Report is ReportReady, or ReportRunning if another instance already runs and the process ended.
	Report string
	// PID is the process id of the started process.
	PID int
	// Process is the handle of the started process.
	Process *Process
}

Result describes a started process.

func Start

func Start(ctx context.Context, cmd Command, handover []byte, opts Options) (Result, error)

Start runs cmd as a detached background process, writes handover (which may be empty) to the descriptor the process reads with Child.ReadHandover, and waits until the process reports ReportReady or ReportRunning, ctx ends, or the timeout passes. Any other result ends the process before Start returns an error. After a success the process keeps running independently of the caller.

Jump to

Keyboard shortcuts

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