Setjmp and longjmp - understanding with examples

I know the definition of setjmp and longjmp. setjmp saves the environment in the context of the stack, and the other restores.

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

I saw that many processor registers are specified in jmp_buf. But how can I guarantee that it is restored?

Please help me explain with neat examples. I googled and referred to other stack overflow issues, but none of them provide clear examples.

Thank you so much in advance.

PS: This should only be from a Linux / Unix context.

+6
source share
1 answer

When longjmp() is called, all of these registers are restored automatically, and execution continues when setjmp() called, but this time setjmp() has a different return value (similar to how fork() has different return values ​​in the parent and child) .

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

+6
source

Source: https://habr.com/ru/post/893985/


All Articles