Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setjmp and longjmp - understanding with examples

Tags:

linux

unix

setjmp

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.

like image 418
RajSanpui Avatar asked Jul 31 '11 16:07

RajSanpui


People also ask

What is the use of setjmp and longjmp functions with examples?

setjmp and longjmp are a pair of C function facilitating cross-procedure transfer of control. Typically they are used to allow resumption of execution at a known good point after an error. Both take as first argument a buffer, which is used to hold the machine state at the jump destination.

What is setjmp used for?

setjmp saves the current environment (the program state), at some point of program execution, into a platform-specific data structure ( jmp_buf ) that can be used at some later point of program execution by longjmp to restore the program state to that saved by setjmp into jmp_buf .

What is the difference between Goto longjmp and setjmp?

What is the difference between goto and longjmp() and setjmp()? A goto statement implements a local jump of program execution, and the longjmp() and setjmp() functions implement a nonlocal, or far, jump of program execution.

What is setjmp h in C language?

The setjmp. h header defines the macro setjmp(), one function longjmp(), and one variable type jmp_buf, for bypassing the normal function call and return discipline.


1 Answers

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

like image 165
ninjalj Avatar answered Sep 17 '22 15:09

ninjalj