Skip to content

Instantly share code, notes, and snippets.

@alekc
Created May 21, 2020 08:36
Show Gist options
  • Save alekc/5378e60595d4c876939d0d3549392f40 to your computer and use it in GitHub Desktop.
Save alekc/5378e60595d4c876939d0d3549392f40 to your computer and use it in GitHub Desktop.
Manage the life of a spawned process in go
// Start a process:
cmd := exec.Command("sleep", "5")
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(3 * 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