相关疑难解决方法(0)

如何将TCP套接字更改为非阻塞?

你如何使套接字无阻塞?

我知道这个fcntl()功能,但我听说它并不总是可靠的.

c sockets

34
推荐指数
7
解决办法
13万
查看次数

对非阻塞套接字使用select()总是返回1

这个问题与(非常接近)在非阻塞套接字连接中,select()始终返回1;但是,我似乎找不到我的代码步履蹒跚的地方。

我正在使用非阻塞套接字,并且想在将客户端连接到服务器以检查超时/成功时使用select()。问题是select()几乎总是立即返回1,即使我什至没有服务器在运行,也没有什么可连接的。预先感谢您的帮助,代码片段如下:

//Loop through the addrinfo structs and try to connect to the first one we can
for(p = serverinfo; p != NULL; p = p->ai_next) {
    if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) 
    {
        //We couldn't create the socket, try again
        perror("client: socket");
        continue;
    }

    //Set the socket to non-blocking
    int flags = fcntl(sockfd, F_GETFL, 0);
    fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);

    if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
        //The error was something other than non-block/in progress, …
Run Code Online (Sandbox Code Playgroud)

c sockets select nonblocking

5
推荐指数
1
解决办法
3万
查看次数

连接后非阻塞套接字选择返回1

首先,我想说这是另一个问题而不是这个:类似但不一样

我的代码看起来像这样:

struct addrinfo hints, *res;
struct sockaddr* serveraddr;

memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;

int res2 = getaddrinfo(ip, port, &hints, &res);
printf("getaddrinfo() res: %d, %d\n", res2, errno);

serveraddr = res->ai_addr;

//create new socket

int soc = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
printf("socket() res: %d, %d\n", socket, errno);

//set nonblocking mode
unsigned long on = 1;
res2 = ioctl(soc, FIONBIO, &on);
printf("ioctl() res: %d\n, %d", res2, errno);

res2 = connect(soc, serveraddr, sizeof(struct sockaddr));
printf("connect() res: %d, %d\n", res2, …
Run Code Online (Sandbox Code Playgroud)

c sockets linux nonblocking select-function

2
推荐指数
1
解决办法
2693
查看次数

标签 统计

c ×3

sockets ×3

nonblocking ×2

linux ×1

select ×1

select-function ×1