One of my program need to execute Unix command from time to time. If I use system(), it would spawn a new process each time, which costs a lot. My solution is to spawn a sh process through open2 or open3, and then simply communicate my Unix command to that sh process.
After the sh process receive my command, it may or may not spawn a new process, depending on the nature of the command, say I can save 50% (the number really depends on what commands I use) cost.
Part of my code read:
#!/usr/bin/perl
use IPC::Open2;
use strict;
my ($reader, $writer);
my $pid = open2($reader, $writer, "sh") || die "failed";
print $writer "history\n";
while (<$reader>) {
print "[", $_, "]\n";
}
Now my problem is that it will not quit the while loop, as there is no eof coming in. So, how can I fix this? ( I also tried open3, the same thing)
By the way, there was a thread leading by help with system function, discussed about why can not call history sh command by using system() call, and no answer came up at that time. My solution actually resolves that problem.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.