为什么Linux会重用由pipe()分配的文件描述符
我在 Linux 中使用套接字和管道时遇到问题。具体来说,我们调用 pipeline(),它分配接下来的两个可用文件描述符...比方说 10 和 11。然后我们在套接字上调用 Accept(),期望它分配 12。相反,它分配 11。
我们已经测试了一下,似乎从 pipeline() 返回的第二个 FD 始终可供创建文件描述符的其他系统调用重用。
谁能解释一下吗?
I'm seeing an issue using both sockets and pipes in Linux. Specifically, we call pipe(), which allocates the next two available file descriptors... let's say 10 and 11. Then we call accept() on a socket, expecting it to allocate 12. Instead, it allocates 11.
We've tested a bit, and it seems the second FD returned from pipe() is always available for reuse by other syscalls that create file descriptors.
Can anyone explain this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这意味着有人在调用管道之后和第二次系统调用之前关闭了有问题的文件描述符。例如,如果您派生出其他进程来在管道的一端执行操作,则可能会搞砸关闭另一进程使用的管道末端的代码,并关闭错误的管道末端。或者任何其他可能在某些文件描述符上调用 close 的东西都可能会关闭错误的东西。
That would imply that someone is closing the file descriptor in question some time after the call to pipe and before the second syscall. For example, if you fork off some other process to do stuff on one end of the pipe, you might be screwing up your code that closes the end of the pipe used by the other process and closing the wrong end of the pipe. Or just about anything else that might call close on some file descriptor might be closing the wrong thing.
也许标志 SO_REUSEADDR 用于管道,因此您没有看到文件描述符编号的增量?编辑: 感谢 duck 和 darron 来提醒我愚蠢的答案。我正在阅读此 链接 ,如果
close()
是调用文件描述符,它会被重用...希望这有帮助,
此致,
汤姆.
Maybe the flag SO_REUSEADDR is used for pipes hence you're not seeing an increment in the file descriptor number?Edit: Thanks to duck and darron for the heads up on my stupid answer. I was reading this link and if
close()
is called on a file descriptor, it gets reused...Hope this helps,
Best regards,
Tom.