I'm writing my own echo server
using sockets and syscalls. I am using epoll
to work with many different clients at the same time and all the operations done with clients are nonblocking. When the server is on and doing nothing, it is in epoll_wait
. Now I want to add the possibility to shut the server down using signals. For example, I start the server in bash terminal
, then I press ctrl-c
and the server somehow handles SIGINT
. My plan is to use signalfd
. I create new signalfd
and add it to epoll
instance with the following code:
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGTERM);
sigaddset(&mask, SIGINT);
signal_fd = signalfd(-1, &mask, 0);
epoll_event event;
event.data.fd = signal_fd;
event.events = EPOLLIN;
epoll_ctl(fd, EPOLL_CTL_ADD, signal_fd, &event);
Then I expect, that when epoll
is waiting and I press ctrl-c
, event on epoll
happens, it wakes up and then I handle the signal with the following code:
if (events[i].data.fd == signal_fd)
{
//do something
exit(0);
}
Though in reality the server just stops without handling the signal. What am I doing wrong, what is the correct way to solve my problem? And if I'm not understanding signals correctly, what is the place, where the one should use signalfd
?
Normally, the set of signals to be received via the file descriptor should be blocked using sigprocmask(2), to prevent the signals being handled according to their default dispositions.
– Recollectsigprocmask
solved all the problems! – Continental