Joseph
Joseph

Reputation: 3959

Using Go to determine if a process/program has been terminated

I am making a small desktop web application with Go. This application will run as a local web server and a Chrome window will be generated in 'app' mode. The Go program will continue to run the web server during this time.

I need to watch for the moment the user kills this Chrome window, so that the web server can close down too.

I've made a comment below showing where I need assistance.

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!")
}

Upvotes: 0

Views: 732

Answers (1)

nussjustin
nussjustin

Reputation: 2100

You can use the Wait() function on cmdExec to wait for the child process to exit.

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!")
}

Tested it locally with Chromium. After closing the browser window, it takes a few seconds before the Chromium process exists and then Wait() returns.

Upvotes: 2

Related Questions