Unix:在调用 select() 时关闭读取文件描述符会发生什么 [英] Unix: What happens when a read file descriptor closes while calling select()

查看:45
本文介绍了Unix:在调用 select() 时关闭读取文件描述符会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在包含一堆读取文件描述符的 FD_SET 上调用 select().如果在 select() 调用期间,文件描述符之一关闭,会发生什么情况?假设发生了某种错误,那么我有责任从集合中查找并删除关闭的文件描述符吗?

Say that I call select() on a FD_SET containing a bunch of read file descriptors. What happens if during the select() call, one of the file descriptor closes? Assuming that some sort of error occurs, then is it my responsibility to find and remove the closed file descriptor from the set?

推荐答案

我不相信这是在任何地方指定的;某些系统可能会立即从 select 返回,而其他系统可能会继续阻塞.请注意,这可能发生的唯一方式是在多线程进程中(否则,close 不会在 select 期间发生;即使它发生在信号处理程序中,select 可能已经被信号中断了).因此,出现这种情况可能表明您有更大的问题需要担心.如果您正在轮询的文件描述符之一可以在 select 期间关闭,则更大的问题是相同的文件描述符可能会立即重新分配给新打开的文件(例如,在另一个不相关的线程中打开的文件)在 close 之后,轮询的线程可能会错误地对属于"不同线程的新文件执行 IO.

I don't believe this is specified anywhere; some systems may immediately return from select while others may continue blocking. Note that the only way this can happen is in a multi-threaded process (otherwise, the close cannot happen during select; even if it happened from a signal handler, select would have already been interrupted by the signal). As such, this situation arising probably indicates you have bigger issues to worry about. If one of the file descriptors you're polling can be closed during select, the bigger issue is that the same file descriptor might be reassigned to a newly opened file (e.g. one opened in another unrelated thread) immediately after the close, and the thread that's polling might then wrongly perform IO on the new file "belonging to" a different thread.

如果您的数据对象包含一组文件描述符,这些文件描述符将在多线程程序中使用 select 进行轮询,那么您几乎肯定需要使用某种同步原语来控制访问到那个集合,并且添加或删除文件描述符应该需要一个与 select(或成员上的任何 IO)正在进行的可能性互斥的锁.

If you have a data object that consists of a set of file descriptors that will be polled with select in a multithreaded program, you almost surely need to be using some sort of synchronization primitive to control access to that set, and adding or removing file descriptors should require a lock that's mutually exclusive with the possibility that select (or any IO on the members) is in progress.

当然在多线程的程序中,最好不要使用select,而是让多线程中的阻塞IO达到预期的效果,不需要复杂的锁逻辑.

Of course in a multi-threaded program, it may be better not to use select at all and instead let blocking IO in multiple threads achieve the desired result without complicated locking logic.

这篇关于Unix:在调用 select() 时关闭读取文件描述符会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆