Skip to content

Instantly share code, notes, and snippets.

@Luzifer
Created July 22, 2016 09:20
Show Gist options
  • Save Luzifer/f6ffc37537da1e987d877289a02c18e6 to your computer and use it in GitHub Desktop.
Save Luzifer/f6ffc37537da1e987d877289a02c18e6 to your computer and use it in GitHub Desktop.
Test for executing commands while using a context to terminate them within a certain time
package main
import (
"log"
"os/exec"
"strconv"
"time"
"golang.org/x/net/context"
)
func main() {
basectx := context.Background()
ctx1, cancel1 := context.WithTimeout(basectx, 10*time.Second)
defer cancel1()
log.Printf("Context: 10s, Sleep: 5s, Expected: <nil>, Actual: %v", ex(ctx1, 5))
ctx2, cancel2 := context.WithTimeout(basectx, 10*time.Second)
defer cancel2()
log.Printf("Context: 10s, Sleep: 60s, Expected: error, Actual: %s", ex(ctx2, 60))
}
func ex(ctx context.Context, sleeptime int) error {
cmd := exec.Command("/bin/bash", "-c", "sleep "+strconv.Itoa(sleeptime))
cmd.Start()
cmdDone := make(chan error)
go func(cmdDone chan error, cmd *exec.Cmd) { cmdDone <- cmd.Wait() }(cmdDone, cmd)
for {
select {
case err := <-cmdDone:
return err
case <-ctx.Done():
cmd.Process.Kill()
}
}
}
// Output:
// # go run main.go
// 2016/07/22 11:08:07 Context: 10s, Sleep: 5s, Expected: <nil>, Actual: <nil>
// 2016/07/22 11:08:17 Context: 10s, Sleep: 60s, Expected: error, Actual: signal: killed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment