setjmp和longjmp-通过示例进行理解 [英] setjmp and longjmp - understanding with examples

查看:52
本文介绍了setjmp和longjmp-通过示例进行理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道setjmp和longjmp的定义.setjmp将环境存储在堆栈上下文中,而另一个还原.

但是我认为我有些地方缺乏理解.有人可以在良好的例子帮助下向我解释我如何保证,如何保存以及如何恢复它吗?

我看到jmp_buf中指向了很多CPU寄存器.但是我如何确保它已恢复?

请帮助我用简洁的例子进行解释.我用谷歌搜索并提到了其他与堆栈溢出有关的问题,但没有一个给出清晰的例子.

非常感谢.

P.S:应该仅来自Linux/Unix上下文.

解决方案

调用 longjmp()时,所有这些寄存器都将自动恢复,并且在对 setjmp(),但这次 setjmp()具有不同的返回值(类似于 fork()在父级和子级中具有不同的返回值).

setjmp()/ longjmp()仅保存有限的环境.特别是,它们仅保存堆栈指针,而不是完整堆栈,因此您只能返回相同的函数或调用函数.POSIX具有 setcontext(),它允许在堆栈之间进行切换,从而使它对于实现诸如用户空间线程(原纤维,绿色线程等)之类的东西更加有用.

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.

解决方案

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

这篇关于setjmp和longjmp-通过示例进行理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆