分别在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);
    }
}
相关推荐
忆挽篱笙歌4 小时前
通信连接,匿名管道
linux·服务器·网络
码客-ygluu6 小时前
X3 LUA 异步分布式微服务集群框架
c++·架构·lua
无足鸟ICT7 小时前
【RHCA+】安装Tuned
linux·服务器·centos
九英里路9 小时前
protobuf快速上手
网络·c++·中间件·json·谷歌·序列化·protobuf
纪念 22910 小时前
C++ 算法基础 (差分)
开发语言·c++·算法
Decay__11 小时前
VMware 安装 SQL Server 双节点 AlwaysOn 可用性组教程 —— WSFC、AG 与侦听器完整部署(系列核心篇)
运维·数据库·sql·mysql·架构
测试界的小码农11 小时前
【Linux 命令实战(06):Linux 文件权限管理,掌握 chmod、chown、chgrp】
linux·运维·服务器
艺杯羹12 小时前
1Panel 装好后 ufw 仍是 inactive:一次服务器安全盲区复盘
服务器·数据库·安全·网络安全·系统架构·实战·1panel
陈希12313 小时前
负载均衡与高可用:LVS、HAProxy、Keepalived 实战
运维·负载均衡·lvs
一条破秋裤13 小时前
【1114】【并发控制】【笔记】
linux