package main import ( "fmt" "os/exec" ) func main() { fmt.Println("Starting a 'sleep 15' command...") // 1. Create the command. cmd := exec.Command("sleep", "15") // 2. Start the command. This is non-blocking. err := cmd.Start() if err != nil { fmt.Printf("Error starting command: %v\n", err) return } // 3. If Start() succeeded, the PID is now available. // The check for err != nil above is critical to prevent a panic // from a nil pointer dereference on cmd.Process. pid := cmd.Process.Pid fmt.Printf("--> Successfully started process with PID: %d\n", pid) fmt.Println("--> You can verify this with 'ps aux | grep", pid, "'") fmt.Println("Waiting for the process to finish in the background...") // 4. Wait for the command to complete and release its resources. err = cmd.Wait() if err != nil { fmt.Printf("Command finished with error: %v\n", err) } else { fmt.Println("Command finished successfully.") } }