Domanda

i am trying to copy the context of a thread including the stack to create a checkpoint, which i can restore later on. For that reason i tried to move the call of getcontext and setcontext into a function which also saves the stack, but that wont work.

Working example from wikipedia:

#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;
}

This just repeatingly prints "Hello world".

I would like to do something like:

#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;
}

But this just prints "Hello world" once and exits.

Now I am stuck. Thanks in advance.

È stato utile?

Soluzione

The saved context is invalid once the function that called getcontext returns. This is explained in the documentation for these functions.

Altri suggerimenti

Cause you use a stack pointer address, which gonna disappear when the function ends. Use ucontext_t ** instead

When you save the context using getcontext() all registers etc are stored in the provided context. This does mean that the content on the stack is saved - you only have one stack.

When you us setcontext() the registers are restored but you still have the same content on your stack. Since you have made a call to set_context() the return instruction pointer is on the stack, you set the content of all registers but the content on the stack remains the same.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top