2017-10-19 46 views
0

我試圖正確地終止命令結束進程和子進程

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() 

我想殺死我的樹莓丕當前omxplayer過程,這樣我就可以開始再次用一個新的視頻。

一旦我發送了Kill信號,我打電話c.Wait()等待當前命令結束後再開始一個新的命令。

問題是第一個命令沒有停止,但是下一個命令仍在啓動。所以我最終同時播放了多個視頻。

+2

'omxplayer'可能是派生一個新的進程。如果是這種情況,您可能不得不搜索其pid,以表明它是否沒有提供關閉它的機制。 – JimB

+0

使用'pstree -p'查看'omxplayer'(如果有)分叉的進程。 – putu

+0

父進程也可能需要清理,但是您不會通過發送SIGKILL來讓它進行清理。看看SIGTERM或SIGINT會發生什麼。 – JimB

回答

1

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() 

基於this Medium post