繁体   English   中英

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

[英]Stops working when trying to `longjmp` from a signal handler

这是我的代码:

#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,程序都不会按预期重新启动,但会停止工作。 有人能帮助我吗?

从目前的C标准来看:

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

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

我想你想要的是这个。

#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);
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM