我正在尝试使用 swapcontext() 创建一个简单的 hello world 示例
这是代码片段:
#include <ucontext.h>
#include <stdio.h>
#include <stdlib.h>
static ucontext_t uctx_main, uctx_func1;
typedef struct test_struct
{
ucontext_t context;
int value;
}test_struct;
test_struct* array[10];
static void
func1(void)
{
printf("func1: started\n");
printf("func1: TESTING\n");
printf("func1: returning\n");
}
void init()
{
memset(array,NULL,10);
array[0] = (test_struct*)malloc(sizeof(test_struct));
array[0]->value = 10;
getcontext(&array[0]->context);
char* func1_stack = (char*)malloc(sizeof(char)*64);
//char func1_stack[64];
array[0]->context.uc_stack.ss_sp = func1_stack;
array[0]->context.uc_stack.ss_size = 64;
array[0]->context.uc_link = &uctx_main;
makecontext(&array[0]->context, func1, 0);
}
int main(int argc, char *argv[])
{
init();
printf("VALUE: %d\n",array[0]->value);
swapcontext(&uctx_main, &array[0]->context);
printf("VALUE: %d\n",array[0]->value);
printf("main: exiting\n");
exit(0);
}
但问题是当程序执行 swapcontext()
时发生段错误。我摆弄了一下,发现问题是我分配给上下文的堆栈大小,但我不知道我做错了什么。
附言我已经尝试分配 sizeof(func1_stack)
但仍然出现段错误
谁能给我一个提示?
最佳答案
使用 64 作为编码的堆栈大小与实际给定的堆栈大小一致。然而,64 字节对于堆栈来说是相当小的。 example here使用 16K 作为堆栈大小。可能是您使用的尺寸太小了。
顺便说一句,memset
可能不正确。它设置数组的前 10 个字节。它实际上并没有影响任何东西,但它可能应该是以下内容:
memset(array,0,sizeof(array)));
关于c - swapcontext() 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763970/