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>
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 $SFD_NONBLOCK);
10 use POSIX qw(:signal_h);
13 # returns a coderef to unblock signals if neither signalfd or kqueue
16 my ($class, $sig, $flags) = @_;
19 # SIGWINCH is 28 on FreeBSD, NetBSD, OpenBSD
20 my $num = ($_ eq 'WINCH' && $^O =~ /linux|bsd/i) ? 28 : do {
26 my $self = bless { sig => \%signo }, $class;
28 my $fd = signalfd(-1, [keys %signo], $flags);
29 if (defined $fd && $fd >= 0) {
30 $io = IO::Handle->new_from_fd($fd, 'r+');
31 } elsif (eval { require PublicInbox::DSKQXS }) {
32 $io = PublicInbox::DSKQXS->signalfd([keys %signo], $flags);
34 return; # wake up every second to check for signals
36 if ($flags & $SFD_NONBLOCK) { # it can go into the event loop
37 $self->SUPER::new($io, EPOLLIN | EPOLLET);
38 } else { # master main loop
44 # PublicInbox::Daemon in master main loop (blocking)
47 # 128 == sizeof(struct signalfd_siginfo)
48 my $r = sysread($self->{sock}, my $buf, 128 * 64);
50 my $nr = $r / 128 - 1; # $nr may be -1
51 for my $off (0..$nr) {
52 # the first uint32_t of signalfd_siginfo: ssi_signo
53 my $signo = unpack('L', substr($buf, 128 * $off, 4));
54 my $cb = $self->{sig}->{$signo};
55 $cb->($signo) if $cb ne 'IGNORE';
61 # called by PublicInbox::DS in epoll_wait loop
63 while (wait_once($_[0])) {} # non-blocking
66 sub sig_setmask { sigprocmask(SIG_SETMASK, @_) or die "sigprocmask: $!" }
68 sub block_signals () {
69 my $oldset = POSIX::SigSet->new;
70 my $newset = POSIX::SigSet->new;
71 $newset->fillset or die "fillset: $!";
72 sig_setmask($newset, $oldset);