C 语言中 setjmp 和 longjmp
setjmp, sigsetjmp - save stack context for nonlocal goto
SYNOPSIS
#include <setjmp.h>
int setjmp(jmp_buf env);
int sigsetjmp(sigjmp_buf env, int savesigs);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
setjmp(): see NOTES.
sigsetjmp(): _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_C_SOURCE
DESCRIPTION
setjmp() and longjmp(3) are useful for dealing with errors and interrupts encountered in a low-level subroutine of a program. setjmp() saves the stack context/environment in env for later use
by longjmp(3). The stack context will be invalidated if the function which called setjmp() returns.
sigsetjmp() is similar to setjmp(). If, and only if, savesigs is nonzero, the process's current signal mask is saved in env and will be restored if a siglongjmp(3) is later performed with
this env.
RETURN VALUE
setjmp() and sigsetjmp() return 0 if returning directly, and nonzero when returning from longjmp(3) or siglongjmp(3) using the saved context.
代码示例:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <setjmp.h> int main() { jmp_buf env; int i; i = setjmp(env); printf("i = %d ", i); if (i != 0) exit(0); longjmp(env, 2); printf("this line does not get printed "); return 0; }
输出结果:
[root@dvrdvs nfs] # ./jmp
i = 0
i = 2
aa