【问题标题】:Can't trap SIGTERM with sigaction function无法使用 sigaction 函数捕获 SIGTERM
【发布时间】:2015-05-19 18:03:54
【问题描述】:

我编译了程序。启动它并等待。我打开另一个终端,并使用命令“kill pid”或“kill -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;
}

【问题讨论】:

  • 您的代码运行良好?
  • 是的,我运行正常。
  • 我正在阅读和关注这里:airtower.wordpress.com/2010/06/16/catch-sigterm-exit-gracefully。但不能让 SIGTERM 打印“完成”。
  • 你的程序完美地捕捉到了SIGTERM。我不清楚你需要什么。
  • 请问您在哪个平台上观察这个,使用哪个构建命令?

标签: c signals sigterm


【解决方案1】:

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

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)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 2018-10-29
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    相关资源
    最近更新 更多