Jon*_*rdy 2 perl pipe io-redirection
我觉得似乎应该有一个简单的方法来做到这一点,但是四处搜寻并没有给我带来好的线索。我只想open()
通过管道连接到应用程序,向其中写入一些数据,然后将子进程的输出发送到STDOUT
调用脚本的。
open(my $foo, '|-', '/path/to/foo');
print $foo 'input'; # Should behave equivalently to "print 'output'"
close($foo);
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法可以做到这一点,或者我遇到了Perl众多“无法从这里到达那里”的时刻之一?
子进程将自动继承STDOUT。这对我有用:
open(my $f, "|-", "cat");
print $f "hi\n";
Run Code Online (Sandbox Code Playgroud)
如果您没有真正立即关闭管道,则问题可能出在另一端:默认情况下,STDOUT是行缓冲的,因此您会print "hello world\n"
立即看到。默认情况下,子进程的管道将使用块缓冲,因此您实际上可能正在等待perl脚本中的数据到达其他程序:
open(my $f, "|-", "cat");
print $f "hi\n";
sleep(10);
close($f); # or exit
# now output appears
Run Code Online (Sandbox Code Playgroud)
尝试添加select $f; $| = 1
(或者我认为更现代的方法是$f->autoflush(1)
)