Alessandro Resta
Alessandro Resta

Reputation: 1172

Go - close an external application

I'm using Go on an OSX machine and trying to make a program to open an external application and then after few seconds, close it - the application, not exit the Go script.

I'm using the library available on https://github.com/skratchdot/open-golang to start the app and it works fine. I also already have the timeout running. But the problem comes when I have to close the application.

Would someone give a hint of how I would be able to exit the app?

Thanks in advance.

Upvotes: 2

Views: 1054

Answers (2)

Alessandro Resta
Alessandro Resta

Reputation: 1172

Thank you guys for the help. I would able to do what I was trying with the following code.

cmd := exec.Command(path string)
    err := cmd.Start()
  if err != nil {
    log.Printf("Command finished with error: %v", err)
  }
  done := make(chan error, 1)
  go func() {
    done <- cmd.Wait()
  }()
  select {
  case <-time.After(30 * time.Second):      // Kills the process after 30 seconds
    if err := cmd.Process.Kill(); err != nil {
      log.Fatal("failed to kill: ", err)
    }
    <-done // allow goroutine to exit
    log.Println("process killed")
    indexInit()
    case err := <-done:
      if err!=nil{
        log.Printf("process done with error = %v", err)
      }
  }
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("Waiting for command to finish...")
  //timer() // The time goes by...
    err = cmd.Wait()
}

I placed that right after start the app with the os/exec package as @JimB recommended.

Upvotes: 1

Jake
Jake

Reputation: 2625

It looks like that library is hiding details that you'd use to close the program, specifically the process ID (PID).

If you launch instead with the os/exec package or get a handle on that PID then you can use the Process object to kill or send signals to the app to try and close it gracefully.

https://golang.org/pkg/os/#Process

Upvotes: 2

Related Questions