【问题标题】:getcontext und setcontext won't work in functionsgetcontext 和 setcontext 在函数中不起作用
【发布时间】:2013-06-05 22:35:00
【问题描述】:

我正在尝试复制一个线程的上下文,包括堆栈以创建一个检查点,稍后我可以恢复该检查点。出于这个原因,我尝试将 getcontext 和 setcontext 的调用移动到一个也保存堆栈的函数中,但这不起作用。

来自维基百科的工作示例:

#include <stdio.h>
#include <ucontext.h>
#include <unistd.h>

int main(int argc, const char *argv[]){
    ucontext_t context;

    getcontext(&context);
    puts("Hello world");
    sleep(1);
    setcontext(&context);
    return 0;
}

这只是重复打印“Hello world”。

我想做这样的事情:

#include <stdio.h>
#include <ucontext.h>
#include <unistd.h>

void set_context(ucontext_t * ct)
{
    setcontext(ct);
}

void get_context(ucontext_t * ct)
{
    getcontext(ct);
}

int main()
{
    ucontext_t context;

    get_context(&context);
    puts("Hello world");
    sleep(1);
    set_context(&context);
    return 0;
}

但这只会打印一次“Hello world”并退出。

现在我被困住了。提前致谢。

【问题讨论】:

    标签: c linux ucontext


    【解决方案1】:

    一旦调用getcontext 的函数返回,保存的上下文就无效了。这些函数的文档中对此进行了说明。

    【讨论】:

    • 在实践中,它可能看起来可以与内联函​​数一起使用,但你是在编译器的心血来潮。它仍然是未定义的行为。
    【解决方案2】:

    因为您使用了堆栈指针地址,该地址会在函数结束时消失。改用 ucontext_t **

    【讨论】:

      【解决方案3】:

      当您使用 getcontext() 保存上下文时,所有寄存器等都存储在提供的上下文中。这确实意味着堆栈上的内容被保存了——你只有一个堆栈。

      当您使用 setcontext() 时,寄存器会恢复,但您的堆栈上仍然有相同的内容。由于您调用了 set_context(),返回指令指针位于堆栈上,因此您设置了所有寄存器的内容,但堆栈上的内容保持不变。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-24
        • 1970-01-01
        • 1970-01-01
        • 2011-08-14
        • 2011-02-01
        • 1970-01-01
        相关资源
        最近更新 更多