Skip to content

Commit 8129339

Browse files
authored
Merge pull request #915 from devlights/add-signal-stop
2 parents 06c95d7 + 561af85 commit 8129339

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

examples/basic/signals/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@
66
| ---------------- | --------------------- | ---------------------------------------------------------- |
77
| notify.go | signal_notify | signal.Notify のサンプルです |
88
| notifycontext.go | signal_notify_context | Go 1.16 から追加された signal.NotifyContext のサンプルです |
9+
| stop.go | signal_stop | signal.Stop()のサンプルです |

examples/basic/signals/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@ func NewRegister() mapping.Register {
1515
func (r *register) Regist(m mapping.ExampleMapping) {
1616
m["signal_notify"] = Notify
1717
m["signal_notify_context"] = NotifyContext
18+
m["signal_stop"] = Stop
1819
}

examples/basic/signals/stop.go

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package signals
2+
3+
import (
4+
"log"
5+
"os"
6+
"os/signal"
7+
"syscall"
8+
"time"
9+
)
10+
11+
// Stop は、signal.Stop()のサンプルです.
12+
//
13+
// signal.Notify()などでハンドル処理を追加した場合
14+
// ファイルの場合と同様に defer で signal.Stop() を呼ぶべき。
15+
//
16+
// > Stop causes package signal to stop relaying incoming signals to c.
17+
// It undoes the effect of all prior calls to Notify using c. When Stop returns, it is guaranteed that c will receive no more signals.
18+
//
19+
// > Stopは、パッケージ・シグナルがcへの受信シグナルのリレーを停止させる。
20+
// ストップが戻れば、cはそれ以上シグナルを受け取らないことが保証される。
21+
//
22+
// # REFERENCES
23+
// - https://pkg.go.dev/os/[email protected]#Stop
24+
func Stop() error {
25+
var (
26+
l = log.New(os.Stderr, "", log.Lmicroseconds)
27+
pid = os.Getpid()
28+
sigs = make(chan os.Signal, 1)
29+
30+
sendSig = func() {
31+
l.Println(">> SIGUSR1")
32+
_ = syscall.Kill(pid, syscall.SIGUSR1)
33+
}
34+
stopSig = func() {
35+
l.Println(">> signal.Stop")
36+
signal.Stop(sigs)
37+
}
38+
)
39+
defer close(sigs)
40+
41+
signal.Notify(sigs, syscall.SIGUSR1, syscall.SIGUSR2)
42+
go func() {
43+
l.Printf("Signal recv: %v\n", <-sigs)
44+
}()
45+
46+
l.Println("<START>")
47+
{
48+
sendSig()
49+
stopSig()
50+
sendSig()
51+
}
52+
time.Sleep(1 * time.Second)
53+
l.Println("< END >")
54+
55+
/*
56+
$ task
57+
task: [build] go build -o "/workspaces/try-golang/try-golang" .
58+
task: [run] ./try-golang -onetime
59+
60+
ENTER EXAMPLE NAME: signal_stop
61+
62+
[Name] "signal_stop"
63+
06:03:32.489167 <START>
64+
06:03:32.489314 >> SIGUSR1
65+
06:03:32.489326 >> signal.Stop
66+
06:03:32.489444 >> SIGUSR1
67+
06:03:32.489442 Signal recv: user defined signal 1
68+
06:03:33.489539 < END >
69+
70+
71+
[Elapsed] 1.000858245s
72+
*/
73+
74+
return nil
75+
}

0 commit comments

Comments
 (0)