Async connect and disconnect with epoll (Linux)

前端 未结 4 2039
无人共我
无人共我 2020-12-07 23:45

I need async connect and disconnect for tcp client using epoll for Linux. There are ext. functions in Windows, such as ConnectEx, DisconnectEx, AcceptEx, etc... In tcp serv

4条回答
  •  庸人自扰
    2020-12-08 00:26

    To do a non-blocking connect(), assuming the socket has already been made non-blocking:

    int res = connect(fd, ...);
    if (res < 0 && errno != EINPROGRESS) {
        // error, fail somehow, close socket
        return;
    }
    
    if (res == 0) {
        // connection has succeeded immediately
    } else {
        // connection attempt is in progress
    }
    

    For the second case, where connect() failed with EINPROGRESS (and only in this case), you have to wait for the socket to be writable, e.g. for epoll specify that you're waiting for EPOLLOUT on this socket. Once you get notified that it's writable (with epoll, also expect to get an EPOLLERR or EPOLLHUP event), check the result of the connection attempt:

    int result;
    socklen_t result_len = sizeof(result);
    if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &result, &result_len) < 0) {
        // error, fail somehow, close socket
        return;
    }
    
    if (result != 0) {
        // connection failed; error code is in 'result'
        return;
    }
    
    // socket is ready for read()/write()
    

    In my experience, on Linux, connect() never immediately succeeds and you always have to wait for writability. However, for example, on FreeBSD, I've seen non-blocking connect() to localhost succeeding right away.

提交回复
热议问题