检查exec.Cmd是否在Go中运行完毕

17x*_*nde 2 go

我正在尝试检查这些情况下是否exec.Cmd 正在运行:

  1. 在我真正开始命令之前
  2. 命令启动后,但在它完成之前
  3. 命令完成后

如果它正在运行,这将允许我终止此命令,以便我可以使用不同的参数再次启动它.

一个简单的用例如下:

c := exec.Command("omxplayer", "video.mp4")
s, _ := c.StdinPipe() // use the pipe to send the "q" string to quit omxplayer

log.Printf("Running (false): %v\n", checkRunning(c)) // prints false: command has not started yet
c.Start()
log.Printf("Running (true): %v\n", checkRunning(c)) // print true: command has started

time.AfterFunc(3*time.Second, func() {
  log.Println("about to quit process...")
  log.Printf("Running (true): %v\n", checkRunning(c)) // prints true: command still running at this point
  s.Write([]byte("q"))
})

log.Println("waiting for command to end")
log.Printf("Running (true): %v\n", checkRunning(c)) // prints true: command still running at this point
c.Wait()
log.Println("command should have ended by now")
log.Printf("Running (false): %v\n", checkRunning(c)) // prints false: command ended at this point
Run Code Online (Sandbox Code Playgroud)

这是我能想到的最好的:

func checkRunning(cmd *exec.Cmd) bool {
  if cmd == nil || cmd.ProcessState != nil && cmd.ProcessState.Exited() || cmd.Process == nil {
    return false
  }

  return true
}
Run Code Online (Sandbox Code Playgroud)

它适用于上面的用例,但它似乎过于复杂,我不确定它是多么可靠.

有没有更好的办法?

cap*_*aig 5

也许在goroutine中同步运行并将结果放在您可以选择的频道上?

c := exec.Command("omxplayer", "video.mp4")
// setup pipes and such
ch := make(chan error)
go func(){
  ch <- c.Run()
}()
select{
  case err := <- ch:
    // done! check error
  case .... //timeouts, ticks or anything else
}
Run Code Online (Sandbox Code Playgroud)