setjmp and longjmp - understanding with examples

蓝咒 提交于 2019-12-08 17:41:29

问题


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, ...).



来源:https://stackoverflow.com/questions/6890892/setjmp-and-longjmp-understanding-with-examples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!