6

我试图了解 getcontext/setcontext 在特定情况下是否可以正常工作。

我可以看到如何使用 setcontext() 将堆栈展开回历史中的某个位置。

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

int  rollback = 0;
ucontext_t context;

void func(void)
{
    setcontext(cp);
}

int main(void)
{
    getcontext(&context);
    if (rollback == 0)
    {
        printf("getcontext has been called\n");
        rollback++;
        func();
    }
    else
    {
        printf("setcontext has been called\n");
    }
}

但我想知道放松后是否可以重新回到未来的某个地方?我想这取决于getcontext()调用捕获堆栈的副本,​​我在文档中找不到确切的详细信息。

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

int  rollback     = 0;
int  backToFuture = 0;
ucontext_t context;
ucontext_t futureContext;

void func(void)
{
    // Some complex calc
    if (some-condition)
    {
        getcontext(&futureContext);  // After returning I want to come back
                                     // here to carry on with my work.
        if (backToFuture == 0)
        {
            setcontext(&context);  // rewind to get stuff-done
        }
    }
    // Finishe work
}

int main(void)
{
    getcontext(&context);
    if (rollback == 0)
    {
        printf("getcontext has been called\n");
        rollback++;
        func();

        // eventually always return here.
    }
    else
    {
        printf("setcontext has been called\n");
        // Do specialized work that needed to be done
        // May involve function calls.
        // 
        // I worry that anything the adds new stack frames
        // will disrupt the saved state of futureContext
        //
        // But without detailed information I can not be sure
        // if this is an allowed senario.
        backToFuture = 1;
        setcontext(&futureContext);
    }
}
4

1 回答 1

4

getcontext不复制堆栈,它只转储寄存器(包括堆栈指针)和一些上下文数据,如信号掩码等。

当您跳下堆栈时,它会使顶部上下文无效。即使您不会进行任何函数调用,也要考虑可以在那里执行的信号处理程序。如果你想在两个堆栈之间跳转,你需要makecontext.

我添加了表明您的代码无效的变量:

void func(void)
{
    // Some complex calc
    if (1)
    {
        volatile int neverChange = 1;
        getcontext(&futureContext);  // After returning I want to come back
                                     // here to carry on with my work.
        printf("neverchange = %d\n", neverChange);
        if (backToFuture == 0)
        {
            setcontext(&context);  // rewind to get stuff-done
        }
    }
    // Finishe work
}

在我的机器上,它导致:

getcontext has been called
neverchange = 1
setcontext has been called
neverchange = 32767
于 2013-02-28T02:48:01.343 回答