开发者

Blocking read from file in PHP

开发者 https://www.devze.com 2023-01-27 07:03 出处:网络
Here is what I want expressed in bash: while true; do while read $line; do echo \"Heard: $line\" done < fifo

Here is what I want expressed in bash:

while true; do
  while read $line; do
    echo "Heard: $line"
  done < fifo
done

Here, fifo is the path to a named pip开发者_StackOverflow社区e. This will read from the fifo, but if the fifo is empty, it will block until there is something in it.

Trying a similar thing in PHP results in a busy-loop since fgets returns when there is nothing in the pipe.


Add

sleep(1);

to avoid heavy cpu usage. This is just the most simple way to avoid busy-loops. You can also look at stream_select(), which allows to specify a timeout how long the script should wait for a readable (or writeable) stream. Or you can try to change the default behaviour of fgets() for a specific stream with stream_set_blocking(). I dont know exactly (I didnt try it myself), but it seems the last one is the one you are looking for.

stream_set_blocking($stream, 1);
$r = fgets($stream);


I believe fread is blocking.


fopen() is where you get blocking; not on fgets(). My problem was that I fopen()ed the file then started my loop, so once the pipe was written to once, the busy loop would start. Instead, putting the fopen() in the loop makes it block until there is a writer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号