Skip to content

Instantly share code, notes, and snippets.

@jelford
Created October 31, 2021 12:20
Show Gist options
  • Save jelford/d8850f357c26ee6840290f7ad89c097b to your computer and use it in GitHub Desktop.
Save jelford/d8850f357c26ee6840290f7ad89c097b to your computer and use it in GitHub Desktop.
A small app that demonstrates using signalfd to handle signals in a normal thread context
// Error handling omitted for brevity
// compile with: gcc signalfd.c -o signalfd
#include <sys/signalfd.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <poll.h>
void handle_signal(int signal_fd)
{
struct signalfd_siginfo siginfo;
ssize_t s;
s = read(signal_fd, &siginfo, sizeof(siginfo));
if (s != sizeof(siginfo))
{
perror("read");
exit(1);
}
uint32_t signo = siginfo.ssi_signo;
char *signame = strsignal(signo);
printf("Received signal %d (%s)\n", signo, signame);
}
int main()
{
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigprocmask(SIG_SETMASK, &mask, NULL);
int signal_fd = signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC);
struct pollfd pollfd = {
.fd = signal_fd,
.events = POLLIN,
};
while (poll(&pollfd, 1, 5000) > 0)
{
handle_signal(pollfd.fd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment