setjmp 和 longjmp - 通过示例进行理解
我知道setjmp和longjmp的定义。 setjmp 将环境存储在堆栈上下文中,另一个恢复。
但我认为我的部分还存在一些缺乏理解的地方。有人可以在很好的例子的帮助下向我解释一下我如何保证、如何保存以及如何恢复吗?
我看到jmp_buf中有很多指向CPU的寄存器。但我如何确保它已恢复?
请帮助我用简洁的例子来解释。我用谷歌搜索并提到了其他有关堆栈溢出的问题,但没有一个给出明确的例子。
预先非常感谢。
PS:它应该仅来自 Linux/Unix 上下文。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当调用
longjmp()
时,所有这些寄存器都会自动恢复,并在相应的setjmp()
调用处继续执行,但这次setjmp() 具有不同的返回值(类似于
fork()
在父级和子级中具有不同的返回值)。setjmp()
/longjmp()
仅保存有限的环境。特别是,它们只保存堆栈指针,而不是完整堆栈,因此您只能返回到同一函数或调用函数。 POSIX 有setcontext()
,它允许在堆栈之间切换,使其对于实现用户空间线程(fibrils、green-threads,...)之类的东西更加立即有用。When calling
longjmp()
, all those registers are restored automatically, and execution continues at the corresponding call tosetjmp()
, but this timesetjmp()
has a different return value (similar to howfork()
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 hassetcontext()
, which allows to switch between stacks, making it more immediately useful for implementing things like userspace threads (fibrils, green-threads, ...).