从Perl生成一个程序并通过STDIN / STDOUT与

时间:2018-04-13 22:10:38

标签: perl fork stdin

我有一个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下面说明,在我看来并不适用于此,给出:

  • 我不关心STDERR(需要open3select
  • 我控制子源代码,因此可以保证发生自动刷新。
  • 协议严格发送一行,接收一行。

1 个答案:

答案 0 :(得分:2)

鉴于原始问题的这些条件......

  • 你不在乎阅读STDERR
  • 您可以控制子源代码,因此可以保证发生自动刷新。
  • 协议严格发送一行,接收一行。

......以下内容将有效。 (请注意,这个孩子用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";
}