Created
March 2, 2022 08:35
-
-
Save vyskocilm/c0d116c8c4fd99b482590ee99428e322 to your computer and use it in GitHub Desktop.
Catching signals via signal.NotifyContext
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"log" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
func main() { | |
log.Print("setting NotifyContext up") | |
go func() { | |
signal := syscall.SIGKILL | |
log.Printf("goroutine: preparing to send signal %s(%d) to myself", signal, signal) | |
time.Sleep(2 * time.Second) | |
p, err := os.FindProcess(os.Getpid()) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Printf("goroutine: kill %d %d", signal, os.Getpid()) | |
err = p.Signal(signal) | |
if err != nil { | |
log.Fatal(err) | |
} | |
}() | |
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM, syscall.SIGKILL) | |
defer cancel() | |
log.Print("<-ctx.Done()") | |
<-ctx.Done() | |
log.Print("context.Done") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
go build && main
When any other signal is used on line 16 (syscall.SIGTERM), then
context.Done
is printed.