setjmp and longjmp - understanding with examples

2019-06-17 03:59发布

问题:

I know the definition of setjmp and longjmp. setjmp stores the environment in stack context and the other one restores.

But i think there is somewhere some lack of understanding in my part. Can someone explain me, with the help of good examples as how can i assure, and how it will be saved and how it will be restored?

I saw the there are a lot of CPU registers pointed in jmp_buf. But how do i assure that it is restored?

Kindly help me to explain with neat examples. I googled and referred to other questions with stack overflow, but none give clear examples.

Huge huge thanks in advance.

P.S: It should be from Linux/ Unix context only.

回答1:

When calling longjmp(), all those registers are restored automatically, and execution continues at the corresponding call to setjmp(), but this time setjmp() has a different return value (similar to how fork() has different return values in parent and child).

setjmp()/longjmp() save only a limited environment. In particular, they just save the stack pointer, not the full stack, so you can only return to the same function or to a calling function. POSIX has setcontext(), which allows to switch between stacks, making it more immediately useful for implementing things like userspace threads (fibrils, green-threads, ...).