Skip to content

Instantly share code, notes, and snippets.

@danesparza
Created June 14, 2020 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danesparza/c6c1a5a10d8fc3274dc85a0e5515bf46 to your computer and use it in GitHub Desktop.
Save danesparza/c6c1a5a10d8fc3274dc85a0e5515bf46 to your computer and use it in GitHub Desktop.
Start (and kill) a command with arguments from go
package main
import (
"log"
"os/exec"
"time"
)
func main() {
// Start a process:
cmd := exec.Command("omxplayer.bin", "--layout", "5.1", "crossbones2.ogg")
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
// Wait for the process to finish or kill it after a timeout (whichever happens first):
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(60 * time.Second):
if err := cmd.Process.Kill(); err != nil {
log.Fatal("failed to kill process: ", err)
}
log.Println("process killed as timeout reached")
case err := <-done:
if err != nil {
log.Fatalf("process finished with error = %v", err)
}
log.Print("process finished successfully")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment