Go by Example

Exec'ing Processes

Replace the current process on Unix with syscall.Exec; a successful handoff skips deferred functions.

On Unix-like systems such as Linux and macOS, syscall.Exec replaces the running program with another one. It does not start a separate child program. If it succeeds, the original program stops and the call does not return.

exec.LookPath finds a program by searching folders named in PATH, a setting provided by the operating system. Pass the program's path, its list of arguments and the environment values it should receive to Exec.

package main
 
import (
    "fmt"
    "os"
    "os/exec"
    "syscall"
)
 
func main() {
    path, err := exec.LookPath("echo")
    if err != nil {
        panic(err)
    }
    if err := syscall.Exec(path, []string{"echo", "hello"}, os.Environ()); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

In production

Use Exec only when the current program should stop and hand control to another one. A deferred function is scheduled to run when its caller returns, but it will not run after a successful replacement. Write saved output and close files first. syscall.Exec is Unix-specific; use os/exec to start a separate program or support other systems.

Enjoyed this? Get more software craft delivered to your inbox.