How to reset a socket back to blocking mode (after I set it to nonblocking mode)?

时光怂恿深爱的人放手 提交于 2019-11-26 17:23:06

问题


I have read this regarding setting a socket to non-blocking mode.

http://www.gnu.org/software/libc/manual/html_mono/libc.html#File-Status-Flags

Here is what I did:

static void setnonblocking(int sock)
{
    int opts;

    opts = fcntl(sock,F_GETFL);
    if (opts < 0) {
        perror("fcntl(F_GETFL)");
        exit(EXIT_FAILURE);
    }
    opts = (opts | O_NONBLOCK);
    if (fcntl(sock,F_SETFL,opts) < 0) {
        perror("fcntl(F_SETFL)");
        exit(EXIT_FAILURE);
    }
    return;
}

How can I set the socket back to Blocking mode? I don't see a O_BLOCK flag?

Thank you.


回答1:


Did you try clearing the O_NONBLOCK flag?

opts = opts & (~O_NONBLOCK)



回答2:


Here is a more cross-platform capable solution:

bool set_blocking_mode(int socket, bool is_blocking)
{
    bool ret = true;

#ifdef WIN32
    /// @note windows sockets are created in blocking mode by default
    // currently on windows, there is no easy way to obtain the socket's current blocking mode since WSAIsBlocking was deprecated
    u_long non_blocking = is_blocking ? 0 : 1;
    ret = NO_ERROR == ioctlsocket(socket, FIONBIO, &non_blocking);
#else
    const int flags = fcntl(socket, F_GETFL, 0);
    if ((flags & O_NONBLOCK) && !is_blocking) { info("set_blocking_mode(): socket was already in non-blocking mode"); return ret; }
    if (!(flags & O_NONBLOCK) && is_blocking) { info("set_blocking_mode(): socket was already in blocking mode"); return ret; }
    ret = 0 == fcntl(socket, F_SETFL, is_blocking ? flags ^ O_NONBLOCK : flags | O_NONBLOCK));
#endif

    return ret;
}



回答3:


Alternative way to clear the flag:

opts ^= O_NONBLOCK;

This will toggle the non-blocking flag, i.e. disable non-blocking if currently enabled.



来源:https://stackoverflow.com/questions/2149798/how-to-reset-a-socket-back-to-blocking-mode-after-i-set-it-to-nonblocking-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!