c - 为什么在 Linux 中使用 select

我正在浏览一个串行程序,我观察到他们在使用 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 first nfds descriptors shall be checked in each set; that is, the descriptors from zero through nfds-1 in the descriptor sets shall be examined.

因此,要测试文件描述符 nnfds 中的值必须至少为 n+1

https://stackoverflow.com/questions/14544621/

相关文章:

linux - 在家学习内核黑客和嵌入式开发?

linux - RealUID,保存的 UID,有效的 UID。这是怎么回事?

linux - 应用程序如何在运行时解析为不同版本的共享库?

linux - 跨多台计算机管理用户配置文件

linux - 使用 Linux 加载程序时 ldconfig 错误 :"is not a symb

c - Linux内核代码中的 "EXPORT_SYMBOL"是什么意思?

linux - 让 Tk 看起来像一个原生 Linux 应用程序

linux - 需要对 Linux bash 内置 exec 命令行为的解释

linux - 使用 'sudo apt-get install build-essentials'

linux - 当我在脚本中使用它时,无法关闭带有 echo "^]"的 scpi(telnet)