开发者

Why didn't this program receive SIGTERM on init/reboot/shutdown?

开发者 https://www.devze.com 2023-02-27 14:23 出处:网络
I need to intercept reboot or shutdown. The prgram is like this: void sig_handler(int sig) { if (sig == SIGTERM) {

I need to intercept reboot or shutdown. The prgram is like this:

void sig_handler(int sig) {
    if (sig == SIGTERM) {
        /* do something */
    }
}

int main() {
    ....
    signal(SIGTERM, sig_handler);

    /* daemon */
    pid = fork();
    if (pid > 0) exit(EXIT_SUCCESS);
    // I didn't do setsid() to retain process group id.
    ....
}

This works when I tested by 'kill -15 '. However, when I tried 'reboot' or 'shutdown' command, it never received the signal. The init man page says:

"When init is requested to change the runlevel, it sends the warning signal SIGTERM to all processes that are undefined in the new runlevel. It then waits 5 seconds before forcibly terminating these processes via the SIGKILL signal. Note that init assumes that all these processes (and their descendants) remain in the same process group which init originally开发者_StackOverflow created for them. If any process changes its process group affiliation it will not receive these signals. Such processes need to be terminated separately."

How to tell init daemon to send SIGTERM to this program? My guess is I should set process group id to something init knows, but how can I do that?


If your program is not started by the init system, it won't be managed by the init system. Launch it from an init.d script to get the benefits described.

0

精彩评论

暂无评论...
验证码 换一张
取 消