sigaction.c:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
// We can also use:
// typedef void (*SigFunc)(int);
int my_signal(int signo, void (*func)(int))
{
struct sigaction act, oact;
act.sa_handler = func;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
// Setup SIGALRM to interrupt any other system call
if(signo == SIGALRM) {
act.sa_flags |= SA_INTERRUPT;
}
else {
act.sa_flags |= SA_RESTART;
}
if(sigaction(signo, &act, &oact) < 0) {
printf("sigaction error!\n");
return 1;
}
return 0;
}
void sig_quit(int signo)
{
printf("caught SIGQUIT signal!\n");
}
int main(int argc, char* argv[])
{
if(my_signal(SIGQUIT, sig_quit) < 0) {
printf("my_signal error!\n");
exit(1);
}
pause();
exit(0);
}
shell:
The program setup the SIGQUIT signal handler with our self-defined my_signal function, which uses sigaction system call to setup the signal handler. Inside the my_signal, we zero out all sa_mask , indicating that we don't turn off any other signals when executing the signal handler. If the signo is SIGALRM, we setup flags to be SA_INTERRUPT, to make it be able to interrupt any other system calls without re-starting it.
After running the program, we type in Ctrl + \, to send out SIGQUIT signal. And the handler caught signal well.
ubuntu@ip-172-31-23-227:~$ ./mysignal.out
^\caught SIGQUIT signal!
No comments:
Post a Comment