2016-04-02 67 views
0

我正在用Go製作一個小型桌面Web應用程序。此應用程序將作爲本地Web服務器運行,Chrome窗口將以「應用程序」模式生成。 Go程序將在此期間繼續運行Web服務器。使用Go來確定過程/程序是否已被終止

我需要注意用戶殺死此Chrome窗口的時刻,以便Web服務器也可以關閉。

我在下面發表了一條評論,說明我需要幫助的地方。

package main 

import (
    "fmt" 
    "os/exec" 
) 

func main(){ 
    // Setup the application and arguments. 
    cmd := "chrome" 
    // URL will be local webserver. 
    args := []string{"--user-data-dir=c:\\","--window-size=800,600","--app=http://www.google.com"} 

    // Start local webserver here. 
    // ... 

    // Prepare Chrome in app mode. 
    cmdExec := exec.Command(cmd, args...); 

    // Start Chrome asynchronously. 
    cmdExec.Start() 

    // Show to the user on the command line that the application is running. 
    fmt.Println("Application in progress! Please close webapp to close webserver!") 

    // Keep the webserver running, do web app things... 

    // Watch for that process we started earlier. If the user closes that Chrome window 
    // Then alert the user that the webserver is now closing down. 

    // This is where I need help! 
    watchForProcessThatWeStartedEarlierForClosure...()//????   

    // And we are done! 
    fmt.Println("Application exit!") 
} 
+0

考慮到Chrome的多進程架構,這可能有點棘手。也許有網頁定期發送ping通過ajax服務器,並超時如果ping沒有收到? – nishantjr

回答

2

您可以使用cmdExec上的Wait()函數來等待子進程退出。

package main 

import (
    "fmt" 
    "os/exec" 
) 

func main(){ 
    // Setup the application and arguments. 
    cmd := "chrome" 
    // URL will be local webserver. 
    args := []string{"--user-data-dir=c:\\","--window-size=800,600","--app=http://www.google.com"} 

    // Start local webserver here. 
    // ... 

    // Prepare Chrome in app mode. 
    cmdExec := exec.Command(cmd, args...); 

    // Start Chrome asynchronously. 
    cmdExec.Start() 

    // Show to the user on the command line that the application is running. 
    fmt.Println("Application in progress! Please close webapp to close webserver!") 

    // Keep the webserver running, do web app things... 

    // Watch for that process we started earlier. If the user closes that Chrome window 
    // Then alert the user that the webserver is now closing down. 

    // Should probably handle the error here 
    _ = cmdExec.Wait()  

    // And we are done! 
    fmt.Println("Application exit!") 
} 

用鉻對本地進行了測試。在關閉瀏覽器窗口後,Chromium進程存在幾秒鐘,然後Wait()返回。