cmd := exec.Command("ls") err := cmd.Run() if err != nil { fmt.Println("Command failed:", err) } if status, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok { if status.Exited() { fmt.Println("Exit status:", status.ExitStatus()) } }
func runCmd(name string, args ...string) int { cmd := exec.Command(name, args...) err := cmd.Run() if err != nil { fmt.Println("Command failed:", err) } if status, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok { if status.Exited() { return status.ExitStatus() } } return -1 }In this example, we define a function that takes a command name and its arguments, runs it, and returns the exit status. We use the same approach as before to obtain the process state and the exit status. Both examples use the `syscall` package from the standard library of Go.