Go 结束进程和子进程

Go 结束进程和子进程,go,raspberry-pi,Go,Raspberry Pi,我正在尝试正确地终止一个命令 c := exec.Command("omxplayer", "video.mp4") c.Start() // send kill signal to terminate command at later stage time.Sleep(4*time.Second) c.Process.Kill() c.Wait() // should wait for program to fully exit // start again with new video

我正在尝试正确地终止一个命令

c := exec.Command("omxplayer", "video.mp4")
c.Start()

// send kill signal to terminate command at later stage
time.Sleep(4*time.Second)
c.Process.Kill()
c.Wait() // should wait for program to fully exit

// start again with new video
c := exec.Command("omxplayer", "video2.mp4")
c.Start()
我正试图在我的Raspberry Pi上终止当前的
omxplayer
进程,这样我就可以用一个新的视频重新启动它

发送
Kill
信号后,调用
c.Wait()
等待当前命令结束,然后再启动新命令


问题是第一个命令没有停止,但下一个命令仍在启动。因此,我最终会同时播放多个视频

omxplayer
正在推出一个新流程。特别是对于
omxplayer
,我可以将“q”字符串发送到它的
StdinPipe
。这就像按键盘上的
q
键,退出程序,同时结束父进程和子进程:

c := exec.Command("omxplayer", "video.mp4")
c.Start()
p := c.StdinPipe()
_, err := p.Write([]byte("q")) // send 'q' to the Stdin of the process to quit omxplayer

c.Wait() // should wait for program to fully exit

// start again with new video
c := exec.Command("omxplayer", "video2.mp4")
c.Start()
另一个更通用的选项是创建一个包含父进程和子进程的进程组,并终止该进程组:

c := exec.Command("omxplayer", "video.mp4")
// make the process group id the same as the pid
c.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
c.Start()

// sending a negative number as the PID sends the kill signal to the group
syscall.Kill(-c.Process.Pid, syscall.SIGKILL)

c.Wait()

基于

omxplayer
可能正在派生一个新流程。如果是这种情况,您可能必须搜索其pid以发出信号,如果它没有提供关闭它的机制。使用
pstree-p
查看由
omxplayer
分叉的进程(如果有)。父进程也可能希望清理,但您不能通过发送SIGKILL来允许它。看看SIGTERM或SIGINT会发生什么。你能检查一下每一步中可能出现的错误吗?(你可以通过分配它们来实现这一点,就像:
err:=c.Wait(),如果err!=nil{log.Fatal(err)}
谢谢大家,我想你是对的,
omxplayer
正在派生一个新的进程。我已经能够通过管道输入用于“退出”的
q
字符来正确地停止它
omxplayer
。既然我知道了要寻找什么,我已经找到了一个解决方案,可以杀死进程组,这似乎也很有效。如果你们中有人有兴趣发布这样的答案,我很乐意接受。