How to Work with Processes and PIDs in Go

Start processes with exec.Command, access the PID via cmd.Process.Pid, and manage them using os.Process methods like Wait and Signal.

Use the os/exec package to start processes and the os package to manage them by PID. Create a process with exec.Command, start it to get a *os.Process containing the PID, and use Wait() to block until completion or Signal() to send signals.

package main

import (
	"os/exec"
	"fmt"
	"os"
)

func main() {
	cmd := exec.Command("sleep", "10")
	if err := cmd.Start(); err != nil {
		panic(err)
	}
	fmt.Println("PID:", cmd.Process.Pid)
	cmd.Process.Signal(os.Interrupt)
	cmd.Wait()
}