如何在连接到套接字时设置超时

问题描述 投票:0回答:2

我正在尝试为

connect()
提供超时,但
getsockopt()
没有报告任何错误。但当我到达
write()
时,它失败并显示“errno of 107 - ENOTCONN”。

我在 Fedora 23 上运行。

connect()
的文档说,对于尚未完成的连接,它应该返回失败,错误号为 EINPROGRESS,但是我遇到了 EAGAIN,所以我将其添加到我的检查中。

目前我的套接字服务器正在

listen()
调用中将积压设置为零。许多调用都会成功,但失败的调用都会失败,并出现我在
write()
调用中提到的 107 - ENOTCONN。

int domain_socket_send(const char* socket_name, unsigned char* buffer,
        unsigned int length, unsigned int timeout)
{
    struct sockaddr_un addr;
    int fd = -1;
    int result = 0;

    // Create socket.
    
    fd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (fd == -1)
        {
        result = -1;
        goto done;
        }

    if (timeout != 0)
        {
        
        // Enabled non-blocking.

        int flags;
        flags = fcntl(fd, F_GETFL);
        fcntl(fd, F_SETFL, flags | O_NONBLOCK);
        }

    // Set socket name.
    
    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, socket_name, sizeof(addr.sun_path) - 1);

    // Connect.
    
    result = connect(fd, (struct sockaddr*) &addr, sizeof(addr));
    if (result == -1)
        {

        // If some error then we're done.
        
        if ((errno != EINPROGRESS) && (errno != EAGAIN))
            goto done;

        fd_set write_set;
        struct timeval tv;

        // Set timeout.
        
        tv.tv_sec = timeout / 1000000;
        tv.tv_usec = timeout % 1000000;

        unsigned int iterations = 0;
        while (1)
            {
            FD_ZERO(&write_set);
            FD_SET(fd, &write_set);

            result = select(fd + 1, NULL, &write_set, NULL, &tv);
            if (result == -1)
                goto done;
            else if (result == 0)
                {
                result = -1;
                errno = ETIMEDOUT;
                goto done;
                }
            else
                {
                if (FD_ISSET(fd, &write_set))
                    {
                    socklen_t len;
                    int socket_error;
                    len = sizeof(socket_error);
            
                    // Get the result of the connect() call.
            
                    result = getsockopt(fd, SOL_SOCKET, SO_ERROR,
                            &socket_error, &len);
                    if (result == -1)
                        goto done;

                    // I think SO_ERROR will be zero for a successful
                    // result and errno otherwise.

                    if (socket_error != 0)
                        {
                        result = -1;
                        errno = socket_error;
                        goto done;
                        }

                    // Now that the socket is writable issue another connect.
            
                    result = connect(fd, (struct sockaddr*) &addr,
                            sizeof(addr));
                    if (result == 0)
                        {
                        if (iterations > 1)
                            {
                            printf("connect() succeeded on iteration %d\n",
                                    iterations);
                            }
                        break;
                        }
                    else
                        {
                        if ((errno != EAGAIN) && (errno != EINPROGRESS))
                            {
                            int err = errno;
                            printf("second connect() failed, errno = %d\n",
                                    errno);
                            errno = err;
                            goto done;
                            }
                        iterations++;
                        }
                    }
                }
            }
        }

    // If we put the socket in non-blocking mode then put it back
    // to blocking mode.

    if (timeout != 0)
        {
        
        // Turn off non-blocking.

        int flags;
        flags = fcntl(fd, F_GETFL);
        fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
        }

    // Write buffer.

    result = write(fd, buffer, length);
    if (result == -1)
        {
        int err = errno;
        printf("write() failed, errno = %d\n", err);
        errno = err;
        goto done;
        }

done:
    if (result == -1)
        result = errno;
    else
        result = 0;
    if (fd != -1)
        {
        shutdown(fd, SHUT_RDWR);
        close(fd);
        }
    return result;
}

我突然意识到,也许我需要多次调用

connect()
直到成功,毕竟这是非阻塞 I/O 而不是异步 I/O。就像我在
read()
上遇到 EAGAIN 后,有数据要读取时必须再次调用
read()
一样。另外,我发现了以下SO问题:Using select() for non-blocking sockets to connect always returns 1,其中EJP的答案说你需要发出多个
connect()

另外,从EJP参考文献这本书来看,似乎表明您需要发出多个

connect()

我修改了这个问题中的代码片段来调用

connect()
,直到成功。我可能仍然需要进行更改,可能会更新传递给
select()
的超时值,但这不是我直接的问题。

多次调用

connect()
似乎解决了我原来的问题,即我在调用
write()
时收到ENOTCONN,我猜是因为套接字未连接。

但是,您可以从代码中看到我正在跟踪 select 循环多少次,直到

connect()
成功。我见过这个数字达到数千。这让我担心我正处于繁忙的等待循环中。

为什么套接字可写,即使它没有处于

connect()
会成功的状态?正在调用
connect()
清除可写状态,并且由于某种原因操作系统再次设置它,或者我真的处于繁忙的等待循环中?

c sockets timeout nonblocking
2个回答
1
投票

来自 http://lxr.free-electrons.com/source/net/unix/af_unix.c

441 static int unix_writable(const struct sock *sk)
442 {
443         return sk->sk_state != TCP_LISTEN &&
444                (atomic_read(&sk->sk_wmem_alloc) << 2) <= sk->sk_sndbuf;
445 }

我不确定正在比较的这些缓冲区是什么,但显然没有检查套接字的连接状态。因此,除非在套接字连接时修改这些缓冲区,否则我的 unix 套接字将始终被标记为可写,因此我无法使用 select() 来确定非阻塞 connect() 何时完成。

并基于以下片段:http://lxr.free-electrons.com/source/net/unix/af_unix.c:

1206 static int unix_stream_connect(struct socket *sock, struct sockaddr *uaddr,
1207                                int addr_len, int flags)
.
.
.
1230         timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
.
.
.
1271         if (unix_recvq_full(other)) {
1272                 err = -EAGAIN;
1273                 if (!timeo)
1274                         goto out_unlock;
1275 
1276                 timeo = unix_wait_for_peer(other, timeo);
.
.
.

设置发送超时似乎可以使连接超时。这也与 http://man7.org/linux/man-pages/man7/socket.7.html.

上的 SO_SNDTIMEO 文档相匹配。

谢谢, 尼克


0
投票

您对

select()
的错误处理可能需要进行一些清理。除非设置了
SO_ERROR
,否则您实际上不需要查询
except_set
。如果
select()
返回 > 0,则设置
write_set
和/或
except_set
,如果未设置
except_set
,则连接成功。

尝试更像这样的事情:

int domain_socket_send(const char* socket_name, unsigned char* buffer,
    unsigned int length, unsigned int timeout)
{
    struct sockaddr_un addr;
    int fd;
    int result;

    // Create socket.

    fd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (fd == -1)
        return errno;

    if (timeout != 0)
        {

        // Enabled non-blocking.

        int flags = fcntl(fd, F_GETFL);
        fcntl(fd, F_SETFL, flags | O_NONBLOCK);
        }

    // Set socket name.

    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, socket_name, sizeof(addr.sun_path) - 1);

    // Connect.

    result = connect(fd, (struct sockaddr*) &addr, sizeof(addr));
    if (result == -1)
        {

        // If some error then we're done.

        if ((errno != EINPROGRESS) && (errno != EAGAIN))
            goto done;

        // Now select() to find out when connect() has finished.

        fd_set write_set;
        fd_set except_set;

        FD_ZERO(&write_set);
        FD_ZERO(&write_set);
        FD_SET(fd, &write_set);
        FD_SET(fd, &except_set);

        struct timeval tv;

        // Set timeout.

        tv.tv_sec = timeout / 1000000;
        tv.tv_usec = timeout % 1000000;

        result = select(fd + 1, NULL, &write_set, &except_set, &tv);
        if (result == -1)
            {
            goto done;
            }
        else if (result == 0)
            {
            result = -1;
            errno = ETIMEDOUT;
            goto done;
            }
        else if (FD_ISSET(fd, &except_set))
            {
            int socket_error;
            socklen_t len = sizeof(socket_error);

            // Get the result of the connect() call.

            result = getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &len);
            if (result != -1)
                {
                result = -1;
                errno = socket_error;
                }

            goto done;
            }
        else
            {
            // connected
            }
        }

    // If we put the socket in non-blocking mode then put it back
    // to blocking mode.

    if (timeout != 0)
        {
        int flags = fcntl(fd, F_GETFL);
        fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
        }

    // Write buffer.

    result = write(fd, buffer, length);

done:
    if (result == -1)
        result = errno;
    else
        result = 0;

    if (fd != -1)
        {
        shutdown(fd, SHUT_RDWR);
        close(fd);
        }

    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.