Skip to content
This repository has been archived by the owner on Apr 12, 2019. It is now read-only.

Use exec.CommandContext for timeout control #41

Merged
merged 1 commit into from
Apr 7, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 6 additions & 21 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package git

import (
"bytes"
"context"
"fmt"
"io"
"os/exec"
Expand Down Expand Up @@ -58,34 +59,18 @@ func (c *Command) RunInDirTimeoutPipeline(timeout time.Duration, dir string, std
log("%s: %v", dir, c)
}

cmd := exec.Command(c.name, c.args...)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

cmd := exec.CommandContext(ctx, c.name, c.args...)
cmd.Dir = dir
cmd.Stdout = stdout
cmd.Stderr = stderr
if err := cmd.Start(); err != nil {
return err
}

done := make(chan error)
go func() {
done <- cmd.Wait()
}()

var err error
select {
case <-time.After(timeout):
if cmd.Process != nil && cmd.ProcessState != nil && !cmd.ProcessState.Exited() {
if err := cmd.Process.Kill(); err != nil {
return fmt.Errorf("fail to kill process: %v", err)
}
}

<-done
return ErrExecTimeout{timeout}
case err = <-done:
}

return err
return cmd.Wait()
}

// RunInDirTimeout executes the command in given directory with given timeout,
Expand Down