File descriptors and the files structure body

Source: Internet
Author: User
Tags function prototype
first, what is a file descriptor

Under Linux everything is file, for the kernel, all open files are referenced by file descriptor, the file descriptor is a non-negative integer, and when an existing file is opened or a new file is created, the kernel returns a file descriptor to the process. When reading and writing a file, use the Open or creat return file descriptor to mark the file, passing it as a parameter to read or write.

In Linux, a process accesses a file by means of a file descriptor (named descriptors FD), which is actually an integer. At the beginning of the program, there are three file descriptors by default: 0 (for standard input), 1 (for standard output), 2 (for standard errors). If you open a new file, its file descriptor is 3.

The scope of the file descriptor changes is 0~open_max-1. second, how to create a file descriptor

The most common way for a process to get a file descriptor is through the system function open or create, or it inherits from the parent process.
If you inherit from a parent process, the child process can access the files used by the parent process. We further think, the process is run independently, non-interference, if the parent-child process to communicate, it can be accessed through these files to start.

File descriptors are unique for each process, and each process has a file descriptor that manages the file descriptor. When you create a subprocess using fork, the child process obtains a copy of all the file descriptors of the parent process, which are opened when the fork is executed. The same replication process occurs when a process is copied or copied by the Fcntl, DUP, and dup2 subroutines. third, the relationship between file descriptor and open file

Each file descriptor corresponds to an open file, and different file descriptors point to the same file. The same file can be opened by a different process, or it can be opened multiple times in the same process. The system maintains a file descriptor table for each process, the value of which starts at 0, so the same file descriptor is seen in different processes, in which case the same file descriptor may point to the same file or point to a different file.
The kernel maintains three kinds of file descriptors:
1, process-level file descriptor table.
Each entry in a process-level file Description chart records information about a single file descriptor. The information in the table is: a set of flags that control the operation of the file descriptor, a reference to the open file handle. This process-level file descriptor is represented by the FILES_STRUCT structure, which has a pointer variable files of this structure type in the PCB.
The files_struct definition is as follows:

struct Files_struct {
atomic_t count;/* Share the number of processes in the table * *
rwlock_t file_lock;/* protect all domains below to prevent nesting in tsk->alloc_lock * /
int MAX_FDS/* Maximum number of current file objects/int max_fdset//
* Maximum number of current file descriptors/
    int next_fd;/* Assigned file description alphanumeric 1*/
struct file * * FD; /* A pointer to an array of file object pointers
/* fd_set *close_on_exec/* Point to the file descriptor that needs to be closed when exec () is executed/
fd_set *open_fds;/* pointer
to open file descriptor/* * Fd_set close_on_exec_init;/* The initial set of file descriptors that need to be closed when exec () is executed/
        fd_set open_fds_init;/* The initial set of the file descriptor/
struct files * fd_array[32];/* an initialization array of file object pointers
/};

2, System-level file descriptor table.
The kernel has a system-level file descriptor table for all open files. It is sometimes called open file descriptor tables, and the entries in the table are called Open file handles. An open file handle stores all the relevant information about the open file.
The following information is roughly included:
1. Current file offset
2. The status identification used when opening the file (flags parameter in open)
3. File access mode (read only, write only, read and write mode)
4, with the signal driver-related settings.
5, the I-node reference to the file.
6, file type and access rights.
7, a pointer to the list of locks held by the file.
8, the file's various attributes, including file size and different types of operation-related time stamps.
Related definition:

struct file
{
struct list_head f_list;//* All open files form a list
/struct dentry *f_dentry;/* pointers
to related directory entries/* struct Vfsmount *f_vfsmnt; /* Pointer to the VFS mount point
/struct file_operations *f_op/* Pointer to the file action sheet/
mode_t f_mode;/* File open Mode/
loff_t f_pos; * The current position of the file
/* unsigned short f_flags/* The flag specified when the file was opened/*
unsigned short f_count;/* The number of processes using the struct/
unsigned long f_ Reada, F_ramax, F_raend, F_ralen, F_rawin;
/* Pre-read flag, the maximum number of pages to read, the last pre-read file pointer, the number of prefetch bytes, and
the number of pre-read pages
/int f_owner;/* Transmit asynchronous I/O data via signal/
unsigned int f_uid, F_gid; /* User uid and gid*/
int f_error/* error code for network write/*

unsigned long f_version;/* version number/
void *private_data; * TTY Driver required *

/};

3, the File System I-node table.
Information about the file system is saved.

The important structure of struct inode── character device driver The
kernel uses the inode structure to represent the specific file, and the file structure represents the open filename descriptor. In the Linux2.6.27 kernel, the inode structure is defined as follows:
struct Inode {
struct hlist_node    i_hash;
struct List_head    i_list;
struct List_head    i_sb_list;
struct List_head    i_dentry;
unsigned long        I_ino;
atomic_t        I_count;
unsigned int        i_nlink;
uid_t            I_uid;
gid_t            I_gid;
 dev_t            I_rdev;   This member represents the INODE structure of the device file, which contains the true device number.
u64            i_version;
loff_t            i_size;
#ifdef __need_i_size_ordered
seqcount_t        i_size_seqcount;
}

The relationship between them (excerpt from the network):
iv. allocation of document descriptors

Allocation of file descriptors: When a user invokes a function such as open, creat, and so on, if successful, returns a file descriptor, which must be the least-used descriptor for the current process. However, to pay special attention to the maximum file descriptor, you can view the maximum file descriptor by command $ulimit–n, the general Linux distribution is 1024, of course, this value can be modified, you can refer to the file descriptor. Five, the input and output function based on the document descriptor

Next, I'll talk about the input and output functions based on the file descriptor:

Open: Opens a file and specifies how the file is accessed, and returns a file descriptor after the call succeeds.

Creat: Opens a file that, if it does not exist, creates it and returns a file descriptor after the call succeeds.

Close: The file is closed and the lock that the process adds to the file is freed.

READ: Reads data from a file that corresponds to a file descriptor, and returns the number of bytes read after the call succeeds.

Write: Writes data to a file that corresponds to a file descriptor, and returns the number of bytes written when the call succeeds.

Ftruncate: Shorten the file descriptor to the specified length and return 0 after the call succeeds.

Lseek: Sets the file pointer to the specified location in the file descriptor file, and returns the position of the new pointer when the call succeeds.

Fsync: Writes all the data in the written file to a disk or other underlying device, and returns 0 when the call succeeds.

Fstat: Returns information about the file that corresponds to the file descriptor, saves the result in struct stat, and returns 0 after the call succeeds.

Fchown: Changes the owner and all groups associated with the open file, and returns 0 after the call succeeds.

Fchmod: Changes the permission bit of the file that corresponds to the file descriptor to the specified octal mode, and returns 0 after the call succeeds.

Flock: Used to impose a recommended lock on the file corresponding to the file descriptor, which returns 0 after successful invocation.

FCNTL: Can be applied to the proposed lock can also impose mandatory locks, can establish record locks, read locks and write locks, the successful return of the call 0.

DUP: Copies the file descriptor, returning the smallest number in the unused file descriptor.

DUP2: The value of the returned file descriptor specified by the user to reopen or redirect a file descriptor.

Select: Read data from multiple file descriptors at the same time or write data to multiple file descriptors.

*1. Dup

Function prototype: int dup (int filefd)

function function: Copy an existing file descriptor FILEFD

*2. DUP2:

function prototypes: int dup2 (int oldfilefd, int newfield)

function function: Copy an existing file description oldfilefd, if Newfield equals OLDFILEFD, return Newfield If the two are not equal, if the Newfield is turned on, close Newfield first, then return to Newfield. FCNTL:

Function prototype: int fcntl (int filefd, int cmd, ...)

function function: Fcntl has 5 functions, it is decided by CMD of the second parameter. Here only one: Copy an existing file descriptor, cmd for F_DUPFD.

The function of the above three functions is to copy the file descriptor, remember that it is a file descriptor, not a copy of the file table, not a copy of the V node table. vi. differences between file descriptors and file pointers

File descriptor: When you open a file in a Linux system, you get a file descriptor, which is a very small positive integer. Each process holds a file descriptor in the PCB (Process Control block), which is the index of the table, and each table item has a pointer to the open file.
File pointers: Use a file pointer as a handle to I/O in the C language. The file pointer points to a data structure called the file structure in the process user area. The file structure includes a buffer and a file descriptor. The file descriptor is an index of the file descriptor, so in a sense the file pointer is the handle of the handle (on the Windows system, the file descriptor is called a file handle).

Article collated from:
http://blog.csdn.net/cywosp/article/details/38965239
http://blog.csdn.net/lf_2016/article/ details/54605651
http://blog.sina.com.cn/s/blog_7943319e01018m3w.html
http://www.cnblogs.com/hnrainll/ archive/2011/11/06/2237872.html
https://my.oschina.net/iuranus/blog/330397

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.