Created
May 21, 2020 08:36
-
-
Save alekc/5378e60595d4c876939d0d3549392f40 to your computer and use it in GitHub Desktop.
Manage the life of a spawned process in go
This file contains hidden or 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
// 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