From c91ea933cdf107ae34431aa8b93c3aca9bada016 Mon Sep 17 00:00:00 2001 From: asandikci Date: Mon, 31 Jul 2023 16:20:07 +0300 Subject: [PATCH] feat: add signal handler --- go-daemon/godaemon1.go | 3 +++ go-daemon/service/sighandler.go | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 go-daemon/service/sighandler.go diff --git a/go-daemon/godaemon1.go b/go-daemon/godaemon1.go index 99432a7..9b42d43 100644 --- a/go-daemon/godaemon1.go +++ b/go-daemon/godaemon1.go @@ -1,6 +1,7 @@ package main import ( + "godaemon1/service" "log" "time" @@ -26,6 +27,8 @@ func main() { } defer cntxt.Release() + service.SigHandler() + log.Print("- - - - - - - - - - - - - - -") log.Print("daemon started") diff --git a/go-daemon/service/sighandler.go b/go-daemon/service/sighandler.go new file mode 100644 index 0000000..965943e --- /dev/null +++ b/go-daemon/service/sighandler.go @@ -0,0 +1,34 @@ +package service + +import ( + "log" + "os" + "os/signal" + "syscall" +) + +func handler(signal os.Signal) { + if signal == syscall.SIGTERM { + log.Println("Got signal: SIGTERM") + } else if signal == syscall.SIGINT { + log.Println("Got signal: SIGINT") + } else { + log.Println("Got another signal") + } +} + +func SigHandler() { + sigChannel := make(chan os.Signal, 1) + signal.Notify(sigChannel) + exitChannel := make(chan int) + + go func() { + for { + s := <-sigChannel + handler(s) + } + }() + + exitcode := <-exitChannel + os.Exit(exitcode) +}