From bcde9675e42848ca79e1a14a19daac3f40ecb143 Mon Sep 17 00:00:00 2001 From: Mark Beckwith Date: Wed, 19 Dec 2018 17:15:31 -0600 Subject: [PATCH] Handle SIGINT and SIGTERM for PID 1 Signed-off-by: Mark Beckwith --- lightningd/lightningd.c | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/lightningd/lightningd.c b/lightningd/lightningd.c index 231dca0bb..9b3e37895 100644 --- a/lightningd/lightningd.c +++ b/lightningd/lightningd.c @@ -574,6 +574,38 @@ void notify_new_block(struct lightningd *ld, u32 block_height) channel_notify_new_block(ld, block_height); } +static void on_sigint(int _ UNUSED) +{ + static const char *msg = "lightningd: SIGINT caught, exiting.\n"; + write(STDERR_FILENO, msg, strlen(msg)); + _exit(1); +} + +static void on_sigterm(int _ UNUSED) +{ + static const char *msg = "lightningd: SIGTERM caught, exiting.\n"; + write(STDERR_FILENO, msg, strlen(msg)); + _exit(1); +} + +/*~ We only need to handle SIGTERM and SIGINT for the case we are PID 1 of + * docker container since Linux makes special this PID and requires that + * some handler exist. */ +static void setup_sig_handlers(void) +{ + struct sigaction sigint, sigterm; + memset(&sigint, 0, sizeof(struct sigaction)); + memset(&sigterm, 0, sizeof(struct sigaction)); + + sigint.sa_handler = on_sigint; + sigterm.sa_handler = on_sigterm; + + if (1 == getpid()) { + sigaction(SIGINT, &sigint, NULL); + sigaction(SIGTERM, &sigterm, NULL); + } +} + int main(int argc, char *argv[]) { struct lightningd *ld; @@ -583,6 +615,8 @@ int main(int argc, char *argv[]) /*~ What happens in strange locales should stay there. */ setup_locale(); + setup_sig_handlers(); + /*~ This checks that the system-installed libraries (usually * dynamically linked) actually are compatible with the ones we * compiled with.