【问题标题】:Perl polling a file handle?Perl轮询文件句柄?
【发布时间】:2015-04-13 05:05:35
【问题描述】:
use strict;
use warnings;

my $file = 'SnPmaster.txt';
open my $info, $file or die "Could not open $file: $!";

while( my $line = <$info>)  {   
    print $line;    
    last if $. == 2;
}

close $info;

无论我在哪里,都建议从文件句柄 (while( my $line = &lt;$info&gt;)) 中读取上述内容。

但是有没有一种方法可以读取而不是使用 while 循环?

open FH,
    "executable_that_prints_every_once_in_awhile"
    or die 'Cannot open FH';
while (1){
    # do something which doesnt get blocked by <FH>

    if (my $line from <FH>) {           <---- is there something like it?
        print $line;
    }

    last if eof <FH>;
}

例如,轮询是否有来自文件句柄的输入?

while( my $line = &lt;$info&gt;) 的问题在于它会阻塞,所以我在等待从 FH 获取东西时不能做其他事情

【问题讨论】:

    标签: perl


    【解决方案1】:

    是的,有。您需要 IO::Selectcan_read 函数。

    类似:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use autodie;
    
    use IO::Select;
    
    my $selector = IO::Select->new();
    
    open( my $program, "-|", "executable_that_prints_every_once_in_awhile" );
    $selector->add($program);
    
    foreach my $readable_fh ( $selector->can_read() ) {
    
        #do something with <$readable_fh>
    }
    

    或者 - 使用 threadsfork 的并行代码:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use autodie;
    use threads;
    
    sub reader_thread { 
       open ( my $program, "-|", "executbale_file" );
       while ( my $line =  <$program> ) {
          print $line;
       }
    }
    
    threads -> create ( \&reader_thread );
    
    while ( 1 ) {
       #do something else
    }
    
    #sync threads at exit - blocks until thread is 'done'. 
    foreach my $thr ( threads -> list ) {
      $thr -> join();
    }
    

    一般来说,当您需要做的不仅仅是微不足道的 IPC 和分叉以获得一般性能时,我建议您使用线程。例如,Thread::Queue 是一种在线程之间来回传递数据的好方法。 (如果你想走那条路,请参阅:Perl daemonize with child daemons

    【讨论】:

    • 或者让句柄不阻塞
    • 我采用了您的第二种方法,效果很好。谢谢
    猜你喜欢
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多