-
Notifications
You must be signed in to change notification settings - Fork 0
/
withcontext.go
68 lines (53 loc) · 1.34 KB
/
withcontext.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package cmdexec
import (
"context"
"errors"
"os/exec"
"runtime"
"time"
"github.com/devlights/gomy/output"
)
// WithContext は、context.Context 付きでコマンドを実行するサンプルです。
func WithContext() error {
if runtime.GOOS == "windows" {
return errors.New("this example cannot run on Windows, sorry")
}
const (
Shell = "/bin/bash"
)
var (
rootCtx = context.Background()
mainCtx, mainCxl = context.WithCancel(rootCtx)
procCtx, procCxl = context.WithTimeout(mainCtx, 500*time.Millisecond)
)
defer mainCxl()
defer procCxl()
var (
cmd *exec.Cmd // コマンド
err error // エラー
)
//
// コマンドは2秒かかるようにして実行するが、渡している context は 500ms でタイムアウトする
//
cmd = exec.CommandContext(procCtx, Shell, "-c", "sleep 2")
err = cmd.Run()
if err != nil {
var exitErr *exec.ExitError
if errors.Is(procCtx.Err(), context.DeadlineExceeded) && errors.As(err, &exitErr) {
output.Stdoutf("[timeout]", "%[1]v(%[1]T)\n", err)
return nil
} else {
return err
}
}
return nil
/*
$ task
task: [build] go build .
task: [run] ./try-golang -onetime
ENTER EXAMPLE NAME: cmdexec_withcontext
[Name] "cmdexec_withcontext"
[timeout] signal: killed(*exec.ExitError)
[Elapsed] 501.067449ms
*/
}