分别在linux和windows上设置socket为阻塞模式

在 Linux 和 Windows 系统中,都可以将 socket 设置为非阻塞模式。

Linux平台

  • 在 Linux 系统中,可以使用 fcntl 函数来设置 socket 为非阻塞模式。例如:

    int flags = fcntl(socket_fd, F_GETFL, 0);
    fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK);

  • 此外,Linux 还提供了一个 accept4 函数,可以直接将返回的 socket 设置为非阻塞模式:

    int client_fd = accept4(server_fd, (struct sockaddr *)&client_addr, &client_addr_len, SOCK_NONBLOCK);

  • 设置阻塞模式,默认阻塞模式不用单独设置

    int flags = fcntl(socket_fd, F_GETFL, 0);
    fcntl(socket_fd, F_SETFL, flags | ~O_NONBLOCK);

Windows平台

  • 在 Windows 系统中,可以使用 ioctlsocket 函数来设置 socket 为非阻塞模式。例如:

    u_long mode = 1;
    ioctlsocket(socket_fd, FIONBIO, &mode);

  • 设置阻塞模式

    u_long mode = 0;
    ioctlsocket(socket_fd, FIONBIO, &mode);

封窗两个函数方便调用

设置非阻塞模式

void SetNonBlocking(SOCKET sockfd)

设置阻塞模式

void SetBlocking(SOCKET sockfd)

复制代码
#ifdef __GNUC__
#define SOCKET int
#elif defined(_WIN32)
#endif


void SetNonBlocking(SOCKET sockfd){
#ifdef _WIN32
    unsigned long flag = 1;
    if(ioctlsocket(sockfd, FIONBIO, &flag) == SOCKET_ERROR){
#else
    int cflags = fcntl(sockfd, F_GETFL, 0); 
    if(fcntl(sockfd, F_SETFL, cflags | O_NONBLOCK) == -1){
#endif
        std::cerr << "ioctlsocket or fcntl set non blocking error" << std::endl;
        exit(-1);
    }
}

void SetBlocking(SOCKET fd){
#ifdef _WIN32
    unsigned long flag = 0;
    if(ioctlsocket(sockfd, FIONBIO, &flag) == SOCKET_ERROR){
#else
    int cflags = fcntl(sockfd, F_GETFL, 0); 
    if(fcntl(sockfd, F_SETFL, cflags & ~O_NONBLOCK) == -1){
#endif
        std::cerr << "ioctlsocket or fcntl set non blocking error" << std::endl;
        exit(-1);
    }
}
相关推荐
A小辣椒20 小时前
TShark:Wireshark CLI 功能
linux
A小辣椒1 天前
TShark:基础知识
linux
AlfredZhao1 天前
OCI 明明分配了 200G 系统盘,为什么 df 只看到 30G?
linux·oci
AlfredZhao2 天前
vi 删除指定范围的行,不用再反复按 dd
linux·vi
clint4562 天前
C++进阶(1)——前景提要
c++
用户9718356334662 天前
银河麒麟 KY10 申威(SW64) 安装 nginx-1.16.1-2.p01.ky10.sw_64.rpm 详细步骤
linux
夜悊2 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴2 天前
CMake 021: IF 条件判据详诠
c++·cmake
猪脚踏浪2 天前
linux 拷贝文件或目录到指定的位置
linux
_wyt0013 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp