| 1 | package Build::PPK::Pipeline; | ||
| 2 | |||
| 3 | # Copyright (c) 2018, cPanel, L.L.C. | ||
| 4 | # All rights reserved. | ||
| 5 | # http://cpanel.net/ | ||
| 6 | # | ||
| 7 | # This is free software; you can redistribute it and/or modify it under the same | ||
| 8 | # terms as Perl itself. See the LICENSE file for further details. | ||
| 9 | |||
| 10 | use strict; | ||
| 11 | use warnings; | ||
| 12 | |||
| 13 | use Carp; | ||
| 14 | use POSIX (); | ||
| 15 | |||
| 16 | sub open { | ||
| 17 | my ( $class, @subs ) = @_; | ||
| 18 | my @pids; | ||
| 19 | |||
| 20 | pipe my ( $child_out, $in ) or confess("Unable to create a file handle pair for standard input piping: $!"); | ||
| 21 | pipe my ( $error_out, $error_in ) or confess("Unable to create a file handle pair for standard error piping: $!"); | ||
| 22 | |||
| 23 | foreach my $sub (@subs) { | ||
| 24 | pipe my ( $out, $child_in ) or confess("Unable to create a file handle pair for standard output piping: $!"); | ||
| 25 | |||
| 26 | my $pid = fork(); | ||
| 27 | |||
| 28 | if ( $pid == 0 ) { | ||
| 29 | POSIX::dup2( fileno($child_out), fileno(STDIN) ) or die("Cannot dup2() output to current child stdin: $!"); | ||
| 30 | POSIX::dup2( fileno($child_in), fileno(STDOUT) ) or die("Cannot dup2() input to current child stdout: $!"); | ||
| 31 | POSIX::dup2( fileno($error_in), fileno(STDERR) ) or die("Cannot dup2() error input to current child: $!"); | ||
| 32 | |||
| 33 | exit $sub->(); | ||
| 34 | } | ||
| 35 | elsif ( !defined($pid) ) { | ||
| 36 | confess("Unable to fork(): $!"); | ||
| 37 | } | ||
| 38 | |||
| 39 | $child_out = $out; | ||
| 40 | |||
| 41 | push @pids, $pid; | ||
| 42 | } | ||
| 43 | |||
| 44 | return bless { | ||
| 45 | 'in' => $in, | ||
| 46 | 'out' => $child_out, | ||
| 47 | 'err' => $error_out, | ||
| 48 | 'pids' => \@pids | ||
| 49 | }, $class; | ||
| 50 | } | ||
| 51 | |||
| 52 | sub close { | ||
| 53 | my ($self) = @_; | ||
| 54 | |||
| 55 | close $self->{'in'}; | ||
| 56 | close $self->{'out'}; | ||
| 57 | close $self->{'err'}; | ||
| 58 | |||
| 59 | my %statuses; | ||
| 60 | |||
| 61 | foreach my $pid ( @{ $self->{'pids'} } ) { | ||
| 62 | waitpid( $pid, 0 ); | ||
| 63 | $statuses{$pid} = $? >> 8; | ||
| 64 | } | ||
| 65 | |||
| 66 | return \%statuses; | ||
| 67 | } | ||
| 68 | |||
| 69 | 1; |