Last active
June 1, 2017 09:46
-
-
Save jomonjohnn/1948bf813a29906eae97 to your computer and use it in GitHub Desktop.
Signal handling in Linux with signalfd #c #Linux #Signals
This file contains 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
/* Signal handling with signalfd() | |
* Original Source : http://741mhz.com/signal-handler/ | |
*/ | |
#include <signal.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/signalfd.h> | |
#include <unistd.h> | |
#define handle_error(msg) \ | |
do { perror(msg); exit(EXIT_FAILURE); } while(0) | |
int main(int argc, char *argv[]) | |
{ | |
// Mask to specify what signals are affected. | |
sigset_t mask; | |
int sfd; | |
struct signalfd_siginfo fdsi; | |
ssize_t s; | |
// Initializes the signal set given by set to empty, | |
// with all the signals excluded from the set. | |
sigemptyset(&mask); | |
// add signals to the set | |
sigaddset(&mask, SIGINT); | |
sigaddset(&mask, SIGQUIT); | |
// Block signals so that they aren't handled | |
// according to their default dispositions | |
if(sigprocmask(SIG_BLOCK, &mask, NULL) == -1) | |
handle_error("sigprocmask"); | |
// Create a file descriptor for accepting signals | |
sfd = signalfd(-1, &mask, 0); | |
if(sfd == -1) | |
handle_error("signalfd"); | |
for(;;){ | |
// Read from file descriptor | |
s = read(sfd, &fdsi, sizeof(struct signalfd_siginfo)); | |
if(s != sizeof(struct signalfd_siginfo)) | |
handle_error("read"); | |
switch(fdsi.ssi_signo){ | |
case SIGINT: | |
printf("Got SIGINT \n"); | |
break; | |
case SIGQUIT: | |
printf("Got SIGQUIT \n"); | |
break; | |
default: | |
printf("Oops...!\n"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment