IO ::选择并将标记添加到句柄 [英] IO::Select and adding a tag to the handle

查看:96
本文介绍了IO ::选择并将标记添加到句柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用IO::Select时向句柄添加其他数据的最佳方法是什么?

I'm wondering what's the best way to add additional data to a handle when I'm using IO::Select?

基本上,我想向IO::Select添加一个句柄,但还附加了该句柄的其他信息,以后可以检索.

Basically I'd like to add a handle to IO::Select but also have additional info attached to that handle that I could retrieve later.

注意:我知道我可以保留一个单独的数据结构,该结构包含一个句柄和其他数据,但是这需要协调两个数据结构,这可能会引起更多的问题,而不是有价值的问题.

Note: I know I could keep a separate data structure which holds a handle and additional data but that would require coordinating two data structures and that's probably going to cause more problems than its worth.

推荐答案

IO :: Select 文档用于add方法

每个句柄可以是IO :: Handle对象,整数或数组引用,其中第一个元素是IO :: Handle或整数.

Each handle can be an IO::Handle object, an integer or an array reference where the first element is an IO::Handle or an integer.

因此,这里可以使用数组引用".

So there, there's "an array reference" that one may use.

一个例子:

use warnings;
use strict;
use feature 'say';

use Time::HiRes qw(sleep);
use POSIX qw(:sys_wait);
use IO::Select;

my $sel = IO::Select->new;

my @procs;
for my $job (1..3) {
    pipe my ($reader, $writer);
    $sel->add( [$reader, "job-$job"] );  # add a tag to the handle

    my $pid = fork // die "Can't fork: $!";

    if ($pid == 0) {
        close $reader;
        sleep rand 4;
        say $writer "\tkid $$ (job $job)";
        close $writer;
        exit; 
    }   
    close $writer;
    push @procs, $pid;
}       
say "Started processes @procs\n";

# Read from pipes when ready, print piped messages
while ( my @ready = $sel->can_read ) {
    foreach my $p (@ready) {
        my ($handle, $tag) = @$p;
        say "Reading from fileno ", $handle->fileno, ", tag: ", $tag;
        print while <$handle>;
        $sel->remove($p);      # *this* order: remove then close
        close $handle;
    }   
}   

# Reap
my $msg = "\nExited (with status): ";
my $kid = 0; # poll to reap
while (($kid = waitpid -1, WNOHANG) > -1) {
    $msg .= "$kid ($?) " if $kid > 0; 
    sleep 0.1;
}   
say $msg;

打印


Started processes 15679 15680 15681

Reading from fileno 5, tag: job-2
        kid 15680 (job 2)
Reading from fileno 4, tag: job-1
        kid 15679 (job 1)
Reading from fileno 6, tag: job-3
        kid 15681 (job 3)

Exited (with status): 15680 (0) 15679 (0) 15681 (0)

这篇关于IO ::选择并将标记添加到句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆