Created
October 17, 2012 19:15
-
-
Save jordanorelli/3907512 to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"log" | |
"fmt" | |
"os/exec" | |
"time" | |
) | |
type TimeoutError struct { | |
D time.Duration | |
Killed bool | |
} | |
func (e *TimeoutError) Error() string { | |
return "command timed out" | |
} | |
func TimeoutCmd(cmd *exec.Cmd, d time.Duration) error { | |
e := make(chan error) | |
go func() { | |
if err := cmd.Start(); err != nil { | |
e <- err | |
return | |
} | |
fmt.Println("command started with pid ", cmd.Process.Pid) | |
if err := cmd.Wait(); err != nil { | |
fmt.Println("error waiting for child process to start", err) | |
e <- err | |
return | |
} | |
e <- nil | |
}() | |
select { | |
case <-time.After(d): | |
// if you uncomment this block, the program will cause a kernel | |
// panic consistently on OS X: | |
// if err := cmd.Process.Release(); err != nil { | |
// return err | |
// } | |
if err := cmd.Process.Kill(); err != nil { | |
return &TimeoutError{D: d, Killed: false} | |
} | |
return &TimeoutError{D: d, Killed: true} | |
case err := <-e: | |
return err | |
} | |
panic("not reached") | |
} | |
func main() { | |
cmd := exec.Command("git", "clone", "https://github.com/404user/404repo") | |
if err := TimeoutCmd(cmd, 3*time.Second); err != nil { | |
log.Fatal(err) | |
} | |
log.Println("command completed.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment