add exec expand module

This commit is contained in:
siddontang 2014-04-22 15:03:07 +08:00
parent 0c336c59bf
commit d6a86f7340
2 changed files with 50 additions and 0 deletions

36
exec/exec.go Normal file
View File

@ -0,0 +1,36 @@
package exec
import (
"os/exec"
"time"
)
//exec another process
//if wait d Duration, it will kill the process
//d is <= 0, wait forever
func ExecTimeout(d time.Duration, name string, args ...string) error {
cmd := exec.Command(name, args...)
if err := cmd.Start(); err != nil {
return err
}
if d <= 0 {
return cmd.Wait()
}
done := make(chan error)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(d):
cmd.Process.Kill()
//wait goroutine return
return <-done
case err := <-done:
return err
}
}

14
exec/exec_test.go Normal file
View File

@ -0,0 +1,14 @@
package exec
import (
"strings"
"testing"
"time"
)
func TestExec(t *testing.T) {
err := ExecTimeout(1*time.Second, "sleep", "10")
if err != nil && !strings.Contains(err.Error(), "signal: killed") {
t.Fatal(err)
}
}