gpt4 book ai didi

c - `longjmp` 进入终止函数

转载 作者:太空狗 更新时间:2023-10-29 12:17:01 26 4
gpt4 key购买 nike

Michael Kerrisk 的“Linux 编程接口(interface)”中的练习 6.2 要求:

Write a program to see what happens if we try to longjmp() into a function that has already terminated.

我在想这个程序应该可以解决问题:

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

static jmp_buf env;

void foo (void);
void bar (void);
void baz (void);

int
main (int argc, char *argv[])
{
foo();
bar();

exit(EXIT_SUCCESS);
}

void
foo (void)
{
printf("foo start\n");

switch (setjmp(env)) {
case 0:
printf("foo branch 0\n");
break;
case 1:
printf("foo branch 1\n");
break;
}

printf("foo end\n");
return;
}

void
bar (void)
{
printf("bar start\n");

baz();

printf("bar end\n");
return;
}

void
baz (void)
{
printf("baz start\n");

longjmp(env, 1);

printf("baz end\n");
return;
}

相反,它会打印:

$ ./setjmp
foo start
foo branch 0
foo end
bar start
baz start
foo branch 1
foo end

也就是说,如果 foo 没有终止,我所期望的行为。这是为什么?如何修改我的程序以将 longjmp 实现为终止函数?

最佳答案

Wikipedia .与一粒盐一起服用。

Jumping to a function that has already terminated by return or longjmp is undefined.[6] However, most implementations of longjmp do not specifically destroy local variables when performing the jump. Since the context survives until its local variables are erased, it could actually be restored by setjmp.

幸运的是,他们确实引用了(尽管是旧的)标准。

§7.13.2.1/2

The longjmp function restores the environment saved by the most recent invocation of the setjmp macro in the same invocation of the program with the corresponding jmp_buf argument. If there has been no such invocation, or if the function containing the invocation of the setjmp macro has terminated execution211) in the interim, or if the invocation of the setjmp macro was within the scope of an identifier with variably modified type and execution has left that scope in the interim, the behavior is undefined.

211) For example, by executing a return statement or because another longjmp call has caused a transfer to a setjmp invocation in a function earlier in the set of nested calls.

关于c - `longjmp` 进入终止函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21150743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com