【问题标题】:How can I use `pipe` to facilitate interprocess communication in Perl?如何使用“管道”来促进 Perl 中的进程间通信?
【发布时间】:2011-02-03 05:25:08
【问题描述】:

谁能解释我如何成功地让我的流程进行通信?我发现 IPC 上的 perldoc 令人困惑。

到目前为止我所拥有的是:

$| = 1;
$SIG{CHLD} = {wait};
my $parentPid = $$;

if ($pid = fork();) ) {
    if ($pid == 0) {
       pipe($parentPid, $$);
       open PARENT, "<$parentPid";
       while (<PARENT>) {
           print $_;
       }
       close PARENT;
       exit();
    } else {

       pipe($parentPid, $pid);
       open CHILD, ">$pid";
          or error("\nError opening: childPid\nRef: $!\n");
       open (FH, "<list")
          or error("\nError opening: list\nRef: $!\n");

       while(<FH>) {
          print CHILD, $_;
       }

       close FH
          or error("\nError closing: list\nRef: $!\n");
       close CHILD
          or error("\nError closing: childPid\nRef: $!\n);
    } else {
    error("\nError forking\nRef: $!\n");
}
  • 首先:perldoc pipe 中的READHANDLEWRITEHANDLE 是什么意思?

  • 第二:我能否在不依赖 CPAN 或其他模块的情况下实施解决方案?


(来源:wellho.net

【问题讨论】:

    标签: perl ipc


    【解决方案1】:

    这是一个基于perldoc perlipc 中的代码的简化示例:

    #!/usr/bin/perl
    
    use strict; use warnings;
    
    $SIG{CHLD} = sub { wait };
    
    pipe my $reader, my $writer;
    
    my $pid = fork;
    defined $pid or die "fork failed: $!";
    
    if ( $pid ) { # parent
        close $reader;
        for my $n ( 1 .. 5 ) {
            select $writer;
            $| = 1;
            print $writer "Message $n\n"
                or die "Failed to pass message to child: $!";
            sleep 1;
        }
        close $writer;
        exit;
    }
    else { # child
        close $writer;
        while ( my $msg = <$reader> ) {
            print "Child received: $msg";
            last if rand > 0.5; # to check error handling in parent
        }
        close $reader;
        exit;
    }
    

    【讨论】:

    • 谢谢!!!这是一个非常简单且易于遵循的解决方案。再问一个问题,“select $writer”是如何知道写入父进程的?
    • pipe 呼叫将$reader 连接到$writer。在fork 之后,两个文件句柄都是重复的。 select $writer 在那里,以便后续的 $| = 1 在正确的文件句柄上运行(而不是 STDOUT 连接到的任何东西)。
    • 这是有道理的。我在研究解决方案时遇到了一张图片,该图片描述了您在谈论的内容,但是没有可参考的代码。很好的答案!
    • 我的原始答案混淆了父进程和子进程。这里时间不早了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    相关资源
    最近更新 更多