Can anyone explain me why do we use setjmp and longjump functions.
I read through the manual pages/doc but wasnt able to get a clear
picture of the same.
setjmp and longjmp are a long-distance version of goto, and
therefore they are greatly frowned upon by the Structured Programming Police.
jmp_buf buf;
some_type_t *p;
if (setjmp(buf) == 0) {
/* try something that might get an error */
...
p = malloc(sizeof(*p));
if (p == NULL) {
longjmp(buf, 1); /* we got an error */
}
...
} else {
/* we got an error, (someone called longjmp) handle it */
/* e.g. use the slow, file-based method instead of */
/* the in-memory method */
}
The tricky thing you can do with longjmp, though, is that it
can be called from functions called from the /* try something that
might get an error */ code. The functions signalling the error
need not have any idea where the error handler is (although they
do need to know where buf is, either passed as a parameter or a
static or global.)
Another tricky thing that can be done, and isn't portable, is to
catch signals and have the signal handler call longjmp(). This
way, the /* we got an error, handle it */ part might correct for
division by zero, overflow, or dereferencing NULL. Or it might
just note that it crashed and log the error.
void sigsegv_handler(int sig) {
/* you're pretty much stuck with buf being a global or */
/* static variable here, as you can't change the parameters */
longjmp(buf, 1);
}
Yet another tricky thing involves a stack of jmp_bufs and nested
error handlers.
Any small example illustrating these would be real helping.
Also, what happens when one jumps from one process/task to other, even though
it is OT can anybody clear this concept.
In general, you DON'T jump from one process/task to another. Other
programs aren't in your address space. And if you try, expect a
real mess.
Gordon L. Burditt