github.com/aergoio/aergo@v1.3.1/internal/common/signal.go (about)

     1  package common
     2  
     3  import (
     4  	"os"
     5  	"os/signal"
     6  	"syscall"
     7  
     8  	"github.com/aergoio/aergo-lib/log"
     9  )
    10  
    11  type interrupt struct {
    12  	C chan struct{}
    13  }
    14  
    15  // HandleKillSig gets killing signals (interrupt, quit and terminate) and calls
    16  // a registered handler function for cleanup. Finally, this will exit program
    17  func HandleKillSig(handler func(), logger *log.Logger) interrupt{
    18  	i := interrupt{
    19  		C:make(chan struct{}),
    20  	}
    21  	sigChannel := make(chan os.Signal, 1)
    22  
    23  	signal.Notify(sigChannel, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
    24  	go func() {
    25  		for signal := range sigChannel {
    26  			logger.Info().Msgf("Receive signal %s, Shutting down...", signal)
    27  			handler()
    28  			close(i.C)
    29  		}
    30  	}()
    31  	return i
    32  }