Hi,
Using Select and syswrite(), the system works better but there's a buffer problem:
If the producer prints the first line, the consumer only reads the first character. When the producer prints the
second line, then the consumer reads the rest of the fist
line characters but can't read the second line so the
consumer never reads the last line.
Here's the code and the result that illustrates the problem:
#producer.pl
my $i;
for $i (0 .. 3){
syswrite(STDOUT,"Hello_$i\n",length("Hello_$i\n"));
$i=$i+1;
sleep(5);
}
while(1){} #The real producer never ends.
#Consumer.pl
$select = IO::Select->new();
$select->add(\*STDIN);
while (1){
if(@ready=$select->can_read(0)){
if(read($ready[0], $tmp, 1))
{
print "Data read $tmp\n";
if ($tmp =~ /\n|\r|\r\n/o){
print "$line\n";
$line = "";
}else{
$line.=$tmp;
}
}
if(eof($ready[0])){
last;
}
}else{
print "Process.\n";
sleep(5);
}
}
#Result
./producer.pl | ./consumer.pl
Data read H
Process.
Data read e
Data read l
Data read l
Data read o
Data read _
Data read 0
Data read
Hello_0
Process.
Data read H
Data read e
Data read l
Data read l
Data read o
Data read _
Data read 1
Data read
Hello_1
Process.
Data read H
Data read e
Data read l
Data read l
Data read o
Data read _
Data read 2
Data read
Hello_2
Process.
Process.
If the producer dies, the consumer can read the last line,
but it never happens.
Thanks,
In reply to Re^4: Read from a Linux pipe hangs.
by dmor4477
in thread Read from a Linux pipe hangs.
by dmor4477
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |