fcntl----file control 文件控制,用来改变打开文件的性质。
在网络编程中使用改变fd的阻塞/非阻塞状态
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd, ... ); //第3个参数的有无取决于cmd的值
返回值:若成功则取决于cmd,
若出错则均返回-1
1、开启非阻塞I/O
int func()
{
int fd = socket(AF_INET, SOCK_STREAM, 0);
int flag = fcntl(fd,F_GETFL,0);//获取文件fd当前的状态
//int flag = fcntl(fd,F_GETFL);//不用第3个参数也可以
if(flag<0)
{
perror("fcntl F_GETFL fail");
close(fd);
return -1;
}
if (fcntl(fd, F_SETFL, flag | O_NONBLOCK) < 0)//设置为非阻塞态
{
perror("fcntl F_SETFL fail");
close(fd);
return -1;
}
}
2、关闭非阻塞I/O,设置为阻塞态
int func()
{
int fd = socket(AF_INET, SOCK_STREAM, 0);
int flag = fcntl(fd,F_GETFL,0);//获取文件fd当前的状态
if(flag<0)
{
perror("fcntl F_GETFL fail");
close(fd);
return -1;
}
flag = flag&~O_NONBLOCK;
//flag &= ~O_NONBLOCK;//等同于上行
if (fcntl(fd, F_SETFL, flag) < 0)//设置为阻塞态
{
perror("fcntl F_SETFL fail");
close(fd);
return -1;
}
}