1 # Copyright (C) 2019-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 package PublicInbox::Sigfd;
5 use parent qw(PublicInbox::DS);
6 use fields qw(sig); # hashref similar to %SIG, but signal numbers as keys
7 use PublicInbox::Syscall qw(signalfd EPOLLIN EPOLLET SFD_NONBLOCK);
11 # returns a coderef to unblock signals if neither signalfd or kqueue
14 my ($class, $sig, $flags) = @_;
15 my $self = fields::new($class);
18 # SIGWINCH is 28 on FreeBSD, NetBSD, OpenBSD
19 my $num = ($_ eq 'WINCH' && $^O =~ /linux|bsd/i) ? 28 : do {
26 my $fd = signalfd(-1, [keys %signo], $flags);
27 if (defined $fd && $fd >= 0) {
28 $io = IO::Handle->new_from_fd($fd, 'r+');
29 } elsif (eval { require PublicInbox::DSKQXS }) {
30 $io = PublicInbox::DSKQXS->signalfd([keys %signo], $flags);
32 return; # wake up every second to check for signals
34 if ($flags & SFD_NONBLOCK) { # it can go into the event loop
35 $self->SUPER::new($io, EPOLLIN | EPOLLET);
36 } else { # master main loop
39 $self->{sig} = \%signo;
43 # PublicInbox::Daemon in master main loop (blocking)
46 # 128 == sizeof(struct signalfd_siginfo)
47 my $r = sysread($self->{sock}, my $buf, 128 * 64);
49 my $nr = $r / 128 - 1; # $nr may be -1
50 for my $off (0..$nr) {
51 # the first uint32_t of signalfd_siginfo: ssi_signo
52 my $signo = unpack('L', substr($buf, 128 * $off, 4));
53 my $cb = $self->{sig}->{$signo};
54 $cb->($signo) if $cb ne 'IGNORE';
60 # called by PublicInbox::DS in epoll_wait loop
62 while (wait_once($_[0])) {} # non-blocking