从信号处理程序尝试`longjmp`时停止工作

时间:2013-07-25 15:54:26

标签: c

这是我的代码:

#include <stdio.h>
#include <setjmp.h>
#include <signal.h>

jmp_buf buf;

void handler(int s);

int main(int argc, char **argv) {
    signal(SIGINT, handler);
    if (setjmp(buf)) {
        printf("back again!\n");
        return 0;
    } else {
        printf("first here.\n");
    }

    for (;;) {}
}

void handler(int s) {
    longjmp(buf, 1);
}

我在Windows 8 64bit的VS 2012下编译它。每次按Control + C,程序都不会按预期重新启动,但会停止工作。有人能帮助我吗?

2 个答案:

答案 0 :(得分:2)

从目前的C标准来看:

  

如果信号发生而不是因为调用中止或   提升函数,如果信号处理程序引用,则行为未定义   任何具有非静态或线程存储持续时间的对象   除了通过为对象赋值之外的无锁原子对象   声明为volatile sig_atomic_t,或者信号处理程序调用any   除了中止函数之外的标准库中的函数   _Exit函数,quick_exit函数或信号函数,第一个参数等于对应的信号编号   导致调用处理程序的信号。

您正在使用静态存储持续时间不在允许类型列表(buf)中的对象,并且您使用的标准库函数不在允许的函数列表中({{1 }})。

答案 1 :(得分:0)

我想你想要的是这个。

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

static int k;

void
handler(int s)
{
    k++;
}

int
main(int argc, char *argv[])
{
    int n = 0;

    signal(SIGINT, handler);

    while (1) {
        if (k > n) { 
            printf("handler got called %d\n", k);
            n = k;
            if (k == 5) {
                break; /* break out after five control-c */
            }
        }
    }

    exit(0);
}

尝试一下,让我知道它是怎么回事。