文章目录
  1. fcntl函数

fcntl函数

fcntl函数提供对文件描述符的各种控制操作。

1
2
3
4
5
6
/*
引用方式: #include <fcntl.h>
cmd: 指定执行哪种类型的操作
返回值根据操作与arg的不同而不同, 若失败返回-1并设置errno
*/
int fcntl(int fd, int cmd,...);

根据操作类型的不同,fcntl函数可能还需要第三个可选参数arg。fcntl函数支持的常用操作及其参数见下表。

 

在网络编程中,fcntl函数通常用来将一个文件描述符设置为非阻塞的。基本框架如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
int setnonblocking( int fd ){
int old_option, new_option;
if((old_option=fcntl( fd, F_GETFL ))<0){
printf("fcntl error: %s\n", strerror(errno));
return -1;
}
new_option = old_option | O_NONBLOCK;
if((fcntl( fd, F_SETFL, new_option ))<0){
printf("fcntl error: %s\n", strerror(errno));
return -1;
}
return old_option;
}