非阻塞连接上的MacOSX select()行为不正确

时间:2009-08-08 22:19:23

标签: c macos sockets

我正在使用我的跨平台框架中的套接字层,我正试图让连接以非阻塞的方式工作。然而,在倾注了文档之后,他们似乎根本没有表现得正常。问题的核心是,在启动非阻塞连接后,以下选择失败以注意连接已成功并继续一遍又一遍地超时。

SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
hostent *h = gethostbyname("www.memecode.com");
if (h)
{
    sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);

    if (h->h_addr_list && h->h_addr_list[0])
    {
        memcpy(&addr.sin_addr, h->h_addr_list[0], sizeof(in_addr));

        // Set non blocking
        fcntl(s, F_SETFL, O_NONBLOCK);

        int64 start = LgiCurrentTime();
        int status = connect(s, (sockaddr*) &addr, sizeof(sockaddr_in));
        printf("Initial connect = %i\n", status);
        while (status && (LgiCurrentTime()-start) < 15000)
        {
            //  Do select to wait for connect to finish
            fd_set wr;
            FD_ZERO(&wr);
            FD_SET(s, &wr);
            int TimeoutMs = 1000;
            struct timeval t = {TimeoutMs / 1000, (TimeoutMs % 1000) * 1000};
            errno = 0;
            int64 sel_start = LgiCurrentTime();
            int ret = select(0, 0, &wr, 0, &t);
            int64 sel_end = LgiCurrentTime();
            printf("%i = select(0,%i,0) errno=%i time=%i\n",
                ret,
                FD_ISSET(s, &wr)!=0,
                errno,
                (int)(sel_end-sel_start));

            if (ret > 0 && FD_ISSET(s, &wr))
            {
                // ready for connect to finish...
                status = connect(s, (sockaddr*) &addr, sizeof(sockaddr_in));
                printf("2nd connect = %i\n", status);
                if (status)
                {
                    if (errno == EISCONN)
                    {
                        status = 0;
                        printf("error = EISCONN so we're good.\n");
                    }
                }
            }
            // else still waiting...
        }
    }
    else printf("host addr error.\n");
}
else printf("gethostbyname failed.\n");

当我在最新的MacOSX Leopard版本上运行此代码时,我得到了这个输出:

Initial connect = -1
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1001
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1000
0 = select(0,1,0) errno=0 time=1000

当我在选择后删除“ret&gt; 0”条件时,连接成功并返回EISCONN。所以连接在幕后工作,但选择永远不会在它上面。根据我对select返回值的理解,它包含fd_set结构中的套接字数,如果没有事件,则返回0。

我的代码出了什么问题?

PS LgiCurrentTime()返回自某点以来的毫秒数,例如: Windows上的GetTickCount ...我忘记了Mac上的确切建议,但这并不重要......只是时间信息。

1 个答案:

答案 0 :(得分:1)

我认为select(..)的第一个参数应该是最高的文件描述符编号+1而不是0使其成为

int ret = select(s+1, 0, &wr, 0, &t);