如何将套接字重置回阻塞模式(在我将其设置为非阻塞模式后)?

n17*_*911 14 c sockets networking nonblocking blocking

关于将套接字设置为非阻塞模式,我已经读过这个.

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

这是我做的:

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;
}
Run Code Online (Sandbox Code Playgroud)

如何将套接字设置回阻止模式?我没有看到O_BLOCK标志?

谢谢.

小智 16

你有没有尝试清除O_NONBLOCK标志?

opts = opts & (~O_NONBLOCK)
Run Code Online (Sandbox Code Playgroud)


Ent*_*ops 6

这是一个更具跨平台能力的解决方案:

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;
}
Run Code Online (Sandbox Code Playgroud)