X-Git-Url: http://www.git.stargrave.org/?a=blobdiff_plain;f=lib%2FPublicInbox%2FSigfd.pm;h=81e5a1b1dd88e99d25bf37aadbb1f520e8a6503f;hb=1c52f49354aa83e71fcceccae888da0c77f2391d;hp=ec5d7145c1d2bdf27c14ce862f3b86bb07d82f53;hpb=d6674af04cb74a4efd513d938bed8bf7ab2838eb;p=public-inbox.git diff --git a/lib/PublicInbox/Sigfd.pm b/lib/PublicInbox/Sigfd.pm index ec5d7145..81e5a1b1 100644 --- a/lib/PublicInbox/Sigfd.pm +++ b/lib/PublicInbox/Sigfd.pm @@ -1,55 +1,57 @@ -# Copyright (C) 2019 all contributors +# Copyright (C) 2019-2021 all contributors # License: AGPL-3.0+ + +# Wraps a signalfd (or similar) for PublicInbox::DS +# fields: (sig: hashref similar to %SIG, but signal numbers as keys) package PublicInbox::Sigfd; use strict; use parent qw(PublicInbox::DS); -use fields qw(sig); # hashref similar to %SIG, but signal numbers as keys -use PublicInbox::Syscall qw(signalfd EPOLLIN EPOLLET SFD_NONBLOCK); +use PublicInbox::Syscall qw(signalfd EPOLLIN EPOLLET); use POSIX (); -use IO::Handle (); # returns a coderef to unblock signals if neither signalfd or kqueue # are available. sub new { - my ($class, $sig, $flags) = @_; - my $self = fields::new($class); + my ($class, $sig, $nonblock) = @_; my %signo = map {; my $cb = $sig->{$_}; + # SIGWINCH is 28 on FreeBSD, NetBSD, OpenBSD my $num = ($_ eq 'WINCH' && $^O =~ /linux|bsd/i) ? 28 : do { my $m = "SIG$_"; POSIX->$m; }; $num => $cb; } keys %$sig; + my $self = bless { sig => \%signo }, $class; my $io; - my $fd = signalfd(-1, [keys %signo], $flags); + my $fd = signalfd([keys %signo], $nonblock); if (defined $fd && $fd >= 0) { - $io = IO::Handle->new_from_fd($fd, 'r+'); + open($io, '+<&=', $fd) or die "open: $!"; } elsif (eval { require PublicInbox::DSKQXS }) { - $io = PublicInbox::DSKQXS->signalfd([keys %signo], $flags); + $io = PublicInbox::DSKQXS->signalfd([keys %signo], $nonblock); } else { return; # wake up every second to check for signals } - if ($flags & SFD_NONBLOCK) { # it can go into the event loop + if ($nonblock) { # it can go into the event loop $self->SUPER::new($io, EPOLLIN | EPOLLET); } else { # master main loop $self->{sock} = $io; + $self; } - $self->{sig} = \%signo; - $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)) { - while (1) { - my $sig = unpack('L', $buf); - my $cb = $self->{sig}->{$sig}; - $cb->($sig) if $cb ne 'IGNORE'; - return $r if length($buf) == 128; - $buf = substr($buf, 128); + 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 = $self->{sig}->{$signo}; + $cb->($signo) if $cb ne 'IGNORE'; } } $r;