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>
4 # a tied handle for auto reaping of children tied to a pipe, see perltie(1)
5 package PublicInbox::ProcessPipe;
11 my ($class, $pid, $fh, $cb, $arg) = @_;
12 bless { pid => $pid, fh => $fh, ppid => $$, cb => $cb, arg => $arg },
16 sub BINMODE { binmode(shift->{fh}) } # for IO::Uncompress::Gunzip
18 sub READ { read($_[0]->{fh}, $_[1], $_[2], $_[3] || 0) }
20 sub READLINE { readline($_[0]->{fh}) }
24 syswrite($_[0]->{fh}, $_[1], $_[2] // length($_[1]), $_[3] // 0);
29 print { $self->{fh} } @_;
32 sub FILENO { fileno($_[0]->{fh}) }
35 my ($self, $wait) = @_;
36 my $fh = delete $self->{fh};
37 my $ret = defined($fh) ? close($fh) : '';
38 my ($pid, $cb, $arg) = delete @$self{qw(pid cb arg)};
39 return $ret unless defined($pid) && $self->{ppid} == $$;
40 if ($wait) { # caller cares about the exit status:
41 my $wp = waitpid($pid, 0);
45 eval { $cb->($arg, $pid) };
46 carp "E: cb(arg, $pid): $@" if $@;
49 carp "waitpid($pid, 0) = $wp, \$!=$!, \$?=$?";
51 } else { # caller just undef-ed it, let event loop deal with it
52 require PublicInbox::DS;
53 PublicInbox::DS::dwaitpid($pid, $cb, $arg);
58 # if caller uses close(), assume they want to check $? immediately so
59 # we'll waitpid() synchronously. n.b. wantarray doesn't seem to
60 # propagate `undef' down to tied methods, otherwise I'd rely on that.
61 sub CLOSE { _close($_[0], 1) }
63 # if relying on DESTROY, assume the caller doesn't care about $? and
64 # we can let the event loop call waitpid() whenever it gets SIGCHLD