1 # Copyright (C) 2019-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Wraps a signalfd (or similar) for PublicInbox::DS
5 # fields: (sig: hashref similar to %SIG, but signal numbers as keys)
6 package PublicInbox::Sigfd;
8 use parent qw(PublicInbox::DS);
9 use PublicInbox::Syscall qw(signalfd EPOLLIN EPOLLET);
12 # returns a coderef to unblock signals if neither signalfd or kqueue
15 my ($class, $sig, $nonblock) = @_;
18 # SIGWINCH is 28 on FreeBSD, NetBSD, OpenBSD
19 my $num = ($_ eq 'WINCH' && $^O =~ /linux|bsd/i) ? 28 : do {
25 my $self = bless { sig => \%signo }, $class;
27 my $fd = signalfd([keys %signo], $nonblock);
28 if (defined $fd && $fd >= 0) {
29 open($io, '+<&=', $fd) or die "open: $!";
30 } elsif (eval { require PublicInbox::DSKQXS }) {
31 $io = PublicInbox::DSKQXS->signalfd([keys %signo], $nonblock);
33 return; # wake up every second to check for signals
35 if ($nonblock) { # it can go into the event loop
36 $self->SUPER::new($io, EPOLLIN | EPOLLET);
37 } else { # master main loop
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