我有一个C程序,只运行一个从STDIN读取JSON结构的循环,并将一行写入STDOUT。
为了支持各种前端格式,我想编写一个Perl程序,它重复读取数据,将其转换为JSON,将其提交给C程序,并接收输出 - 就好像我在使用qx//
调用C程序,每次都不重新启动它。
This thread描述了同样的问题,除了父进程在C中。我想知道Perl是否提供了一种更容易实现此目的的方法。如果可能的话,C程序保持不变并且不知道它是由Perl分叉还是从命令行运行是优选的(但不是必需的)。
为了说明(注意 - 为孩子使用Perl,但希望适用相同的原则):
档案parent.pl
#!/usr/bin/env perl
use warnings;
use strict;
$|++;
# {{ spawn child.pl }}
while (1) {
print "Enter text to send to the child: ";
my $text = <>;
last if !defined $text;
# {{ send $text on some file descriptor to child.pl }}
# {{ receive $reply on some file descriptor from child.pl }}
}
档案child.pl
:
#!/usr/bin/env perl
use warnings;
use strict;
$|++;
while (my $line = <STDIN>) {
chomp $line;
$line .= ", back atcha.\n";
print $line;
}
执行:
$ parent.pl
Enter text to send to the child: hello
hello, back atcha.
Enter text to send to the child:
更新
使用open2
的警告,由@ikegami在Programming Perl / Interprocess Communication下面说明,在我看来并不适用于此,给出:
open3
和select
)答案 0 :(得分:2)
鉴于原始问题的这些条件......
......以下内容将有效。 (请注意,这个孩子用Perl写在这里,但也可能是C.)
<强> parent.pl 强>
#!/usr/bin/env perl
use warnings;
use strict;
use IPC::Open2;
$|=1;
my $pid = open2(my $ifh, my $ofh, 'child.pl') or die;
while (1) {
print STDOUT "Enter text to send to the child: ";
my $message = <STDIN>;
last if !defined $message;
print $ofh $message; # comes with \n
my $reply = <$ifh>;
print STDOUT $reply;
}
close $ifh or die;
close $ofh or die;
waitpid $pid, 0;
<强> child.pl 强>
#!/usr/bin/env perl
use warnings;
use strict;
$|=1;
while (my $line = <STDIN>) {
chomp $line;
print STDOUT $line . ", back atcha.\n";
}