I could not know when the command will return the result, and a default timer is set. Then I have this question.
sigChan := make(os.Signal, 1)
signal.Notify(sigChan, SIGCHLD)
cmd := exec.Command(...)
cmd.Start()
select {
case <-time.After(1e9):
// kill the process and release?
case <-sigChan:
// the process has been terminated
}
Use exec.CommandContext()
if you want to terminate the command after a timeout.
Then, you need to wait until the command returns to get its result. So, use cmd.Run()
instead of cmd.Start()
. If blocking is a concern, then spawn a goroutine that blocks and waits for the command to terminate.
For instance:
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, ...)
err := cmd.Run()
//Process error or results
}()