LINUX (UNIX) file I/O Learning (i)

Source: Internet
Author: User

One, the file descriptor

  A file descriptor is an identity (non-negative, int) that is returned by the kernel to the appropriate process when a file is opened or created. The corresponding process can reference the identity to manipulate the file that is opened or created.

3 file descriptors are defined in Unistd.h:

Standard input Stdin_fileno 0

Standard output Stdout_fileno 1

Standard error Stderr_fileno 3

Second, open/create file

Open and create a file normally using the Open, creat function   

1#include <sys/types.h>2#include <sys/stat.h>3#include <fcntl.h>4 5 //Open a file6 intOpenConst Char*pathname,intflags); 7Returns: If the file descriptor succeeds, if the error is-18 //Create a file9 intOpenConst Char*pathname,intflags, mode_t mode); TenReturns: If the file descriptor succeeds, if the error is-1 One //create a file in a write-only manner A intCreat (Const Char*pathname, mode_t mode); -Returns: If the file descriptor succeeds, if the error is-1

The open function can be used for opening a file, and it can also be used to create a file, return a file descriptor, and the file descriptor must be the least current unused.

Pathname: The name of the file that will be opened or will be created

Flags: can be the result of a value or an operation (note: The first three can only be selected)

O_rdonly--Open a file in read-only mode

O_wronly--open files in a write-only manner

O_RDWR--open files in a readable and writable manner

O_append--Opens the file in the form appended to the end of the file

O_crear--Creates a file if it does not exist, and specifies the 3rd parameter mode

O_EXCL-If the o_creat is indicated at the same time, if the file is already present, the error will be created if it does not exist (detection and creation are bound together for atomic operation)

O_trunc--If this file is present and open for self-read or write-only, truncate its length to 0

O_noctty--if p a t h n a m e refers to an end device, the equipment is not assigned as the control terminal of this process.

    O_nonblock-if p a t h n a m e refers to an F I F O, a block special file, or a character special file, this option sets the non-blocking mode for this open operation and subsequent I/O operations for this file.

O_sync--Causes each w R i t e to wait until the physical I/O operation is complete.
O_sync--The selection is not p O S I X. 1 component, but S V guaranteed in a given descriptor

Mode

For the creat function, because the creat function is a write-only way to create a file,

creat (pathname, mode) equals open (Pathname, o_wronly | O_creat | O_trunc, Mode)

third, close the file

Close the file with the close function  

1 #include <unistd.h>23int close (int fd);

  You can close an open file by specifying the appropriate file descriptor

iv. Current file offset (for open files)

The open file has a current file location associated with the file, starting at that location when I/O operations are in progress. The Lseek is used to reposition the current position in the file (or to return the current file location).

Because the previous return type of Lseek and offset are all long types, the Lseek

1 #include <sys/types.h>2 #include <unistd.h>34 off_t lseek (int  int whence);

FD: Corresponding file descriptor

Offset: The amount of displacement relative to the whence in the file

Whence: Identifies a specific location in the file with 3 values

Seek_set: Refers to the beginning of a file

Seek_cur: Refers to the location of the current file

Seek_end: Refers to the end of a file

Lseek (FD, 0, seek_cur) is used to return the current position of the file.

For the file that is just opened, returns 0, when opened in O_append, returns nonzero for the end of the file.

If the current amount of displacement modified with the Lseek function exceeds the current length of the file, the file will form a file hole, and the file hole will not occupy disk space, but when the file is read, the file hole is read as 0.

v. I/O operations

 I/O operations include read and write operations to the file, so the Read,write function is used

1 #include <unistd.h>23 ssize_t read (intvoid *buf, size_t count); 4 5 ssize_t write (intconstvoid *buf, size_t count);

FD: File descriptor for the corresponding file

BUF: Read/write buffers

Count: On read, the number of bytes to read, to write, the size of buf  

To read:  

When a normal file is read, it reaches the end of the file before it is read to the required number of bytes. For example, if you have 3 bytes before reaching the end of the file and require a read of 10 bytes, read returns 3 and the next time you call re ad, it will return 0 (end of file ). That is, when the end of the file is read, the last read must return 0.

  When reading from an end device, it is usually read one line at a time.
When reading from the network, the buffer mechanism in the network may cause the return value to be less than the number of bytes required to read.
Some record-oriented devices, such as tapes, return at most one record at a time.

To write:

Write error Reason:

1. Disk full

2. The file length limit is exceeded

Changes the current displacement of the file after Write,read

vi. 3 file-related data structures in the kernel

The information about this file is maintained in the operating system kernel, and their relationship is as follows:

Operating system for the maintenance process, set up a process table, each process in the process table is a separate record entry

Each process maintains an open file, sets a file descriptor Table (1), and does not have a single file descriptor that occupies one record in it, and a record consists of two items:

1. File Descriptor Flags

2. Pointers to File tables

3 items are also included in the file table

1. File status Flag (O_rdonly | O_wronly ... )

2. Current displacement of the file (see Iv. Current displacement of the file )

3. Pointer to v node (V-node, virtual file system for file)

The information that the V-node includes

Information for 1.V nodes

Information for 2.I nodes

3. Length of File

When two separate processes open the same file, they each get a file descriptor table, a file sheet, but the V node pointer in the file table points to the same V node.

At this point, when a file is read, two processes are irrelevant, because two processes have a separate file table (containing the current amount of displacement of a file, which belongs to the current process only). When the file is written, there may be a problem, for example, when the file is opened two processes (A, b) of the current displacement of the file is set to 0, at which time process A first write to the file as 1000 bytes, after writing, change the current displacement of the file is 1000, and the length of the file is 1000, At this point, process B writes to the file (note that at this point the current displacement of the file for the B process does not change or 0), at which time the B process writes 1000 bytes and then overwrites the a process write, resulting in a write overwrite.

Of course, this problem can be solved, as long as the open file to add O_append can be resolved, Because this flag specifies the two operations (1. Set the file current offset of the files table to the end of the file 2. Write to file) as an atomic operation, that is, each time the file is written, the current displacement of the file is modified to be the end of the file. This is an example of a process file share.

In addition, atomic manipulation refers to the operation of multiple steps as a step, either full or not.

Vii. Changing the nature of open files

The nature of the variant is to be used fcntl, or dup,dup2) (Fcntl can replace dup,dup2)

1 #include <unistd.h>2 #include <fcntl.h>34int fcntl (  intint/* */);

FD: Corresponding file descriptor

CMD: The function used to determine the FCNTL can be the following value

F_DUPFD: Copying file descriptors

F_GETFD/F_SETFD: Get/Set File descriptor flag

F_GETFL/F_SETFL: Get/Set file status flag

There are others, but first of all, learn these.

...: In Ansci C, more parameters can be added

Features of the FCNTL:

As CMD is listed, a flag represents a function

1. Copying file descriptors

The copy descriptor can be used with dup,dup2,fcntl.

After copying the file descriptor, the new file descriptor and the original file descriptor share a file table, but each has a file descriptor

1 #include <unistd.h>23int dup (int  OLDFD); 4 int dup2 (intint newfd);

NEWFD = DUP (OLDEFD); Equivalent to NEWFD = Fcntl (OLDFD, F_DUPFD);

Dup2 (OLDFD, NEWFD);

Close (NEWFD);

Fcntl (OLDFD, F_DUPFD, NEWFD);

It's just dup2 for the atomic operation.

The dup2 action is that the NEWFD is developed as a new file descriptor, and if NEWFD is already open, it is first closed on replication.

2. Get/Set File descriptor flag (currently only has a flag bit close_on_exec) and fd_cloexec

When you copy a file descriptor with DUP,DUP2,FCNTL, the value is cleared.

Setting F_GETFD Gets the value of Fd_cloexec (returned as a function return value)

Setting F_SETFD will ... The value of the parameter is set to the FD_CLOEXEC bit (using the 3rd parameter)

3. Get/Set File status flag

Setting F_GERFL returns the status flag of a file as a function return value

Since O_rdonly,o_wronly,o_rdwr can only set one, the return value and the O_accmode phase are first judged to be the 3 value of which

and other signs that don't need

Setting F_SETFL assigns the value of the third parameter of a function to the status flag of the file

LINUX (UNIX) file I/O Learning (i)

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.