]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Sigfd.pm
sigfd: set SIGWINCH for MIPS and PA-RISC on Linux
[public-inbox.git] / lib / PublicInbox / Sigfd.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
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;
7 use strict;
8 use parent qw(PublicInbox::DS);
9 use PublicInbox::Syscall qw(signalfd EPOLLIN EPOLLET %SIGNUM);
10 use POSIX ();
11
12 # returns a coderef to unblock signals if neither signalfd or kqueue
13 # are available.
14 sub new {
15         my ($class, $sig, $nonblock) = @_;
16         my %signo = map {;
17                 # $num => $cb;
18                 ($SIGNUM{$_} // POSIX->can("SIG$_")->()) => $sig->{$_}
19         } keys %$sig;
20         my $self = bless { sig => \%signo }, $class;
21         my $io;
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);
27         } else {
28                 return; # wake up every second to check for signals
29         }
30         if ($nonblock) { # it can go into the event loop
31                 $self->SUPER::new($io, EPOLLIN | EPOLLET);
32         } else { # master main loop
33                 $self->{sock} = $io;
34                 $self;
35         }
36 }
37
38 # PublicInbox::Daemon in master main loop (blocking)
39 sub wait_once ($) {
40         my ($self) = @_;
41         # 128 == sizeof(struct signalfd_siginfo)
42         my $r = sysread($self->{sock}, my $buf, 128 * 64);
43         if (defined($r)) {
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';
50                 }
51         }
52         $r;
53 }
54
55 # called by PublicInbox::DS in epoll_wait loop
56 sub event_step {
57         while (wait_once($_[0])) {} # non-blocking
58 }
59
60 1;