Everything in the Linux system is a file, and we want to operate a file through the file descriptor fd (handle).
Different file descriptors naturally have different attributes, and the same file descriptor attributes can also be modified.
There are two ways to set the file descriptor attribute, one is to use the open function to open the file , and specify the read and write attributes of the file descriptor by specifying the parameters of the open function. Another way is to set it through the fcntl function .
1. Open function setting
The prototype of the open function is as follows:
int open(char *pathname,int access[,int permiss])
The function returns a file descriptor fd, and the attribute of fd can be set by specifying access. Common attributes are as follows:
access |
meaning |
O_RDONLY |
read file |
O_WRONLY |
write file |
O_RDWR |
read and write files |
O_APPEND |
Read and write files, but write at the end each time |
O_CREATE |
If the file does not exist, create a new file |
O_BINARY |
open file as binary |
2. fcntl function setting
View the fcntl function prototype through the man manual:
NAME
fcntl - manipulate file descriptor
SYNOPSIS
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd, ... /* arg */ );
This function can get or set the attributes of the file descriptor. This is specified by the parameter cmd.
When cmd is F_GETFL, it means to obtain the attributes of the file descriptor, and the third parameter is not used at this time
When cmd is F_SETFL, it means setting the attributes of the file descriptor. At this time, the third parameter specifies the attributes to be set
return value:
Failed: -1
Success: F_GETFL returns the obtained file descriptor attribute, and F_SETFL returns a value of 0
The basic usage is:
int flags; //保存属性
flags = fcntl(0, F_GETFL); // 1、获取属性
//2、在原属性基础上修改
flags |= O_NONBLOCK;
//3.修改的属性再设置回去
fcntl(0, F_SETFL, flags);