Perl   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了perl – 如何判断管道打开过程是否已终止?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
假设使用以下代码创建句柄:
use IO::File;

my $fh = IO::File->new;

my $pid = $fh->open('some_long_running_proc |') or die $!;

$fh->autoflush(1);
$fh->blocking(0);

然后用这样的循环读取:

while (some_condition_herE) {
    my @lines = $fh->getlines;
    ...
    sleep 1;
}

作为some_condition_here,如果管道另一端的进程终止,那么它将返回false?

$fh-> eof的测试将无法工作,因为该过程仍然可以在不打印任何新行的情况下运行.测试$fh->打开似乎没有做任何有用的事情.

目前我正在使用$pid =! waitpid($pid,WNOHANG)似乎适用于符合POSIX标准的环境.这是最好的方法吗?在Windows上怎么样?

解决方法

@H_197_17@ 在使用SELEct时,
use Strict;
use warnings;

use IO::SELEct qw( );

sub process_msg {
    my ($client,$msg) = @_;
    chomp $msg;
    print "$client->{iD} said '$msg'\n";
    return 1;  # Return false to close the handle.
}

my $SELEct = IO::SELEct->new();
my %clients;

for (...) {
    my $fh = ...;
    $clients{fileno($fh)} = {
        id  => '...'
        buf => '',# ...
    };

    $SELEct->add($fh);
}

while (my @ready = $SELEct->can_read) {
    for my $fh (@ready) {
        my $client = $clients{ fileno($fh) };
        our $buf; local *buf = \( $client->{Buf} );

        my $rv = sysread($fh,$buf,64*1024,length($buf));
        if (!$rv) {
            if (defined($rv)) {
                print "[$client->{iD} ended]\n";
            } else {
                print "[Error reading from $client->{iD}: $!]\n";
            }

            print "[Incomplete message received from $client->{iD}]\n"
                if length($buf);

            delete $clients{ fileno($fh) };
            $SELEct->remove($fh);
            next;
        }

        while ($buf =~ s/^(.*\n)//) {
            if (!process_msg($client,"$1")) {
                print "[Dropping $client->{iD}]\n";
                delete $clients{ fileno($fh) };
                $SELEct->remove($fh);
                last;
            }
        }
    }
}

大佬总结

以上是大佬教程为你收集整理的perl – 如何判断管道打开过程是否已终止?全部内容,希望文章能够帮你解决perl – 如何判断管道打开过程是否已终止?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。