1 # Copyright (C) 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 %SIGNUM);
12 # returns a coderef to unblock signals if neither signalfd or kqueue
15 my ($class, $sig, $nonblock) = @_;
18 ($SIGNUM{$_} // POSIX->can("SIG$_")->()) => $sig->{$_}
20 my $self = bless { sig => \%signo }, $class;
22 my $fd = signalfd([keys %signo], $nonblock);
23 if (defined $fd && $fd >= 0) {
24 open($io, '+<&=', $fd) or die "open: $!";
25 } elsif (eval { require PublicInbox::DSKQXS }) {
26 $io = PublicInbox::DSKQXS->signalfd([keys %signo], $nonblock);
28 return; # wake up every second to check for signals
30 if ($nonblock) { # it can go into the event loop
31 $self->SUPER::new($io, EPOLLIN | EPOLLET);
32 } else { # master main loop
38 # PublicInbox::Daemon in master main loop (blocking)
41 # 128 == sizeof(struct signalfd_siginfo)
42 my $r = sysread($self->{sock}, my $buf, 128 * 64);
44 my $nr = $r / 128 - 1; # $nr may be -1
45 for my $off (0..$nr) {
46 # the first uint32_t of signalfd_siginfo: ssi_signo
47 my $signo = unpack('L', substr($buf, 128 * $off, 4));
48 my $cb = $self->{sig}->{$signo};
49 $cb->($signo) if $cb ne 'IGNORE';
55 # called by PublicInbox::DS in epoll_wait loop
57 while (wait_once($_[0])) {} # non-blocking