Created
December 23, 2025 05:39
-
-
Save riturajborpujari/b0c2987a826bd134e5a10f108bc80bb1 to your computer and use it in GitHub Desktop.
POSIX signal handling in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <signal.h> | |
| #include <unistd.h> | |
| struct sigaction old; | |
| void onSignalTstp(int signal) | |
| { | |
| // handle signal, attach old (default) handler and re-raise the signal | |
| printf("Signal received: SIGTSTP(%d)\n", signal); | |
| sigaction(SIGTSTP, &old, NULL); | |
| raise(SIGTSTP); | |
| } | |
| void onSignalCont(int signal) | |
| { | |
| // handle signal, re-attach handler for SIGTSTP | |
| printf("Signal received: SIGCONT(%d)\n", signal); | |
| struct sigaction tstp = {0}; | |
| tstp.sa_handler = onSignalTstp; | |
| sigaction(SIGTSTP, &tstp, &old); | |
| } | |
| int main() | |
| { | |
| // attach handler for SIGTSTP | |
| struct sigaction tstp = {0}; | |
| tstp.sa_handler = onSignalTstp; | |
| sigaction(SIGTSTP, &tstp, &old); | |
| // another handler for SIGCONT | |
| struct sigaction cont = {0}; | |
| cont.sa_handler = onSignalCont; | |
| sigaction(SIGCONT, &cont, NULL); | |
| int i = 0; | |
| while (true) { | |
| printf("Counting %d\n", i++); | |
| sleep(1); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment