construct arbitrary pipeline w/ IO::Pipe & fork
Bennett Todd <[email protected]>
| Newsgroups | gmane.comp.lang.perl.fun |
|---|---|
| Message-ID | <[email protected]> |
A friend set me a pretty puzzle. Or at least, I enjoyed wrapping my
brain around it. He wanted to set up a pipeline of commands. For
various design constraint reasons, he didn't know in advance what
the commands were nor how many of them there were --- the whole
pipeline is constructed from external data. Further, he didn't want
to let a shell lay its fingers on the text of the args, he wanted to
do it directly. And lastly he's enjoying using the object-oriented
file I/O components.
There's surely More Than One Way To Do It, but here's what I came up
with.
use IO::Pipe;
my @cmds = (
[ 'perl', '-le', 'print for 1..10' ],
[ 'sort', '-r' ],
[ 'sed', 's/^/-> /' ],
);
while (@cmds) {
my $cmd = shift @cmds;
my $pipe = IO::Pipe->new;
my $pid = fork;
die "I'm forked\n" unless defined $pid;
if ($pid == 0) {
STDOUT->fdopen($pipe->writer->fileno, "w");
exec @{$cmd};
die;
}
STDIN->fdopen($pipe->reader->fileno, "r");
}
print STDIN->getlines;
-Bennett
signature.asc
(application/pgp-signature, 189 B)
-----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) iD8DBQE/MP6MHZWg9mCTffwRAokKAJ0ZI40wDdkqzVBTu/p7mpxCPb6t1wCdFq8u nLV9iuxlor58oWApFXR8Hfc= =Qk8c -----END PGP SIGNATURE-----