Skip to content

Commit d455e41

Browse files
zhsjtklauser
authored andcommitted
unix: add SignalNum to convert signal name to a number
Fixes golang/go#28027 Change-Id: Idf8b554e0fd102fd8b2f2f2ea0fa47bf139303da Reviewed-on: https://go-review.googlesource.com/c/164778 Run-TryBot: Tobias Klauser <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Tobias Klauser <[email protected]>
1 parent b688937 commit d455e41

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

unix/syscall_unix.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ var (
2828
errENOENT error = syscall.ENOENT
2929
)
3030

31+
var (
32+
signalNameMapOnce sync.Once
33+
signalNameMap map[string]syscall.Signal
34+
)
35+
3136
// errnoErr returns common boxed Errno values, to prevent
3237
// allocations at runtime.
3338
func errnoErr(e syscall.Errno) error {
@@ -66,6 +71,19 @@ func SignalName(s syscall.Signal) string {
6671
return ""
6772
}
6873

74+
// SignalNum returns the syscall.Signal for signal named s,
75+
// or 0 if a signal with such name is not found.
76+
// The signal name should start with "SIG".
77+
func SignalNum(s string) syscall.Signal {
78+
signalNameMapOnce.Do(func() {
79+
signalNameMap = make(map[string]syscall.Signal)
80+
for _, signal := range signalList {
81+
signalNameMap[signal.name] = signal.num
82+
}
83+
})
84+
return signalNameMap[s]
85+
}
86+
6987
// clen returns the index of the first NULL byte in n or len(n) if n contains no NULL byte.
7088
func clen(n []byte) int {
7189
i := bytes.IndexByte(n, 0)

unix/syscall_unix_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,27 @@ func TestErrnoSignalName(t *testing.T) {
9898
}
9999
}
100100

101+
func TestSignalNum(t *testing.T) {
102+
testSignals := []struct {
103+
name string
104+
want syscall.Signal
105+
}{
106+
{"SIGHUP", syscall.SIGHUP},
107+
{"SIGPIPE", syscall.SIGPIPE},
108+
{"SIGSEGV", syscall.SIGSEGV},
109+
{"NONEXISTS", 0},
110+
}
111+
for _, ts := range testSignals {
112+
t.Run(fmt.Sprintf("%s/%d", ts.name, ts.want), func(t *testing.T) {
113+
got := unix.SignalNum(ts.name)
114+
if got != ts.want {
115+
t.Errorf("SignalNum(%s) returned %d, want %d", ts.name, got, ts.want)
116+
}
117+
})
118+
119+
}
120+
}
121+
101122
func TestFcntlInt(t *testing.T) {
102123
t.Parallel()
103124
file, err := ioutil.TempFile("", "TestFnctlInt")

0 commit comments

Comments
 (0)