go - 使用 Go 确定进程/程序是否已终止

标签 go

我正在使用 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/

相关文章:

go - 如何设置 LiteIDE 以便 Golang 标识符补全跨包工作?

arrays - 在 Golang 中重新 slice

rest - 使用动态段构建休息请求

转到转换为 *ptrdiff_t 的类型?

go - 捕获或分配 golang 模板输出到变量

go - Go 中的三个逗号语法是什么?

http - PDF 下载在 golang 的服务器端不起作用

go - 在缓冲 channel 上使用范围时程序中的死锁

使用 tabwriter 转到文本/模板

golang exec Output() 卡住了,但是 Run() 没问题