我正在尝试实现一个协程,但是在我的代码中,我为uc_lick指定了ctx_main,但是在执行与ucontext_t对应的子例程routine2之后,程序直接退出,而不是返回到main函数继续执行。
我已经读过linux手册了。根据我的理解,应该可以在执行子例程后返回main函数,但目前只有routine1在执行后返回main,程序在routine2执行后直接退出。
退出状态码是routine2中最后一个函数的返回值(19,printf的返回值)。为什么会发生这种情况?
#include <stdio.h>
#include <ucontext.h>
typedef void (*coroutine_func)();
#define STACK_SIZE (1<<15)
ucontext_t ctx_main;
ucontext_t c1, c2;
ucontext_t create_ctx(coroutine_func func, ucontext_t *ret_ctx) {
ucontext_t ctx;
getcontext(&ctx);
char stack[STACK_SIZE];
ctx.uc_stack.ss_sp = stack;
ctx.uc_stack.ss_size = sizeof(stack);
ctx.uc_link = ret_ctx;
makecontext(&ctx, func, 0);
return ctx;
}
void routine1() {
printf("routine1 running\n");
swapcontext(&c1, &c2);
printf("routine1 returning\n");
}
void routine2() {
printf("routine2 running\n");
swapcontext(&c2, &c1);
printf("routine2 returning\n"); // return value is 19
}
int main() {
c1 = create_ctx(routine1, &ctx_main);
c2 = create_ctx(routine2, &ctx_main);
swapcontext(&ctx_main, &c1);
swapcontext(&ctx_main, &c2);
// Will not run to here, exit after routine2 is executed.
printf("main exiting.\n");
return 0;
}结果:
routine1 running
routine2 running
routine1 returning
routine2 returning
Process finished with exit code 19发布于 2021-10-11 08:44:32
在变量停止存在后,您正在使用该变量。
ucontext_t create_ctx(coroutine_func func, ucontext_t *ret_ctx) {
char stack[STACK_SIZE]; // allocated on stack
ctx.uc_stack.ss_sp = stack;
return ctx; // ss_sp is invalid pointer
} // variable stack stops existing您必须分配具有足够生命周期的内存。例如:
char *stack = malloc(STACK_SIZE);
ctx.uc_stack.ss_sp = stack;
ctx.uc_stack.ss_size = STACK_SIZE;如何检查:使用杀菌器选项进行编译,它们将帮助您调试程序:
+ gcc -D_FORTIFY_SOURCE=2 -D_GLIBCXX_ASSERTIONS -fstack-clash-protection -fstack-protector-all -fstack-protector-strong -ggdb3 -grecord-gcc-switches -fcf-protection -O -Wall -Wextra -Wwrite-strings -Wno-unused-function -Wno-unused-parameter -Wno-implicit-function-declaration -fsanitize=address,undefined,pointer-compare,pointer-subtract /tmp/1.c
==1265711==WARNING: ASan doesn't fully support makecontext/swapcontext functions and may produce false positives in some cases!
routine1 running
routine2 running
routine2 returning
*** stack smashing detected ***: terminatedhttps://stackoverflow.com/questions/69523192
复制相似问题