]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ProcessPipe.pm
processpipe: lazy-require PublicInbox::DS for dwaitpid
[public-inbox.git] / lib / PublicInbox / ProcessPipe.pm
1 # Copyright (C) 2016-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # a tied handle for auto reaping of children tied to a pipe, see perltie(1)
5 package PublicInbox::ProcessPipe;
6 use strict;
7 use v5.10.1;
8 use Carp qw(carp);
9
10 sub TIEHANDLE {
11         my ($class, $pid, $fh, $cb, $arg) = @_;
12         bless { pid => $pid, fh => $fh, ppid => $$, cb => $cb, arg => $arg },
13                 $class;
14 }
15
16 sub READ { read($_[0]->{fh}, $_[1], $_[2], $_[3] || 0) }
17
18 sub READLINE { readline($_[0]->{fh}) }
19
20 sub WRITE {
21         use bytes qw(length);
22         syswrite($_[0]->{fh}, $_[1], $_[2] // length($_[1]), $_[3] // 0);
23 }
24
25 sub PRINT {
26         my $self = shift;
27         print { $self->{fh} } @_;
28 }
29
30 sub FILENO { fileno($_[0]->{fh}) }
31
32 sub _close ($;$) {
33         my ($self, $wait) = @_;
34         my $fh = delete $self->{fh};
35         my $ret = defined($fh) ? close($fh) : '';
36         my ($pid, $cb, $arg) = delete @$self{qw(pid cb arg)};
37         return $ret unless defined($pid) && $self->{ppid} == $$;
38         if ($wait) { # caller cares about the exit status:
39                 my $wp = waitpid($pid, 0);
40                 if ($wp == $pid) {
41                         $ret = '' if $?;
42                         if ($cb) {
43                                 eval { $cb->($arg, $pid) };
44                                 carp "E: cb(arg, $pid): $@" if $@;
45                         }
46                 } else {
47                         carp "waitpid($pid, 0) = $wp, \$!=$!, \$?=$?";
48                 }
49         } else { # caller just undef-ed it, let event loop deal with it
50                 require PublicInbox::DS;
51                 PublicInbox::DS::dwaitpid($pid, $cb, $arg);
52         }
53         $ret;
54 }
55
56 # if caller uses close(), assume they want to check $? immediately so
57 # we'll waitpid() synchronously.  n.b. wantarray doesn't seem to
58 # propagate `undef' down to tied methods, otherwise I'd rely on that.
59 sub CLOSE { _close($_[0], 1) }
60
61 # if relying on DESTROY, assume the caller doesn't care about $? and
62 # we can let the event loop call waitpid() whenever it gets SIGCHLD
63 sub DESTROY {
64         _close($_[0]);
65         undef;
66 }
67
68 1;