简体   繁体   English

如何在 C / C++ 中使用 FD_SET Unix 设置套接字文件描述符

[英]How to set Socket File Descriptor with FD_SET Unix in C / C++

I'm currently working on a socket programming project.我目前正在从事套接字编程项目。 Let's assume:让我们假设:

fd_set fd_in;

Now I would like to set the file Descriptor for the select function:现在我想为 select function 设置文件描述符:

FD_SET(socket_fd, &fd_in);

Is that the right way?那是正确的方法吗?

Then I use the select function:然后我使用 select function:

int rc = select(socket_fd + 1, &fd_in, NULL, NULL, NULL);

Having done some research I haven't managed to proceed.做了一些研究,我还没有设法继续。

I appreciate your support, Regards, from Brooks感谢您的支持,问候,来自布鲁克斯

The appropriate manual pages are available on line, for example here .相应的手册页可在线获取,例如此处

Nevertheless, it might not be clear to you that before adding any file descriptors to your fd_set , you should first clear it:不过,您可能不清楚在将任何文件描述符添加到fd_set之前,您应该先清除它:

FD_ZERO(&fd_in);

Then, yes, you use FD_SET() just as you present in the question:然后,是的,您使用FD_SET()就像您在问题中提出的那样:

 FD_SET(socket_fd, &fd_in);

That assumes that the value of socket_fd is an open file descriptor.假设socket_fd的值是一个打开的文件描述符。

Having done so, it is reasonable to use a pointer to the resulting fd_set as one of the arguments to select() , again as you present:这样做之后,使用指向结果fd_set的指针作为select()的 arguments 之一是合理的,再次如您所见:

 int rc = select(socket_fd + 1, &fd_in, NULL, NULL, NULL);

Do note that请注意

  • that particular call registers interest only in the specified file descriptor becoming available for reading (or for accepting a connection if it is a listening socket), not for writing or exceptional conditions.该特定调用仅对指定的文件描述符感兴趣,该文件描述符可用于读取(或者如果它是侦听套接字,则用于接受连接),而不是用于写入或异常情况。

  • you must check select() 's return value and take appropriate action based on the result.您必须检查select()的返回值并根据结果采取适当的措施。 Since you're using only a single fd_set with a single element, without a timeout, you should expect select to return either 1 (when the file descriptor is ready) or -1 (on error).由于您仅使用带有单个元素的单个fd_set ,没有超时,因此您应该期望select返回 1(当文件描述符准备好时)或 -1(出错时)。

  • generally speaking, you need to set up the fd_set(s) each time you call select .一般来说,每次调用select时都需要设置 fd_set(s) 。 Except in certain special cases, the contents of the sets after select() returns are often not the same as they were before the call, and in the event that select reports an error then you cannot afterward rely on anything about them at all.除非在某些特殊情况下, select()返回之后的集合内容通常与调用之前的内容不同,并且如果select报告错误,那么您就不能再依赖它们的任何内容了。 Thus, when select() is called in a loop, which is common, there generally needs to be fd_set setup code in the same loop.因此,当在循环中调用select()时,这很常见,通常需要在同一个循环中有 fd_set 设置代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM