Can';带sigaction函数的t陷阱SIGTERM

Can';带sigaction函数的t陷阱SIGTERM,c,signals,sigterm,C,Signals,Sigterm,我编译了这个程序。开始并等待。我打开另一个终端,并使用命令“kill-pid”或“kill-15pid”或“kill-SIGTERM-pid”(用实际进程ID替换pid)终止任何正在运行的程序。终止的程序正在退出,但无法捕获SIGTERM以打印“完成” 我在这里复制代码: 需要帮忙吗?我很感激所有的回答 #include <signal.h> #include <stdio.h> #include <string.h> #include <unistd.

我编译了这个程序。开始并等待。我打开另一个终端,并使用命令“kill-pid”或“kill-15pid”或“kill-SIGTERM-pid”(用实际进程ID替换pid)终止任何正在运行的程序。终止的程序正在退出,但无法捕获SIGTERM以打印“完成”

我在这里复制代码:

需要帮忙吗?我很感激所有的回答

#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;
}
#包括
#包括
#包括
#包括
挥发性sig_原子_t done=0;
无效期限(整数符号)
{
完成=1;
}
int main(int argc,char*argv[])
{
结构动作;
memset(&action,0,sizeof(struct-sigaction));
action.sa_handler=术语;
sigation(SIGTERM和action,NULL);
int循环=0;
而(!完成)
{
int t=睡眠(3);
/*sleep返回剩余的秒数,如果
*中断*/
而(t>0)
{
printf(“循环运行被%d中断”
“还剩一秒,完成…\n”,t);
t=睡眠(t);
}
printf(“已完成循环运行%d.\n”,循环++);
}
printf(“完成。\n”);
返回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
以及我在那里注册的所有其他信号(到
sigaddset
sigaction
)。

您的代码工作正常吗?是的,我正常运行它。我正在阅读以下内容:。但无法捕获SIGTERM以打印“完成”。您的程序完美地捕获了
SIGTERM
。我不清楚你需要什么。请问你在哪个平台上观察到这个,使用哪个构建命令?