Skip to content

Instantly share code, notes, and snippets.

@adililhan
Created October 17, 2022 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adililhan/451bafd20587ca5db62de1b649abddfa to your computer and use it in GitHub Desktop.
Save adililhan/451bafd20587ca5db62de1b649abddfa to your computer and use it in GitHub Desktop.
non-reentrant function block signal
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
int sum;
int calculate(int first, int second) {
sum = first + second;
sleep(3); // represent I/O intensive function call
return sum;
}
void signal_handler(int signal_number) {
sum = 50 + 60;
printf("Interrupt caught!\n");
printf("Result from signal_handler: %d\n", sum);
printf("---\n");
}
int main()
{
sigset_t prevMask, blockMask;
sigemptyset(&blockMask);
sigaddset(&blockMask, SIGINT);
struct sigaction sa;
sa.sa_handler = signal_handler;
sa.sa_flags = SA_RESTART;
if(sigaction(SIGINT, &sa, NULL) == -1) {
perror("sigaction");
exit(EXIT_FAILURE);
}
for (;;) {
if (sigprocmask(SIG_BLOCK, &blockMask, &prevMask) == -1) {
perror("sigprocmask");
}
printf("Result from main: %d\n", calculate(3, 5));
printf("---\n");
if(sigprocmask(SIG_SETMASK, &prevMask, NULL) == -1) {
perror("sigprocmask");
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment