我正在使用 Go 制作一个小型桌面 Web 应用程序。此应用程序将作为本地网络服务器运行,并且将以“应用程序”模式生成一个 Chrome 窗口。 Go 程序将在此期间继续运行 Web 服务器。
我需要注意用户关闭此 Chrome 窗口的那一刻,以便网络服务器也可以关闭。
我在下方发表了评论,指出了我需要帮助的地方。
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!")
}
最佳答案
您可以使用 Wait() cmdExec 函数等待子进程退出。
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 对其进行了测试。关闭浏览器窗口后,Chromium 进程需要几秒钟才能存在,然后 Wait() 返回。
关于go - 使用 Go 确定进程/程序是否已终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36371073/