gpt4 book ai didi

go - 检查 exec.Cmd 是否在 Go 中完成运行

转载 作者:IT王子 更新时间:2023-10-29 01:52:14 25 4
gpt4 key购买 nike

在这些情况下,我正在尝试检查 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

这是我能想到的最好的:

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

return true
}

它适用于上面的用例,但它似乎过于复杂,我不确定它的可靠性。

有没有更好的办法?

最佳答案

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

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
}

关于go - 检查 exec.Cmd 是否在 Go 中完成运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46934025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com