简体   繁体   中英

Logging a message from SIGTERM

What's the proper way to log a shutdown message when an application (a C++ daemon, in my case) receives a SIGTERM or SIGINT?

According to CERT and the signal(7) manpage , many functions (including, presumably, those used by most logging libraries) aren't safe to call from signal handlers.

Vlad Lazarenko wrote a great blog post earlier this year on this very topic. On Linux it boils down to creating a signal descriptor with signalfd(2) and use an event loop such as poll(2) or epoll_wait(2) . Here is Vlad's example reading from the descriptor

#include <sys/signalfd.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

#define handle_error(msg)                               \
    do { perror(msg); exit(EXIT_FAILURE); } while (0)

int
main(int argc, char *argv[])
{
    sigset_t mask;
    int sfd;
    struct signalfd_siginfo fdsi;
    ssize_t s;

    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGQUIT);

    /* Block signals so that they aren't handled
       according to their default dispositions */

    if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1)
        handle_error("sigprocmask");

    sfd = signalfd(-1, &mask, 0);
    if (sfd == -1)
        handle_error("signalfd");

    for (;;) {
        s = read(sfd, &fdsi, sizeof(struct signalfd_siginfo));
        if (s != sizeof(struct signalfd_siginfo))
            handle_error("read");

        if (fdsi.ssi_signo == SIGINT) {
            printf("Got SIGINT\n");
        } else if (fdsi.ssi_signo == SIGQUIT) {
            printf("Got SIGQUIT\n");
            exit(EXIT_SUCCESS);
        } else {
            printf("Read unexpected signal\n");
        }
    }
}

This example can easily be extended to integrate into an event loop.

Logging could be done not from handler, but after it:

int received_sigterm = 0;

void
sigterm_handler(int sig)
{
  received_sigterm = 1;
}

void
loop(void)
{
  for(;;) {
    sleep(1);
    if (received_sigterm)
      log("finish\n");
  }
}

int
main()
{
  log("start\n");
  signal(SIGTERM, sigterm_handler);
  loop();
}

The concept is borrowed from openssh-6.1 sources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM