Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

16. Process Management and Communication > 16.8. Controlling Input and Output o...

16.8. Controlling Input and Output of Another Program

Problem

You want to both write to and read from another program. The open function lets you do one or the other, but not both.

Solution

Use the standard IPC::Open2 module:

use IPC::Open2;

$pid= open2(*README, *WRITEME, $program);
print WRITEME "here's your input\n";
$output = <README>;
close(WRITEME);
close(README);
waitpid($pid, 0);

Discussion

Wanting simultaneous read and write access to another program is very common, but surprisingly perilous. That’s one reason the built-in open doesn’t permit:

open(my $double_handle, "| program args |")     # WRONG

The big problem here is buffering. Because you can’t force the other program to unbuffer its output, you can’t guarantee that your reads won’t block. If you block trying to read at the same time the other process blocks waiting for you to send something, you’ve achieved the unholy state of deadlock. There you’ll both stay, wedged, until someone kills your process or the machine reboots.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint