From 1a0e7452f3e7367b30d3d62cab23dcd4e0bb6d8c Mon Sep 17 00:00:00 2001 From: David Hill Date: Thu, 5 May 2016 15:16:42 -0400 Subject: [PATCH] btcd: handle signal SIGTERM (#688) When an OS reboots or shuts down, it sends all processes SIGTERM before sending SIGKILL. This allows btcd to do a proper shutdown which most importantly closes the database. --- signal.go | 15 ++++++++++----- signalsigterm.go | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 5 deletions(-) create mode 100644 signalsigterm.go diff --git a/signal.go b/signal.go index 0c527b27..64cb900e 100644 --- a/signal.go +++ b/signal.go @@ -16,6 +16,10 @@ var interruptChannel chan os.Signal // to be invoked on SIGINT (Ctrl+C) signals. var addHandlerChannel = make(chan func()) +// signals defines the default signals to catch in order to do a proper +// shutdown. +var signals = []os.Signal{os.Interrupt} + // mainInterruptHandler listens for SIGINT (Ctrl+C) signals on the // interruptChannel and invokes the registered interruptCallbacks accordingly. // It also listens for callback registration. It must be run as a goroutine. @@ -32,16 +36,17 @@ func mainInterruptHandler() { for { select { - case <-interruptChannel: + case sig := <-interruptChannel: // Ignore more than one shutdown signal. if isShutdown { - btcdLog.Infof("Received SIGINT (Ctrl+C). " + - "Already shutting down...") + btcdLog.Infof("Received signal (%s). "+ + "Already shutting down...", sig) continue } isShutdown = true - btcdLog.Infof("Received SIGINT (Ctrl+C). Shutting down...") + btcdLog.Infof("Received signal (%s). Shutting down...", + sig) // Run handlers in LIFO order. for i := range interruptCallbacks { @@ -74,7 +79,7 @@ func addInterruptHandler(handler func()) { // all other callbacks and exits if not already done. if interruptChannel == nil { interruptChannel = make(chan os.Signal, 1) - signal.Notify(interruptChannel, os.Interrupt) + signal.Notify(interruptChannel, signals...) go mainInterruptHandler() } diff --git a/signalsigterm.go b/signalsigterm.go new file mode 100644 index 00000000..7aaa39a7 --- /dev/null +++ b/signalsigterm.go @@ -0,0 +1,16 @@ +// Copyright (c) 2016 The btcsuite developers +// Use of this source code is governed by an ISC +// license that can be found in the LICENSE file. + +// +build darwin dragonfly freebsd linux netbsd openbsd solaris + +package main + +import ( + "os" + "syscall" +) + +func init() { + signals = []os.Signal{os.Interrupt, syscall.SIGTERM} +}