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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
|
# debsigs: Package signing/verification system
# SPDX-FileCopyrightText: 2000 Progeny Linux Systems, Inc. <jgoerzen@progeny.com>
# SPDX-FileCopyrightText: 2009 Peter Pentchev <roam@ringlet.net>
# SPDX-License-Identifier: GPL-2.0-or-later
package Debian::debsigs::forktools;
use strict;
use warnings;
use IO::Pipe;
use IO::Handle;
use POSIX ":sys_wait_h";
use Exporter ();
use vars qw($VERSION @EXPORT_OK);
our @ISA = qw(Exporter);
our %EXPORT_TAGS = ( 'all' => [qw(&forkreader &forkwriter &forkboth &assertsuccess)] );
Exporter::export_ok_tags('all');
our $VERSION = '1.10';
use vars @EXPORT_OK;
# The forkreader will generate a new fd that is used to read from the
# forked program. If you want to write to it, a writer fd may be passed.
sub forkreader {
my ($outputfd, @args) = @_;
my $pipe = new IO::Pipe;
my $pid = fork();
if ($pid < 0) {
die "Couldn't fork: $!";
}
if ($pid) { # Parent
$pipe->reader(); # Re-bless into the reader.
if (wantarray()) {
return ($pipe, $pid);
}
return $pipe; # And return for use by the program.
} else { # Child.
$pipe->writer(); # Make into the writer.
my $fd = $pipe->fileno;
open(STDOUT, ">&$fd"); # Send standard output to the pipe.
if ($outputfd) { # If they specified an input fd, dup it.
my $fd = $outputfd->fileno;
open(STDIN, "<&$fd");
}
exec(@args) or die "Couldn't exec: $!\n";
}
}
sub forkwriter {
my ($inputfd, @args) = @_;
my $pipe = new IO::Pipe;
my $pid = fork();
if ($pid < 0) {
die "Couldn't fork: $!";
}
if ($pid) { # Parent.
$pipe->writer(); # Re-bless into the writer.
if (wantarray()) {
return ($pipe, $pid);
}
return $pipe; # And return for use by the program.
} else { # Child.
$pipe->reader();
my $fd = $pipe->fileno;
open(STDIN, "<&$fd");
if ($inputfd) {
my $fd = $inputfd->fileno;
open(STDOUT, ">&$fd");
}
exec(@args) or die "Couldn't exec: $!\n";
}
}
sub forkboth {
my ($outputfd, $inputfd, @args) = @_;
my $pid = fork();
if ($pid < 0) {
die "Couldn't fork: $!";
}
if ($pid) { # Parent.
return $pid;
} else { # Child.
my $fd = $outputfd->fileno;
open(STDIN, "<&$fd");
$fd = $inputfd->fileno;
open(STDOUT, ">&$fd");
exec(@args) or die "Couldn't exec: $!\n";
}
}
sub assertsuccess {
my ($pid, $package, $block) = @_;
my $res = waitpid($pid, (defined($block) && $block) ? 0 : &WNOHANG);
my $code = $?;
return if ($res < 1); # bad pid or not exited, ok.
my $ec = WEXITSTATUS($code);
die "Program $package ($pid) failed with code $code (exit $ec)" if ($code);
# print STDERR "Program $package ($pid) exited successfully.\n";
}
1;
|