如何确定最大的FD选择? [英] How to determine max fd for select?

查看:207
本文介绍了如何确定最大的FD选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为标题也很简单,我想获得最高的FD数传进选择作为第一个参数尚未使用 FD_SETSISE 似乎是如此低效和不必要的。我的假设是,我的进程开始后,创建总会有最高的FD多项最新插座,所以我可以简单地把它加1,并把它传递给选择,这是真的?

Just as straightforward as the title, I want to get the highest fd number to pass into select as its first argument yet using FD_SETSISE seems to be so inefficient and unnecessary. My assumption is that after my process begins, the latest socket created will always have the highest fd number so I can simply add 1 to it and pass it to select, is that true?

推荐答案

FD_SETSIZE的的效率低下。它只是允许一组描述符的数量最多的一个方便的宏。如果你使用它,选择将通过整组搜索,即使你实际使用的最高描述可能相当低。也就是说,如果你想获得最大的描述符通过选择是7没有在迭代8至1024点没有(或任何FD_SETSIZE等于你的平台上)。

FD_SETSIZE is inefficient. It is just a convenience macro for the largest number of descriptors allowed in a set. If you use it, select will search through the entire set even though the highest descriptor you are actually using may be quite low. That is, if the highest descriptor you want to pass to select is 7 there is no point in iterating from 8 to 1024 (or whatever FD_SETSIZE is equal to on your platform).

我的假设是,我的进程开始后,创造了最新的插座将始终具有最高的FD号

My assumption is that after my process begins, the latest socket created will always have the highest fd number

没有,这是错误的。操作系统是怎么回事时,它会打开一个文件或套接字选择最低的可用文件描述符。所以,如果在你的程序的过程中,如果你有0-7打开,关闭5,然后创建另一个插座将被分配5。

No, this is wrong. The OS is going to choose the lowest available file descriptor when it opens a file or socket. So if in the course of your program if you have 0-7 open, close 5, and then create another socket it will be assigned 5.

底线是,你必须追踪最高的开放式插座自己。作为一个惯例,因为你必须FD_SET你想每一个选择调用之前,选择要使用的套反正也不是很难放一点如果还有语句来找到您要添加到集中的最大文件描述符。它不需要任何东西太多参与比是这样的:

The bottom line is that you have to keep track of the highest open socket yourself. As a practice, since you have to FD_SET the sets you want to use in select before every select call anyway it isn't hard to put a little if statement in there to find the max file descriptor you are adding to the set. It need not be anything too much involved than something like this:

  int maxfd;

  for (i = 0, maxfd = 0; i < nclients; i++)
  {
    FD_SET(clients[i], &read_fds);
    if (clients[i] > maxfd)
        maxfd = clients[i];
  }

  select(maxfd + 1, ........);

替代品是寻找到调查的epoll 这消除了一些选择的滋扰的。

Alternatives are to look into poll and epoll which eliminate some of the nuisances of select.

这篇关于如何确定最大的FD选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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