longjmp(buffer,0)不返回0

Arm*_*let 2 c longjmp setjmp

我正在尝试使用setjmp/longjmp做一些简单的事情:要求用户多次按Enter键,如果用户插入其他内容,它将使用longjmp重新启动进程.

我正在使用计数器来检查它是否有效,此计数器在启动时为0,但是当使用longjmp时,计数器将重新启动为1.

#include <stdio.h>
#include <setjmp.h>
jmp_buf buffer;
char inputBuffer[512];

void handle_interrupt(int signal) {
    longjmp(buffer, 0);
}

int main(int argc, const char * argv[]) {
    int counter = 0;
    counter = setjmp(buffer); // Save the initial state.

    printf("Counter: %d\n", counter);

    printf("\nWelcome in the jump game, press enter (nothing else!): \n");
    while (fgets(inputBuffer, sizeof(inputBuffer), stdin)) {
        if (*inputBuffer == '\n') { // If user press Enter
            counter++;
            printf("%d\n\n", counter);
            printf("Again: \n");
        } else {
            handle_interrupt(0);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

pc3:Assignement 3 ArmandG$ ./tictockforever
Counter: 0

Welcome in the jump game, press enter (nothing else!): 

1

Again: 

2

Again: 
StackOverflow
Counter: 1

Welcome in the jump game, press enter (nothing else!): 

2

Again: 
Run Code Online (Sandbox Code Playgroud)

我知道这段代码很傻,我只是想在一个简单的例子中使用setjmp/longjmp.

Ded*_*tor 6

setjmp 直接在第一次返回时仅返回0.

在任何其他情况下,它返回您传递给的任何内容longjmp,除非您传递0:
在这种情况下,它返回1.