我想实时修改程序的输出,而不用等待它的执行结束。
例如我有这个程序:speak.pl
#!/usr/bin/env perl
use 5.010;
use Time::HiRes qw( usleep );
for(1..10) {
say "I am counting: $_";
usleep(100000);
}
还有这个:wrapper.pl:
#!/usr/bin/env perl
print "You are saying: $_\n" while(<>);
在执行此命令时:
./speak.pl | ./wrapper.pl
不幸的是,在 speak.pl 终止执行之前,什么也没有发生。有没有办法在执行期间修改 speak.pl 的输出数据?
我还尝试通过一个中间文件:
./speak.pl > tmp & ./read.pl tmp
有了这个:
#!/usr/bin/env perl
use 5.010;
use File::Tail;
my $file=File::Tail->new(name=>$ARGV[0], maxinterval=>300, adjustafter=>7);
while (defined(my $line=$file->read)) {
print "You're saying: $line";
}
但输出文件似乎只在执行结束时写入。
有什么线索吗?
附言我在 Cygwin 上运行,我希望它不会产生任何差异。
最佳答案
这可能与缓冲有关。数据在通过管道发送(或在执行结束时刷新)之前存储到一定大小。
尝试使用 usig stdbuf -i0 -o0 -e0 ./speak.pl | stdbuf -i0 -o0 -e0 ./wrapper.pl
禁用缓冲。
当你使用 perl 时,请考虑 this link禁用 perl 自己的缓冲机制。
关于linux - 执行期间的管道数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25842601/