[Memphis.pm] bidirectional pipe

Carl Brock Sides csides at autozone.com
Mon Oct 23 14:10:15 CDT 2000


* Carl Brock Sides <csides at autozone.com> [001020 11:53]:

Answering my own question.

> Suppose you have a program X, and you want to write (in Perl, of
> course), a wrapper W for this program. You want W to take standard
> input, modify it, and pass it to X; then W should get back standard out
> from X, and pass it back.
[snip]
> Since the obvious answer doesn't work, what's the most elegant way to do
> this in perl?

Perusing the IPC documentation (perldoc perlipc), I discovered
IPC::Open2, which lets you open bidirectional pipes. For example, here's
a generic wrapper to do gzip-encoding for a cgi script:

#!/usr/local/perl-5.6/bin/perl -w -T

use IPC::Open2;

# the cgi we're wrapping
my $cgi = '/home/csides/public_html/hello.cgi';

$ENV{'PATH'} = ''; # keep taint-checking happy if we're on the command line
$ENV{'BASHRC'} = ''; # ditto

open2(*READER, *WRITER, $cgi);

# pass STDIN on to $cgi
print WRITER <STDIN>;

# read in the headers from the wrapped program,
# printing them to stdout. Add a Content-encoding: gzip
# header unless the content is already encoded
while (<READER>) {
	$encoded = 1 if /^Content-encoding:/i;
	if (/^$/) {
		print "Content-encoding: gzip\n" unless $encoded;
		print;
		last;
	}	
}

# print out the body of the response, gzipped if needed.
if ($encoded) {
	print <READER>;
} else {	
	open(GZIP, "| /bin/gzip -cf") or die $!;
	print GZIP <READER>;
}	

exit 0;

__END__

-- 
Brock Sides
csides at autozone.com

The original plan [for GNOME] was to aim to make a desktop as good as the Macintosh, and we should not lower our ambition by making one merely as good as Windows. -- RMS 
----------------------------------------------------------------------------
To unsubscribe, please send email to majordomo at pm.org
with 'unsubscribe memphis-pm-list' in the body of the message.
----------------------------------------------------------------------------




More information about the Memphis-pm mailing list