Hi,
I'm learning to use the setjmp/longjmp functions and still can't
really grasp what's going on here. I'd basically like to be able to
jump back and forth from (or to) two given functions.
Let's consider the following toy-example (yes, the example is stupid
but never mind...)
BEGIN CODE =====================
#include <stdlib.h>
#include <stdio.h>
#include <setjmp.h>
void wrapper();
void ping(jmp_buf, jmp_buf);
void pong(jmp_buf, jmp_buf);
int main() {
wrapper();
return 0;
}
void ping(jmp_buf ping_env, jmp_buf pong_env) {
printf("calling ping\n");
switch (setjmp(ping_env)) {
case 0:
printf("ping: case 0\n");
pong(ping_env, pong_env);
break;
case 1:
printf("ping: case 1\n");
longjmp(pong_env, 1);
break;
case 2:
printf("ping: case 2\n");
longjmp(pong_env, 2);
break;
default:
printf("ping: case default\n");
break;
}
printf("ping is done\n");
}
void pong(jmp_buf ping_env, jmp_buf pong_env) {
printf("\tcalling pong\n");
switch (setjmp(pong_env)) {
case 0:
printf("\tpong: case 0\n");
longjmp(ping_env, 1);
break;
case 1:
printf("\tpong: case 1\n");
longjmp(ping_env, 2);
break;
case 2:
printf("\tpong: case 2\n");
longjmp(ping_env, 3);
break;
default:
printf("\tpong: case default\n");
break;
}
printf("pong is done\n");
}
void wrapper() {
jmp_buf pong_env;
jmp_buf ping_env;
ping(ping_env, pong_env);
}
END CODE ========================
This code works OK if I make ping_env and pong_env static global
variables. However, when I try to pass them as parameters the code
crash with a "Bus error".
Any explanation as to why it crashes? (Well, I guess that's because
the jmp_buf variables passed as parameters are somehow not properly
restored, but I'm new to this so...)
And, even better, any advise on how to correct this while keeping the
intent of the program? (Yeah, I know any real-life application of this
pattern would yield pretty awful code but that's not the matter
here...)
Thanks,
nch