Exec'ing Processes
Replace the current process on Unix with syscall.Exec; a successful handoff skips deferred functions.
On Unix, syscall.Exec replaces the current process with another executable. It does not start a child; on success, the call never returns.
LookPath resolves a program through PATH. Pass the executable path, its argument vector, and the environment 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 process should hand off control to another program. Deferred functions do not run after successful replacement, so flush logs and close resources first. syscall.Exec is Unix-specific; use os/exec when a child process is intended or portability is required.
Enjoyed this? Get more software craft delivered to your inbox.