PHP 中阻止读取文件
这是我想要在 bash 中表达的内容:
while true; do
while read $line; do
echo "Heard: $line"
done < fifo
done
这里,fifo 是命名管道的路径。这将从 fifo 中读取,但如果 fifo 为空,它将阻塞,直到里面有东西为止。
在 PHP 中尝试类似的操作会导致繁忙循环,因为当管道中没有任何内容时 fgets 返回。
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 pipe. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
添加
以避免 CPU 使用率过高。这只是避免繁忙循环的最简单方法。您还可以查看 stream_select(),它允许指定脚本应等待的超时时间可读(或可写)流。或者您可以尝试使用 stream_set_blocking()。我不太清楚(我自己没有尝试过),但似乎最后一个就是您要找的那个。
Add
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.
我相信 fread 正在阻塞。
I believe fread is blocking.
fopen() 是你被阻止的地方;不在 fgets() 上。我的问题是我 fopen()ed 该文件然后开始循环,因此一旦管道被写入一次,繁忙的循环就会开始。相反,将 fopen() 放入循环中会使其阻塞,直到有写入者为止。
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.