Perl FAQ 5.14: How do I open a pipe both to and from a command?

Perl FAQ 5.14

How do I open a pipe both to and from a command?

In general, this is a dangerous move because you can find yourself in a deadlock situation. It's better to put one end of the pipe to a file. For example:

    # first write some_cmd's input into a_file, then 
    open(CMD, "some_cmd its_args < a_file |");
    while () {

    # or else the other way; run the cmd
    open(CMD, "| some_cmd its_args > a_file");
    while ($condition) {
        print CMD "some output\n";
        # other code deleted
    close CMD || warn "cmd exited $?";

    # now read the file
    while (<FILE>) {

If you have ptys, you could arrange to run the command on a pty and avoid the deadlock problem. See the package in the distributed library for ways to do this.

At the risk of deadlock, it is theoretically possible to use a fork, two pipe calls, and an exec to manually set up the two-way pipe. (BSD system may use socketpair() in place of the two pipes, but this is not as portable.) The open2 library function distributed with the current perl release will do this for you.

This assumes it's going to talk to something like adb, both writing to it and reading from it. This is presumably safe because you ``know'' that commands like adb will read a line at a time and output a line at a time. Programs like sort or cat that read their entire input stream first, however, are quite apt to cause deadlock.

There's also an library that handles this for stderr as well.

Other resources at this site: