为什么在Linux中使用的选择 [英] Why is select used in Linux

查看:132
本文介绍了为什么在Linux中使用的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要通过一个串行程序,我发现他们使用选择()使用前阅读() 。到底为什么是这样要求的。为什么不能我们只是直接调用阅读()并检查是否发生故障或不?同时我们为什么必须用1来增加文件描述符,并通过它,而我传递)的文件描述符已设置为选择(

I was going through a serial program and I observed that they use select() before using read(). Why exactly is this required. Why cant we just directly call read() and check if it fails or not ? Also 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()?

例如:

R =选择(FD + 1,&安培; FDS,NULL,NULL,&安培;超时);
 其中,FDS已经fd的值

r=select(fd+1, &fds, NULL, NULL, &timeout); where fds already has the value of fd

推荐答案

的<一个href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/select.html\"><$c$c>select()系统调用告诉你是否有任何数据在你感兴趣的文件描述符读取。严格来说,它是对文件描述符的读操作是阻止还是不是个问题。

The select() system call tells you whether there is any data to read on the file descriptors that you're interested in. Strictly, it is a question of whether a read operation on the file descriptor will block or not.

如果您执行阅读()上的文件描述符 - 如连接到串行端口 - 并没有要读取的数据,则调用将挂起,直到有一些数据来读取。使用程序选择()不希望被阻止这样的。

If you execute read() on a file descriptor — such as that connected to a serial port — and there is no data to read, then the call will hang until there is some data to read. Programs using select() do not wish to be blocked like that.

您还问:

为什么我们用1来增加文件描述符,并通过它,而我传递的文件描述符已设置为选择

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 的大小,但可能做很糟糕。第一个参数选择()被称为 NFDs的 的和POSIX说:

That's probably specifying the size of the FD_SET but probably doing it badly. The first argument to select() is known as nfds and POSIX says:

NFDs的参数指定要测试的描述符的范围。第一个 NFDs的描述符应在每一组进行检查;也就是说,从0到 NFDs的-1 在描述符集的描述应当审查。

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.

因此​​,要测试一个文件描述符 N NFDs的的值必须至少 N + 1

So, to test a file descriptor n, the value in nfds must be at least n+1.

这篇关于为什么在Linux中使用的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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