I have an external program which reads from STDIN and returns the result by STDOUT. I would like to feed my data to this program and retrieve the result (and the exit code too, but this is a different matter) without creating a temporary file for the data which I feed to the filter (and using backticks to get the result). BTW, I'm on Windows. How can I do this?
Here is my first attempt. For testing, I use perl -wpe 1 as external program, which acts as "poor man's cat":
The program outputsuse strict; use warnings; use IPC::Open2; $|=1; $SIG{PIPE} = sub { print STDERR "SIGPIPE received\n"; exit; }; my $pid = open2(my $reader, my $writer, 'perl -wpe 1'); print $writer "$_\n" for (qw(first second third)); print "Data written\n"; close $writer; print "Reading from pipe:\n"; while(my $data=<$reader>) { print "Received: ".<$reader>."\n"; } close $reader; print "No more data\n"; waitpid($pid, 0); print "Finished\n";
Data written Reading from pipe:
and then hangs. Obviously, reading from the pipe does not work. Indeed, I found the following warning in IPC::Open2]:
This whole affair is quite dangerous, as you may block forever. It assumes it's going to talk to something like bc, both writing to it and reading from it. This is presumably safe because you "know" that commands like bc will read a line at a time and output a line at a time. Programs like sort that read their entire input stream first, however, are quite apt to cause deadlock.
Maybe this is what happens in my case (though I don't understand *why* this restriction exists). Maybe someone could give me a hint, how to implement this properly?In reply to Can't get it working: Bidirectional Pipe on Windows by rovf
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |