【问题标题】:How can I loop over data from a pipe?如何循环管道中的数据?
【发布时间】:2014-04-10 21:36:50
【问题描述】:

我发现了一些代码,Perl 中的两个进程可以通过管道进行通信。示例:

if ($pid = fork) {  
      close $reader;  
      print $writer "Parent Pid $$ is sending this\n";  
      close $writer;  
      waitpid($pid,0);   
}   
else {  
      close $writer;  
      chomp($line = <$reader>);  
      print "Child Pid $$ just read this: `$line'\n";  
      close $reader;  
      exit;  
}   

现在我有以下问题:

  1. 是否可以让阅读器从管道中读取,然后阻塞,直到新数据从管道中传出,就像循环一样?
  2. 如果是,当父进程没有数据要发送时,杀死子进程的方法是什么?
  3. 每个程序有多少打开的读/写管道有限制吗?例如。如果我分叉 10 个进程并有 20 个管道(10 个读/10 个写),这是一个坏主意吗?

如果问题太基本,我很抱歉,但我的经验是使用另一种语言的线程。

【问题讨论】:

    标签: linux perl multiprocessing fork pipe


    【解决方案1】:

    有一些重要的警告(*),在 Perl 中对管道的 I/O 很像对任何其他文件句柄的 I/O。 readline (&lt;&gt;) 运算符将等待管道上的输入,就像它来自套接字或 STDIN 一样。当您close 管道的写入端时,读取端将收到文件结尾(readline 将返回undef)。我可以通过对您的脚本进行一些小的修改来演示这些概念:

    pipe $reader, $writer;
    
    if ($pid = fork) {  
          close $reader;  
          sleep 5;
          for (1..10) {
              print $writer "Parent Pid $$ is sending this\n";  
          }
          close $writer;  
          waitpid($pid,0);   
    }   
    else {  
          close $writer;  
          # <$reader> will block until parent produces something
          # and will return undef when parent closes the write end of the pipe
          while ($line = <$reader>) {
              chomp($line);
              print "Child Pid $$ just read this: `$line'\n";  
          }
          close $reader;  
          exit;  
    }
    

    3 .进程中通常有一个操作系统强加的limit on the number of open filehandles,打开的管道句柄会根据这个值计算,但10或20个管道不会有问题。 p>

    * 一个重要的警告是管道具有的小缓冲区大小,在某些操作系统上限制很小。如果你填满这个缓冲区,管道的写端可能会阻塞写操作,直到读端从缓冲区中取出一些东西。如果你不仔细管理你的读写,你的程序可能会死锁。

    【讨论】:

    • 我们所说的每个管道的缓冲区有多小?几个字节?只传递几个原始值?那么使用某种形式的共享内存是首选方式吗?
    • 64K 是典型的,但可能会更小。
    • 那么父母孩子通常如何在 perl 代码中交谈?通过共享内存是推荐的方式?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多