0%

fcntl函数

fcntl函数

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

1
2
3
4
#include <unistd.h>
#include <fcntl.h>

int fcntl(int fd, int cmd, ... /* arg */ );

fd参数是被操作的文件描述符,cmd参数指定执行何种类型的操作。根据操作类型的不同,该函数可能还需要第三个可选参数 argfcntl函数支持的常用操作及其参数如下表所示。

image-20220816114524640

fcntl函数成功时的返回值如表中最后一列所示,失败则返回-1并设置errno

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

比如:终端文件默认是阻塞读的,这里用 fcntl 将其更改为非阻塞读

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MSG_TRY "try again\n"

int main(void)
{
char buf[10];
int flags, n;

flags = fcntl(STDIN_FILENO, F_GETFL); //获取stdin属性信息
if (flags == -1)
{
perror("fcntl error");
exit(1);
}
flags |= O_NONBLOCK;
int ret = fcntl(STDIN_FILENO, F_SETFL, flags);
if (ret == -1)
{
perror("fcntl error");
exit(1);
}

while (true)
{
n = read(STDIN_FILENO, buf, 10);
if (n < 0)
{
if (errno != EAGAIN)
{
perror("read /dev/tty");
exit(1);
}
sleep(3);
write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));
continue;
}
write(STDOUT_FILENO, buf, n);
}

return 0;
}

image-20220816115555375