1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
| | # Copyright (C) all contributors <meta@public-inbox.org>
# License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
# Wraps a signalfd (or similar) for PublicInbox::DS
# fields: (sig: hashref similar to %SIG, but signal numbers as keys)
package PublicInbox::Sigfd;
use v5.12;
use parent qw(PublicInbox::DS);
use PublicInbox::Syscall qw(signalfd EPOLLIN EPOLLET %SIGNUM);
use POSIX ();
# returns a coderef to unblock signals if neither signalfd or kqueue
# are available.
sub new {
my ($class, $sig) = @_;
my %signo = map {;
# $num => [ $cb, $signame ];
($SIGNUM{$_} // POSIX->can("SIG$_")->()) => [ $sig->{$_}, $_ ]
} keys %$sig;
my $self = bless { sig => \%signo }, $class;
my $io;
my $fd = signalfd([keys %signo]);
if (defined $fd && $fd >= 0) {
open($io, '+<&=', $fd) or die "open: $!";
} elsif (eval { require PublicInbox::DSKQXS }) {
$io = PublicInbox::DSKQXS->signalfd([keys %signo]);
} else {
return; # wake up every second to check for signals
}
$self->SUPER::new($io, EPOLLIN | EPOLLET);
$self->{is_kq} = 1 if tied(*$io);
$self;
}
# PublicInbox::Daemon in master main loop (blocking)
sub wait_once ($) {
my ($self) = @_;
# 128 == sizeof(struct signalfd_siginfo)
my $r = sysread($self->{sock}, my $buf, 128 * 64);
if (defined($r)) {
my $nr = $r / 128 - 1; # $nr may be -1
for my $off (0..$nr) {
# the first uint32_t of signalfd_siginfo: ssi_signo
my $signo = unpack('L', substr($buf, 128 * $off, 4));
my ($cb, $signame) = @{$self->{sig}->{$signo}};
$cb->($signame) if $cb ne 'IGNORE';
}
}
$r;
}
# called by PublicInbox::DS in epoll_wait loop
sub event_step {
while (wait_once($_[0])) {} # non-blocking
}
1;
|