develooper Front page | perl.fwp | Postings from August 2003

construct arbitrary pipeline w/ IO::Pipe & fork

Bennett Todd
August 6, 2003 06:13
construct arbitrary pipeline w/ IO::Pipe & fork
Message ID:
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

	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};
	    STDIN->fdopen($pipe->reader->fileno, "r");
	print STDIN->getlines;

-Bennett Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About