分别在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);
    }
}
相关推荐
IT大白鼠13 小时前
彭大帅的AI运维助手第 10 篇——K8s 集群探针升级记:从服务级到业务级
运维·kubernetes·aiops·彭大帅
多弗朗皮卡丘16 小时前
网络基础:数据链路层与其他协议或技术
linux·网络·tcp/ip
考虑考虑19 小时前
nginx拦截url
运维·后端·nginx
南风841119 小时前
C++ 四种强制类型转换详解
c++
微笑星河q20 小时前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
速捷工控 PLC触摸屏还原程序20 小时前
欧姆龙NB上传密码忘了,换屏前怎么保留原程序?
运维·服务器·欧姆龙
xx z21 小时前
directx修复工具下载(DirectX Repair 增强版 使用说明)
windows·系统·工具·软件
方便面不加香菜21 小时前
Docker Volume -- 对照总结及综合实战案例操作演示
运维·docker·容器
爱勇宝21 小时前
SSL 证书别再手动续了:acme.sh + Let's Encrypt + 云厂商 DNS 全自动实战
运维·服务器