SendVarious/Fork.pm untested

filter: Statementstmt 0.0% 0 / 47 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 88 CC 6 SCAR 21.7
CC
6
Cov
0%
superfork
20.0
open_to_child
6.0
open_from_child
6.0
CRAP 8.8
1  
2 # Copyright(C) 2006 David Muir Sharnoff <muir@idiom.com>
3  
4 package Mail::SendVarious::Fork;
5  
6 # this shouldn't be here, but does it really deserve its own distribution?
7  
8 use IO::Handle;
9 require Exporter;
10 use strict;
11  
12 our @ISA = qw(Exporter);
13 our @EXPORT = qw(
14 superfork
15 open_to_child
16 open_to_child_child
17 open_from_child
18 open_from_child_child
19 );
20  
21 sub superfork
22 {
23 my $pid;
24 FORK: {
25 if ($pid = fork) {
26 # parent
27 return $pid;
28 } elsif (defined $pid) {
29 # child
30 return 0;
31 } elsif ($! =~ /No more processes/) {
32 sleep 5;
33 redo FORK;
34 } else {
35 die "Couldn't fork: $!";
36 }
37 }
38 }
39  
40 sub open_to_child
41 {
42 my($fh, @args) = @_;
43 my $r = new IO::Handle;
44 pipe($r,$fh) || die "pipe: $!";
45 my $pid;
46 if (($pid = superfork()) == 0) {
47 open_to_child_child ($r, $fh, @args);
48 die "should not have returned";
49 }
50 close($r);
51 $fh->autoflush(1);
52 return $pid;
53 }
54  
55  
56 sub open_to_child_child
57 {
58 my ($r, $w, @args) = @_;
59 close($w);
60 open(STDIN, "<&", $r) || die "reopen STDIN>&$r: $!";
61 my $c = shift(@args);
62 exec($c, @args) || die "exec $c @args: $!";
63 }
64  
65 sub open_from_child
66 {
67 my($fh, @args) = @_;
68 my $w = new IO::Handle;
69 pipe($fh,$w) || die "pipe: $!";
70 if (superfork() == 0) {
71 open_from_child_child ($fh, $w, @args);
72 die "should not have returned";
73 }
74 close($w);
75 return 1;
76 }
77  
78 sub open_from_child_child
79 {
80 my ($r, $w, @args) = @_;
81 close($r);
82 open(STDOUT,">&", $w) || die "reopen STDOUT>&$w: $!";
83 (exec @args) || die "exec @args: $!";
84 }
85  
86 1;