Documentation
¶
Overview ¶
Package signals provides utility functions for handling OS signals.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Context ¶
Context returns an iterator that creates a new context from the parent context each time in the loop, then passes it to the loop body. The context passed to the loop body will be cancelled when one of the specified signals is received.
The iterator yields a new context and the loop index.
Control passes immediately into the loop body. This is different from Wait.
After receiving a signal, Get returns it.
Example ¶
package main import ( "context" "fmt" "syscall" "time" "github.com/goaux/iter/signals" ) func main() { go func() { pid := syscall.Getpid() time.Sleep(300 * time.Millisecond) fmt.Println("SIGUSR1") syscall.Kill(pid, syscall.SIGUSR1) time.Sleep(100 * time.Millisecond) fmt.Println("SIGUSR2") syscall.Kill(pid, syscall.SIGUSR2) time.Sleep(100 * time.Millisecond) fmt.Println("SIGINT") syscall.Kill(pid, syscall.SIGINT) }() for ctx := range signals.Context(context.TODO(), syscall.SIGINT) { fmt.Println("start loop") for ctx, i := range signals.Context(ctx, syscall.SIGUSR1, syscall.SIGUSR2) { fmt.Printf("%d enter body. signal:%v\n", i, signals.Get(ctx)) <-ctx.Done() fmt.Printf("%d leave body. signal:%v\n", i, signals.Get(ctx)) } fmt.Printf("finish loop. signal:%v\n", signals.Get(ctx)) break } }
Output: start loop 0 enter body. signal:<nil> SIGUSR1 0 leave body. signal:user defined signal 1 1 enter body. signal:<nil> SIGUSR2 1 leave body. signal:user defined signal 2 2 enter body. signal:<nil> SIGINT 2 leave body. signal:<nil> finish loop. signal:interrupt
func Get ¶
Get retrieves the signal stored in the context, if any. It returns nil if no signal is stored.
func Wait ¶
Wait returns an iterator that waits for the specified signals and passes the received signal to the loop body along with the loop index.
The iterator yields the loop index and the received signal.
Example ¶
package main import ( "context" "fmt" "syscall" "time" "github.com/goaux/iter/signals" ) func main() { go func() { pid := syscall.Getpid() time.Sleep(200 * time.Millisecond) fmt.Println("SIGHUP") syscall.Kill(pid, syscall.SIGHUP) time.Sleep(100 * time.Millisecond) fmt.Println("SIGINT") syscall.Kill(pid, syscall.SIGINT) }() for i, si := range signals.Wait(context.TODO(), syscall.SIGHUP, syscall.SIGINT) { fmt.Println(i, si) if si == syscall.SIGINT { break } } }
Output: SIGHUP 0 hangup SIGINT 1 interrupt
Types ¶
This section is empty.