gpt4 book ai didi

perl - 您如何判断管道打开的进程是否已终止?

转载 作者:行者123 更新时间:2023-12-04 17:27:24 26 4
gpt4 key购买 nike

假设使用以下代码创建了一个句柄:

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->opened似乎没有做任何有用的事情。

目前我正在使用 $pid =! waitpid($pid, WNOHANG)这似乎适用于 POSIX 兼容环境。这是最好的方法吗?在 Windows 上呢?

最佳答案

关于使用 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 - 您如何判断管道打开的进程是否已终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6378176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com