Created
June 14, 2020 18:33
-
-
Save danesparza/c6c1a5a10d8fc3274dc85a0e5515bf46 to your computer and use it in GitHub Desktop.
Start (and kill) a command with arguments from go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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