...
Source file
src/runtime/debug/example_monitor_test.go
1
2
3
4
5 package debug_test
6
7 import (
8 "io"
9 "log"
10 "os"
11 "os/exec"
12 "runtime/debug"
13 )
14
15
16
17
18
19 func ExampleSetCrashOutput_monitor() {
20 appmain()
21
22
23
24
25
26
27
28
29
30
31
32
33 }
34
35
36 func appmain() {
37 monitor()
38
39
40 println("hello")
41 panic("oops")
42 }
43
44
45
46
47
48
49
50 func monitor() {
51 const monitorVar = "RUNTIME_DEBUG_MONITOR"
52 if os.Getenv(monitorVar) != "" {
53
54 log.SetFlags(0)
55 log.SetPrefix("monitor: ")
56
57 crash, err := io.ReadAll(os.Stdin)
58 if err != nil {
59 log.Fatalf("failed to read from input pipe: %v", err)
60 }
61 if len(crash) == 0 {
62
63 os.Exit(0)
64 }
65
66
67 f, err := os.CreateTemp("", "*.crash")
68 if err != nil {
69 log.Fatal(err)
70 }
71 if _, err := f.Write(crash); err != nil {
72 log.Fatal(err)
73 }
74 if err := f.Close(); err != nil {
75 log.Fatal(err)
76 }
77 log.Fatalf("saved crash report at %s", f.Name())
78 }
79
80
81
82 exe, err := os.Executable()
83 if err != nil {
84 log.Fatal(err)
85 }
86 cmd := exec.Command(exe, "-test.run=ExampleSetCrashOutput_monitor")
87 cmd.Env = append(os.Environ(), monitorVar+"=1")
88 cmd.Stderr = os.Stderr
89 cmd.Stdout = os.Stderr
90 pipe, err := cmd.StdinPipe()
91 if err != nil {
92 log.Fatalf("StdinPipe: %v", err)
93 }
94 debug.SetCrashOutput(pipe.(*os.File), debug.CrashOptions{})
95 if err := cmd.Start(); err != nil {
96 log.Fatalf("can't start monitor: %v", err)
97 }
98
99 }
100
View as plain text