fcntl----file control 文件控制,用来改变打开文件的性质。
在网络编程中使用改变fd的阻塞/非阻塞状态
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd, ... /* arg */ );
返回值:若成功则取决于cmd,若出错则返回-1
1、开启非阻塞I/O
int func()
{
int flag = fcntl(fd,F_GETFL,0);//获取文件fd当前的状态
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 flag = fcntl(fd,F_GETFL,0);//获取文件fd当前的状态
if(flag<0)
{
perror("fcntl F_GETFL fail");
close(fd);
return -1;
}
flag = &~O_NONBLOCK;
if (fcntl(fd, F_SETFL, flag) < 0)//设置为阻塞态
{
perror("fcntl F_SETFL fail");
close(fd);
return -1;
}
}