分别在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);
    }
}
相关推荐
望获linux1 小时前
【Linux基础知识系列】第一百一十篇 - 使用Nmap进行网络安全扫描
java·linux·开发语言·前端·数据库·信息可视化·php
Q741_1474 小时前
C++ 力扣 76.最小覆盖子串 题解 优选算法 滑动窗口 每日一题
c++·算法·leetcode·双指针·滑动窗口
花小璇学linux8 小时前
imx6ull-驱动开发篇42——Linux I2C 驱动框架简介
linux·驱动开发·嵌入式软件
凌肖战8 小时前
编写Linux下设备驱动时两种方案:内核态驱动开发和用户态驱动开发
linux·驱动开发
Rverdoser10 小时前
网站开发用什么语言好
服务器
Wy_编程10 小时前
VS中创建Linux项目
linux
luck_lin10 小时前
linux添加新硬盘挂载分区和数据迁移
linux·运维·分区扩容
四时久成11 小时前
服务器认证系统
运维·服务器
Univin11 小时前
8.25作业
数据结构·windows
Incredibuild11 小时前
DevSecOps 集成 CI/CD Pipeline:实用指南
c++·ci/cd·devsecops