in reply to read does not block
Presumably there is a delay before the data response to write() is available from read(). Here is how to wait and also time out after a certain delay so you don't go infinite. The read_data() sub will return a value 3 seconds after the program starts. This simulates a delay. It will time out as shown as we only try to get data for 2 seconds. Uncomment the $wait = 5; line to see it succeed. You can see that it tries a lot (several hundred times) - this is very resource intensive so a short sleep is often a good idea before retries. You can trial the sleep 1 to see it cut the retries. There is a Time::HiRes module available to let you sleep a few millisconds which would generally be better as a full second is a bit over the top as you note.
$wait = 2; # wait up to this many seconds for data # $wait = 5; $start = time(); # zero our vars and then enter the do until loop $timeout = $wait + time(); $data = ''; $count = 0; do { $count++; $data = read_data(); # sleep 1 unless $data; } until $data or time() > $timeout; if ($data) { print "Tried $count times\nGot data '$data'\n"; } else { print "Tried to read_data() but failed after $wait seconds and $co +unt tries!\n"; } # a short sub that only returns data after 3 seconds from # program start time sub read_data { return (time() > ( $start + 3) ) ? "You have waited long enough!" : +''; }
cheers
tachyon
s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print
|
|---|