Recover in C
#include <stdio.h>
#include <setjmp.h>
jmp_buf jump_buffer;
// This function simulates a panic
void may_panic() {
printf("Simulating a panic\n");
longjmp(jump_buffer, 1);
}
int main() {
// setjmp sets up the jump buffer and returns 0
if (setjmp(jump_buffer) == 0) {
// This code will run normally
printf("Calling may_panic()\n");
may_panic();
// This code will not run, because may_panic() "panics"
printf("After may_panic()\n");
} else {
// This code runs if may_panic() "panics"
printf("Recovered. Error:\n a problem\n");
}
return 0;
}
In C, there’s no built-in concept of panic and recover as in some other languages. However, we can simulate similar behavior using the setjmp
and longjmp
functions from the <setjmp.h>
library.
The setjmp
function saves the current execution context, and longjmp
can later be used to return to this saved context, simulating a kind of error recovery mechanism.
In this example:
We define a global
jmp_buf
to store our jump buffer.The
may_panic()
function simulates a panic by callinglongjmp()
.In
main()
, we usesetjmp()
to set up our recovery point. Ifsetjmp()
returns 0, it means we’re setting up the jump buffer for the first time.We then call
may_panic()
, which will trigger our simulated panic.If a panic occurs (simulated by
longjmp()
), execution jumps back to thesetjmp()
call, but this time it returns a non-zero value (in this case, 1).We then handle the “recovered” state by printing an error message.
This approach provides a way to simulate panic and recover behavior in C, although it’s not as clean or safe as in languages with built-in support for these concepts. In practice, C programmers often use other error handling mechanisms, such as error codes or global error states.
To compile and run this program:
$ gcc -o recover recover.c
$ ./recover
Calling may_panic()
Simulating a panic
Recovered. Error:
a problem
Note that using setjmp
and longjmp
can make code harder to understand and maintain, and can lead to issues with local variables. In real-world C programming, it’s often better to use more structured error handling approaches.