linux下将文件描述符设为非阻塞

52 阅读1分钟

1:首先获得文件描述符的标志状态(以sockfd举例):\

  int old_option=fcntl(sockfd,F_GETFD)  //获取标志状态

2:将标志状态设为非阻塞标志:
int new_option = old_option | O_NOBLOCK
O_NOBLOCK是一个十六进制整数,其值为4: image.png 通过按位与将old_option倒数第三位值设置为1,以下代码运行可以看出:\

std::cout<<std::bitset<sizeof(old_optipn)*8>(old_optipn)<<std::endl;
int new_option = old_optipn | O_NONBLOCK;
std::cout<<std::bitset<sizeof(O_NONBLOCK)*8>(O_NONBLOCK)<<std::endl;
std::cout<<std::bitset<sizeof(new_option)*8>(new_option)<<std::endl;`

image.png
3:设置文件的状态标志: fcntl(sockfd,F_SETFL,new_option)