Debian Codegraph @

perl/forktools.pm

raw
1 # debsigs: Package signing/verification system
2 # SPDX-FileCopyrightText: 2000 Progeny Linux Systems, Inc. <[email protected]>
3 # SPDX-FileCopyrightText: 2009 Peter Pentchev <[email protected]>
4 # SPDX-License-Identifier: GPL-2.0-or-later
5
6 package Debian::debsigs::forktools;
7
8 use strict;
9 use warnings;
10
11 use IO::Pipe;
12 use IO::Handle;
13 use POSIX ":sys_wait_h";
14
15 use Exporter ();
16 use vars qw($VERSION @EXPORT_OK);
17 our @ISA = qw(Exporter);
18 our %EXPORT_TAGS = ( 'all' => [qw(&forkreader &forkwriter &forkboth &assertsuccess)] );
19 Exporter::export_ok_tags('all');
20
21 our $VERSION = '1.10';
22
23 use vars @EXPORT_OK;
24
25 # The forkreader will generate a new fd that is used to read from the
26 # forked program. If you want to write to it, a writer fd may be passed.
27
28 sub forkreader {
29 my ($outputfd, @args) = @_;
30
31 my $pipe = new IO::Pipe;
32 my $pid = fork();
33 if ($pid < 0) {
34 die "Couldn't fork: $!";
35 }
36
37 if ($pid) { # Parent
38 $pipe->reader(); # Re-bless into the reader.
39 if (wantarray()) {
40 return ($pipe, $pid);
41 }
42 return $pipe; # And return for use by the program.
43 } else { # Child.
44 $pipe->writer(); # Make into the writer.
45 my $fd = $pipe->fileno;
46 open(STDOUT, ">&$fd"); # Send standard output to the pipe.
47 if ($outputfd) { # If they specified an input fd, dup it.
48 my $fd = $outputfd->fileno;
49 open(STDIN, "<&$fd");
50 }
51 exec(@args) or die "Couldn't exec: $!\n";
52 }
53 }
54
55 sub forkwriter {
56 my ($inputfd, @args) = @_;
57
58 my $pipe = new IO::Pipe;
59 my $pid = fork();
60 if ($pid < 0) {
61 die "Couldn't fork: $!";
62 }
63
64 if ($pid) { # Parent.
65 $pipe->writer(); # Re-bless into the writer.
66 if (wantarray()) {
67 return ($pipe, $pid);
68 }
69 return $pipe; # And return for use by the program.
70 } else { # Child.
71 $pipe->reader();
72 my $fd = $pipe->fileno;
73 open(STDIN, "<&$fd");
74 if ($inputfd) {
75 my $fd = $inputfd->fileno;
76 open(STDOUT, ">&$fd");
77 }
78 exec(@args) or die "Couldn't exec: $!\n";
79 }
80 }
81
82 sub forkboth {
83 my ($outputfd, $inputfd, @args) = @_;
84 my $pid = fork();
85 if ($pid < 0) {
86 die "Couldn't fork: $!";
87 }
88
89 if ($pid) { # Parent.
90 return $pid;
91 } else { # Child.
92 my $fd = $outputfd->fileno;
93 open(STDIN, "<&$fd");
94 $fd = $inputfd->fileno;
95 open(STDOUT, ">&$fd");
96 exec(@args) or die "Couldn't exec: $!\n";
97 }
98 }
99
100 sub assertsuccess {
101 my ($pid, $package, $block) = @_;
102
103 my $res = waitpid($pid, (defined($block) && $block) ? 0 : &WNOHANG);
104 my $code = $?;
105 return if ($res < 1); # bad pid or not exited, ok.
106 my $ec = WEXITSTATUS($code);
107 die "Program $package ($pid) failed with code $code (exit $ec)" if ($code);
108 # print STDERR "Program $package ($pid) exited successfully.\n";
109 }
110
111 1;