Skip to content

Instantly share code, notes, and snippets.

@riturajborpujari
Created December 23, 2025 05:39
Show Gist options
  • Select an option

  • Save riturajborpujari/b0c2987a826bd134e5a10f108bc80bb1 to your computer and use it in GitHub Desktop.

Select an option

Save riturajborpujari/b0c2987a826bd134e5a10f108bc80bb1 to your computer and use it in GitHub Desktop.
POSIX signal handling in C
#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