mirror of https://github.com/siddontang/go.git
add exec expand module
This commit is contained in:
parent
0c336c59bf
commit
d6a86f7340
|
@ -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
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue