今天我正在 Linux (Debian) 中创建一个示例代码套接字。但在 FD_ZERO
和 FD_SET
之后,它运行不正确。 select
将在超时之前返回 1 (我的期望是 select 将返回 0 ),但我没有对套接字采取任何操作。这是我的代码。有人可以帮助我吗?
#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 sockfd, retval;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
/* Watch sockfd to see when it has input. */
FD_ZERO(&rfds);
FD_SET(sockfd, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(FD_SETSIZE, &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(sockfd, &rfds) will be true. */
else
printf("No data within five seconds.\n");
exit(EXIT_SUCCESS);
}
最佳答案
第一个问题是FD_SET
。第一个参数应该是套接字的文件描述符:
FD_SET( sockfd, &rfds );
select
调用也存在问题。第一个参数必须大于最大描述符。从 select
的手册页中:
(Example: If you have set two file descriptors
4
and17
, nfds should not be2
,
but rather17 + 1
, i.e.18
.)
因此 select
调用应该是:
select( sockfd+1, &rfds, NULL, NULL, &tv );
关于c - 在linux中创建socket和FD_SET后select总是返回1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39183953/