gpt4 book ai didi

connect() 在阻塞套接字上返回 "Operation now in progress"?

转载 作者:IT王子 更新时间:2023-10-29 00:07:14 25 4
gpt4 key购买 nike

我有一个阻塞套接字(至少在下面的代码中是这样):

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
ERROR("%s: error opening socket", __func__);
return (RESP_ERROR);
}

t.tv_sec = timeout;
t.tv_usec = 0;

int rf = fcntl(sock, F_GETFD);
ERROR("fcntl ret=%d, ret & O_NONBLOCK = %d", rf, rf & O_NONBLOCK);

if ((setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&t, sizeof (t)) < 0)
|| (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&t, sizeof (t)))) {
strerror_r(errno, err, 254);
ERROR("%s: error on setsockopt -> %s", __func__, err);
close(sock);
return (RESP_ERROR);
}

rf = fcntl(sock, F_GETFD);
ERROR("after select fcntl ret=%d, ret & O_NONBLOCK = %d", rf, rf & O_NONBLOCK);

if (connect(sock, (struct sockaddr *)&dst, sizeof (dst)) != 0) {
strerror_r(errno, err, 254);
ERROR("%s: error on connect -> %s", __func__, err);
close(sock);
return (RESP_ERROR);
}

这是来自日志:

Mar 6 10:42:04 tcpclient: fcntl ret=0, ret & O_NONBLOCK = 0

Mar 6 10:42:04 tcpclient: after select fcntl ret=0, ret & O_NONBLOCK = 0

Mar 6 10:42:14 tcpclient: authenticate: error on connect -> Operation now in progress

看起来这是一个阻塞套接字,但返回非阻塞的典型错误? Linux 是 2.6.18-308.el5。有什么想法吗?

最佳答案

如果 timeout 不是 0,则对 connect() 的调用超时并返回。这与连接是否建立无关。

从超时过期的那一刻起,connect() 的行为就像在非阻塞套接字上调用一样。

引用此案例(逐字来自 man connect 并忽略下面的“immediately”):

EINPROGRESS

The socket is nonblocking and the connection cannot be completed immediately. It is possible to select(2) or poll(2) for completion by selecting the socket for writing. After select(2) indicates writability, use getsockopt(2) to read the SO_ERROR option at level SOL_SOCKET to determine whether connect() completed successfully (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual error codes listed here, explain‐ ing the reason for the failure).


顺便说一句:有人可以确认这是标准行为,并且在某处明确提到过吗?

man 7 socket 状态(我用斜体):

SO_RCVTIMEO and SO_SNDTIMEO

Specify the receiving or sending timeouts until reporting an error. [...] if no data has been transferred and the timeout has been reached then -1 is returned with errno set to EAGAIN or EWOULDBLOCK just as if the socket was specified to be nonblocking. [...] Timeouts only have effect for system calls that perform socket I/O (e.g., read(2), recvmsg(2), send(2), sendmsg(2)); timeouts have no effect for select(2), poll(2), epoll_wait(2), etc.

没有关于 connect() 的消息,所以我不确定我的答案是否成立。

关于connect() 在阻塞套接字上返回 "Operation now in progress"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15243988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com