常规文件读取可以从非阻塞 IO 中受益吗?
对我来说似乎不是,我找到了一个支持我的观点的链接。你怎么认为?
It seems not to me and I found a link that supports my opinion. What do you think?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您发布的链接内容是正确的。以非阻塞模式打开的常规文件套接字将始终“准备好”读取;当您实际尝试读取它时,会发生阻塞(或更准确地说,正如消息来源指出的那样,休眠),直到操作成功为止。
无论如何,我认为你的消息来源需要一些镇静剂。一个愤怒的人,就是这样。
The content of the link you posted is correct. A regular file socket, opened in non-blocking mode, will always be "ready" for reading; when you actually try to read it, blocking (or more accurately as your source points out, sleeping) will occur until the operation can succeed.
In any case, I think your source needs some sedatives. One angry person, that is.
在过去的几个小时里,我一直在深入研究这个问题,并且可以证明您引用的链接的作者是正确的。然而,对 非阻塞 IO 的支持似乎是“更好”(非常宽松地使用该术语) v2.6+ 的本机 Linux 内核中的常规文件。 “libaio”包包含一个公开内核提供的功能的库,但它对受支持的不同类型的文件系统有一些警告,并且它不能移植到 Linux 2.6+ 之外的任何版本。
这是关于该主题的另一篇好文章。
I've been digging into this quite heavily for the past few hours and can attest that the author of the link you cited is correct. However, the appears to be "better" (using that term very loosely) support for non-blocking IO against regular files in native Linux Kernel for v2.6+. The "libaio" package contains a library that exposes the functionality offered by the kernel, but it has some caveats about the different types of file systems which are supported and it's not portable to anything outside of Linux 2.6+.
And here's another good article on the subject.
您是对的,非阻塞模式对常规文件没有任何好处,并且不允许这样做。如果有一个可以设置的辅助标志以及 O_NONBLOCK 来更改此设置,那就太好了,但由于缓存和虚拟内存的工作方式,定义什么实际上并不是一件容易的事普通文件的正确“非阻塞”行为意味着。当然,除非您允许程序锁定与文件关联的内存,否则会出现竞争条件。 (事实上,为普通文件实现一种非睡眠 IO 的一种方法是
mmap
文件并mlock
映射。之后,在任何合理的实现上,只要文件偏移量和缓冲区大小保持在映射区域的范围内,read
和write
就永远不会休眠。)You're correct that nonblocking mode has no benefit for regular files, and is not allowed to. It would be nice if there were a secondary flag that could be set, along with
O_NONBLOCK
, to change this, but due to the way cache and virtual memory work, it's actually not an easy task to define what correct "non-blocking" behavior for ordinary files would mean. Certainly there would be race conditions unless you allowed programs to lock memory associated with the file. (In fact, one way to implement a sort of non-sleeping IO for ordinary files would be tommap
the file andmlock
the map. After that, on any reasonable implementation,read
andwrite
would never sleep as long as the file offset and buffer size remained within the bounds of the mapped region.)