gpt4 book ai didi

c - 为什么在 Linux 中使用 select

转载 作者:IT老高 更新时间:2023-10-28 12:38:41 25 4
gpt4 key购买 nike

我正在浏览一个串行程序,我观察到他们在使用 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

关于c - 为什么在 Linux 中使用 select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14544621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com