无法使用sigaction功能捕获SIGTERM

时间:2015-03-17 10:36:28

标签: c signals sigterm

我编译了程序。开始等待。我打开另一个终端,用命令" kill pid"杀死任何正在运行的程序。或"杀死-15 pid"或" kill -SIGTERM pid" (将PID替换为实际进程ID)。被杀死的程序退出,但无法捕获SIGTERM打印"完成。"。

我在这里复制代码:https://airtower.wordpress.com/2010/06/16/catch-sigterm-exit-gracefully/

我可以帮你吗?我很感激所有答案。

#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

volatile sig_atomic_t done = 0;

void term(int signum)
{
    done = 1;
}

int main(int argc, char *argv[])
{
    struct sigaction action;
    memset(&action, 0, sizeof(struct sigaction));
    action.sa_handler = term;
    sigaction(SIGTERM, &action, NULL);

    int loop = 0;
    while (!done)
    {
        int t = sleep(3);
        /* sleep returns the number of seconds left if
         * interrupted */
        while (t > 0)
        {
            printf("Loop run was interrupted with %d "
                "sec to go, finishing...\n", t);
            t = sleep(t);
        }
        printf("Finished loop run %d.\n", loop++);
    }

    printf("done.\n");
    return 0;
}

1 个答案:

答案 0 :(得分:0)

您需要正确设置信号处理程序,以便处理要捕获的信号。这就是我做信号处理程序的方式:

static void handle_signal(int signum); //in header, then implement

//in the source file
struct sigaction myaction;
myaction.sa_handler = handle_signal;
myaction.sa_flags = 0; //or whatever flags you want but do it here so the signals you register see these flags

sigset_t mask;
sigemptyset(&mask);

sigaddset(&mask, SIGTERM);
sigaction(SIGTERM, &myaction, NULL);

myaction.sa_mask = mask;

我能够捕捉SIGTERM以及我在那里注册的所有其他信号(sigaddsetsigaction)。