Processes, signals and OS interfaces
Processes, signals and OS interfaces
A process has its own address space and OS resources. A goroutine is not a process. Start a child with os/exec, pass arguments separately and wait for its exit; avoid a shell when you only need a command. Run the following complete programs on Linux with Go 1.23.2. The first re-executes only its own binary with a fixed argument, so it needs no external command.
package main
import ( "fmt" "os" "os/exec")
func main() { if len(os.Args) == 2 && os.Args[1] == "child" { fmt.Println("child ready") return } exe, err := os.Executable() if err != nil { panic(err) } cmd := exec.Command(exe, "child") out, err := cmd.Output() if err != nil { panic(err) } fmt.Printf("%s", out) fmt.Println(cmd.ProcessState.Success())}Output waits for the child and collects stdout; its error reports failure. A successful Start alone does not mean success: call Wait exactly once after a successful Start. Never assume a child PID is a goroutine identifier. CommandContext can cancel the immediate child; killing an entire process tree needs OS-specific design.
Expected output:
child readytrueConvert an interrupt to cancellation
package main
import ( "context" "fmt" "os" "os/signal" "time")
func main() { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() p, err := os.FindProcess(os.Getpid()) if err != nil { panic(err) } if err = p.Signal(os.Interrupt); err != nil { panic(err) } select { case <-ctx.Done(): fmt.Println(ctx.Err()) case <-time.After(3 * time.Second): panic("signal not delivered") }}NotifyContext registers before we send an interrupt to our own process. The timer is a failure watchdog, not the synchronization mechanism. Stop releases registration; default signal behavior may resume. Signal sets and process signaling differ across operating systems. Prefer application cleanup on context cancellation; SIGKILL cannot be intercepted.
Expected output:
context canceledTry it locally
Write a self-child fixture that exits 7 and report its exit status using errors.As with *exec.ExitError. Do not parse the error text.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Native interoperability 01: Processes, signals and OS interfaces
Check the lesson objective before moving on.
A child starts successfully but exits 7. Which operation observes that failure?
Why call stop from NotifyContext?