如何在 perl 脚本中生成其他程序并立即继续 Perl 处理? [英] How to spawn other programs within perl script and immediately continue Perl processing?
问题描述
如何在 perl 脚本中生成其他程序并立即继续 Perl 处理(而不是暂停直到生成的程序终止)?是否可以在生成的程序运行时处理它的输出而不是等待它结束?
How to spawn other programs within perl script and immediately continue Perl processing (instead of halting until the spawned program terminates) ? Is it possible to process the output coming from the spawned program while it is running instead of waiting it to end?
推荐答案
你可以使用 open
为此(运行程序 /bin/some/program
两个命令行参数):
You can use open
for this (to run the program /bin/some/program
with two command-line arguments):
open my $fh, "-|", "/bin/some/program", "cmdline_argument_1", "cmdline_argument_2";
while (my $line = readline($fh)) {
print "Program said: $line";
}
读取 $fh
将为您提供正在运行的程序的标准输出.
Reading from $fh
will give you the stdout of the program you're running.
反之亦然:
open my $fh, "|-", "/bin/some/program";
say $fh "Hello!";
这会将您在文件句柄上写入的所有内容通过管道传输到衍生进程的标准输入.
This pipes everything you write on the filehandle to the stdin of the spawned process.
如果您想在同一个进程中读写,请查看 IPC::Open3
和 IPC::Cmd
模块.
If you want to read and write to and from the same process, have a look at the IPC::Open3
and IPC::Cmd
modules.
这篇关于如何在 perl 脚本中生成其他程序并立即继续 Perl 处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!