c - 在linux中创建socket和FD_SET后select总是返回1

标签 c linux sockets

今天我正在 Linux (Debian) 中创建一个示例代码套接字。但在 FD_ZEROFD_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 and 17, nfds should not be 2,
but rather 17 + 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/

相关文章:

c - 为什么我的 for 循环预期显示标识符错误?

c - 使用 Reed-Solomon Erasure Correction 的前向纠错

c - 当访问我的结构中的图形时,它会打印一个空行

linux - 在 bash 脚本中使用 IF 条件比较整数

sockets - 一台机器作为 STunnel 的服务器和客户端

java - 使用线程处理套接字

c - Makefile 日志记录在第一个错误时停止并显示错误

javascript - 如何防止 ChildProcess 内存不足? Electron/Node.js

python - 使用不同的 mac 地址作为源模拟 1K Web 客户端

c# - 带有客户端身份验证的 .Net 和 Java 之间的 SSL 套接字