你好,我有一个关于select()的问题 [英] hello i have a question about select()

查看:96
本文介绍了你好,我有一个关于select()的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解select():

i know about select() :

int select(int nfds, fd_set *readfds, fd_set *writefds,
                  fd_set *exceptfds, struct timeval *timeout);



nfds是参数,指定要测试的描述符的数量.
如果我将nfds设置为0.这种方式会影响select()吗?
例如:



nfds is argument specifies the number of descriptors to be tested.
if i set nfds to be 0. This way will impact the select()?
for example:

#include <stdio.h>
       #include <stdlib.h>
       #include <sys/time.h>
       #include <sys/types.h>
       #include <unistd.h>
       int
       main(void)
       {
           fd_set rfds;
           struct timeval tv;
           int retval;
           /* Watch stdin (fd 0) to see when it has input. */
           FD_ZERO(&rfds);
           FD_SET(0, &rfds);
           /* Wait up to five seconds. */
           tv.tv_sec = 5;
           tv.tv_usec = 0;
           retval = select(1, &rfds, NULL, NULL, &tv);
           /* Don't rely on the value of tv now! */
           if (retval == -1)
               perror("select()");
           else if (retval)
               printf("Data is available now.\n");
               /* FD_ISSET(0, &rfds) will be true. */
           else
               printf("No data within five seconds.\n");
           exit(EXIT_SUCCESS);
       }




如果我将nfds设置为1,就可以了,并且可以使用printf数据现在可用.".
但是,如果我将其设置为0,它仍然可以运行,但是会花费更多的时间并打印出五秒钟之内没有数据".


请告诉我为什么或告诉我在哪里可以找到答案,谢谢!




if i set nfds to be 1, it will be ok and printf " Data is available now. ".
But if i set it to be 0, it still can run but it take more time and printf "No data within five seconds".


please tell me why or tell me where i can find the answer, thank you!

推荐答案

nfds是您在select(),但该描述有点误导.

文件描述符从0开始,然后从那里开始.因此,fd_set可以是位数组,其中,如果您想听第n个文件描述符,则可以在fd_set中设置第n + 1个位.但是,select()需要知道在哪里停止,以便nfds进入哪里,这就是为什么nfds必须设置为您要收听的最大文件描述符号的原因. .

将其设置为0时,select()实际上没有监听任何文件描述符,这就是为什么它超时的原因.
nfds is the number of file descriptors that you are listening for in select(), but that description is a little misleading.

File descriptors start at 0 and go up from there. Thus, the fd_sets can be bit arrays, where if you want to listen to the nth file descriptor then you set the n+1th bit in the fd_set. However, select() needs to know where to stop, so that''s where nfds comes in, and that''s why nfds must be set to the maximum file descriptor number that you want to listen to plus one.

When you set it to 0, select() is effectively listening to no file descriptors, which is why it hits the timeout.


这篇关于你好,我有一个关于select()的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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