Skip to content

Instantly share code, notes, and snippets.

@maksimuimin
Created May 1, 2024 08:34
Show Gist options
  • Save maksimuimin/c14b066b0b454ac7a1962631c3a238bb to your computer and use it in GitHub Desktop.
Save maksimuimin/c14b066b0b454ac7a1962631c3a238bb to your computer and use it in GitHub Desktop.
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
static jmp_buf buf;
void handler(int sig) {
printf("Got signal: %s\n", strsignal(sig));
longjmp(buf, 1);
}
#define _EXCEPTION_HANDLER(_handler) \
({ \
struct sigaction _act = { \
.sa_handler = _handler, \
.sa_flags = SA_RESETHAND, \
}; \
/* Список сигналов об ошибках */ \
sigaction(SIGABRT, &_act, NULL); \
sigaction(SIGSEGV, &_act, NULL); \
sigaction(SIGFPE, &_act, NULL); \
sigaction(SIGILL, &_act, NULL); \
sigaction(SIGBUS, &_act, NULL); \
})
#define TRY \
_EXCEPTION_HANDLER(handler); \
do { \
if (!setjmp(buf))
#define CATCH \
else
#define FINALLY \
} while (0); \
_EXCEPTION_HANDLER(SIG_DFL)
#define THROW abort
int main()
{
TRY {
printf("Try 1\n");
// Программа может кинуть исключение
THROW();
} CATCH {
printf("Exception 1\n");
} FINALLY;
TRY {
printf("Try 2\n");
} CATCH {
printf("Exception 2\n");
} FINALLY;
TRY {
printf("Try 3\n");
// Эмулируем segmentation fault
kill(getpid(), SIGSEGV);
} CATCH {
printf("Exception 3\n");
} FINALLY;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment