Is it possible to mix a named pipe with select in perl?
I need to write a daemon that supposed to have one 开发者_C百科TCP socket and one named pipe. Usually if I need to implement a multi IO server with "pure" sockets, the select based multi-IO model is always the one I will choose. so does anyone of you have ever used named pipe in select or you can just tell me it is impossible. thanks in advance.
In a word, yes:
#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw/mkfifo/;
use IO::Select;
use IO::Handle;
my $filename = "/tmp/pipe.$$";
mkfifo $filename, 0700
or die "could not create pipe $filename: $!";
die "could not fork\n" unless defined(my $pid = fork);
unless ($pid) {
open my $fh, ">", $filename
or die "could not open $filename\n";
my $i = 1;
for (1 .. 10) {
sleep 1;
print $fh $i++, "\n";
$fh->flush;
}
exit;
}
my $s = IO::Select->new;
open my $fh, "<", "$filename"
or die "could not open $filename\n";
$s->add($fh);
OUTER: while (1) {
print localtime() . "\n";
my @files = $s->can_read(.25);
if (@files) {
for my $fh (@files) {
my $line = <$fh>;
print "from pipe: $line";
last OUTER if $line == 10;
}
}
}
精彩评论