【发布时间】:2012-09-20 12:49:25
【问题描述】:
我正在尝试与交互式进程进行通信。我希望我的 perl 脚本成为用户和进程之间的“模块人”。该过程将文本放入标准输出,提示用户输入命令,将更多文本放入标准输出,提示用户输入命令,......提供原始图形:
User <----STDOUT---- interface.pl <-----STDOUT--- Process
User -----STDIN----> interface.pl ------STDIN---> Process
User <----STDOUT---- interface.pl <-----STDOUT--- Process
User -----STDIN----> interface.pl ------STDIN---> Process
User <----STDOUT---- interface.pl <-----STDOUT--- Process
User -----STDIN----> interface.pl ------STDIN---> Process
以下模拟了我正在尝试做的事情:
#!/usr/bin/perl
use strict;
use warnings;
use FileHandle;
use IPC::Open2;
my $pid = open2( \*READER, \*WRITER, "cat -n" );
WRITER->autoflush(); # default here, actually
my $got = "";
my $input = " ";
while ($input ne "") {
chomp($input = <STDIN>);
print WRITER "$input \n";
$got = <READER>;
print $got;
}
由于输出缓冲上述示例不起作用。无论输入什么文本,或者按了多少输入,程序都在那里。解决方法是发出:
my $pid = open2( \*READER, \*WRITER, "cat -un" );
注意“cat -un”而不是“cat -n”。 -u 关闭 cat 上的输出缓冲。关闭输出缓冲时,此方法有效。我试图与最有可能的缓冲区输出交互的过程,因为我面临与“cat -n”相同的问题。不幸的是,我无法关闭正在与之通信的进程的输出缓冲,那么我该如何处理这个问题?
UPDATE1(使用 ptty):
#!/usr/bin/perl
use strict;
use warnings;
use IO::Pty;
use IPC::Open2;
my $reader = new IO::Pty;
my $writer = new IO::Pty;
my $pid = open2( $reader, $writer, "cat -n" );
my $got = "";
my $input = " ";
$writer->autoflush(1);
while ($input ne "") {
chomp($input = <STDIN>);
$writer->print("$input \n");
$got = $reader->getline;
print $got;
}
~
【问题讨论】:
-
open2总是打开它自己的管道,你不能给它 ptys。有关使用IO::Pty::Easy的简单示例,请参阅 perlmonks.org/?node_id=835953。
标签: perl ipc pipe output-buffering tty