
上QQ阅读APP看书,第一时间看更新
How to do it…
- Open the console and create the folder chapter01/recipe09.
- Navigate to the directory.
- Create the main_running.go file with the following content:
package main
import (
"fmt"
"os/exec"
"runtime"
)
func main() {
var cmd string
if runtime.GOOS == "windows" {
cmd = "timeout"
} else {
cmd = "sleep"
}
proc := exec.Command(cmd, "1")
proc.Start()
// No process state is returned
// till the process finish.
fmt.Printf("Process state for running process: %v\n",
proc.ProcessState)
// The PID could be obtain
// event for the running process
fmt.Printf("PID of running process: %d\n\n",
proc.Process.Pid)
}
- Run the code by executing go run main_running.go.
- See the output in the Terminal:

- Create the main.go file with the following content:
func main() {
var cmd string
if runtime.GOOS == "windows" {
cmd = "timeout"
} else {
cmd = "sleep"
}
proc := exec.Command(cmd, "1")
proc.Start()
// Wait function will
// wait till the process ends.
proc.Wait()
// After the process terminates
// the *os.ProcessState contains
// simple information
// about the process run
fmt.Printf("PID: %d\n", proc.ProcessState.Pid())
fmt.Printf("Process took: %dms\n",
proc.ProcessState.SystemTime()/time.Microsecond)
fmt.Printf("Exited sucessfuly : %t\n",
proc.ProcessState.Success())
}
- Run the code by executing go run main.go.
- See the output in the Terminal:
