C++ 为什么';t SIGINT处理程序在我的代码中工作吗?

C++ 为什么';t SIGINT处理程序在我的代码中工作吗?,c++,linux,ubuntu,signals,C++,Linux,Ubuntu,Signals,我需要我的命令行应用程序在主线程中等待Ctrl-C,然后执行一些去初始化代码并退出 我使用以下测试程序测试了此场景: #include <unistd.h> #include <signal.h> #include <cstdlib> #include <cstdio> #include <cassert> using namespace std; void control_break_handler(int) { printf("

我需要我的命令行应用程序在主线程中等待Ctrl-C,然后执行一些去初始化代码并退出

我使用以下测试程序测试了此场景:

#include <unistd.h>
#include <signal.h>
#include <cstdlib>
#include <cstdio>
#include <cassert>

using namespace std;

void control_break_handler(int) { printf("\ncontrol_break_handler\n"); }

int main()
{
    printf("%s", "Before signal\n");

    int result = 0;

    struct sigaction sigact = {};
    result = sigemptyset(&sigact.sa_mask);
    assert(result == 0);
    sigact.sa_handler = &control_break_handler;
    sigact.sa_flags = 0;
    result = sigaction(SIGINT, &sigact, NULL);
    assert(result == 0);

    sigset_t set;
    result = sigemptyset(&set);
    assert(result == 0);
    result = sigaddset(&set, SIGINT);
    assert(result == 0);
    int sig;
    result = sigwait(&set, &sig);
    assert(result == 0);
    printf("\nsigwait returned %d, sig = %d\n", result, sig);

    sleep(10);

    return 0;
}
在第一个Ctrl-C之后,仅在第二个Ctrl-C之后调用“control\u break\u处理程序”。 如何在第一个Ctrl-C上执行去初始化代码? 我使用Ubuntu 13.04 x64


编辑:好的,看来我已经弄明白了。我扔掉了
sigaction
,在
sigwait
之前添加了对
sigprocmask
的调用。它似乎工作正常。

不要使用sigwait。你已经注册了信号处理程序,如果信号出现,它将在你的应用程序退出之前被调用。但是主线程和整个应用程序将立即退出。你的意思是我必须重新设计应用程序来等待工作线程而不是SIGINT吗?另外,mask还设置了
sa.sa_flags=sa_RESTART
如果被处理程序中断,则重新启动函数(作为异步调用的处理程序)@user835103欢迎您。。。使用printf是代码中的直接问题。请记住,始终在信号处理程序中调用安全函数,并且处理程序应该小而简单。
sigwait returned 0, sig = 2