我正在浏览一个串行程序,我观察到他们在使用 read()
之前使用了 select()
。为什么需要这样做。为什么我们不能直接调用 read()
并检查它是否失败?另外,为什么我们必须将文件描述符增加 1 并在我将文件描述符集传递给 select()
时传递它?
例子:
r=select(fd+1, &fds, NULL, NULL, &timeout);
其中 fds 已经具有 fd 的值
最佳答案
select()
系统调用告诉你在你感兴趣的文件描述符上是否有任何数据要读取。严格来说,这是一个文件描述符上的读取操作是否会阻塞的问题。
如果您在文件描述符上执行 read()
- 例如连接到串行端口的文件描述符 - 并且没有要读取的数据,那么调用将挂起,直到有一些数据要读取.使用 select()
的程序不希望这样被阻止。
你还问:
Why do we have to increment the file descriptor by 1 and pass it while I am passing the file descriptor set already to
select
?
这可能是指定 FD_SET 的大小。 select()
的第一个参数称为 nfds
,POSIX 表示:
The
nfds
argument specifies the range of descriptors to be tested. The firstnfds
descriptors shall be checked in each set; that is, the descriptors from zero throughnfds-1
in the descriptor sets shall be examined.
因此,要测试文件描述符 n
,nfds
中的值必须至少为 n+1
。
关于c - 为什么在 Linux 中使用 select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14544621/