About Linux file I/o detailed

Source: Internet
Author: User
Tags constant data structures strlen

Most file I/O in a Linux system uses only 5 functions: Open,read,write,lseek and close. The functions covered in this topic are called I/O with no buffering, and without buffering, read or read are implemented through a system call to the kernel, which is part of the POSIX.1 and single UNIX specification. We will further discuss file sharing among multiple processes and the kernel data structures involved.

File descriptor
A file descriptor is a non-negative integer that, when used with open or create, returns a file descriptor identifying the file, which can be passed as a parameter to read or write use. File descriptor 0 (symbolic constant: Stdin_fileno) is associated with the standard input of the process, and file descriptor 1 (symbolic constant: Stdout_fileno) is associated with the standard output of the process, file descriptor 2 (symbolic constant: stderr_ Fileno) is associated with the standard output of a process, which is defined in <unistd.h>. The scope of the file descriptor is that the value of the 0~open_max,open_max can be called sysconf (_sc_open_max) by a function, and the following is an example:

#include <stdio.h>

#include <unistd.h>

Int

Main (void)

{

Long Open_max = sysconf (_sc_open_max);

printf ("%dn", Open_max);

return 0;

}

Output: 1024

Open function
#include <fcntl.h>

int open (const char* pathname, int oflag, .../* mode_t mode *);

Use one or more of the following constants for the "or" operation to constitute the Oflag parameter (these constants are defined in <fcntl.h>):

O_rdonly,o_wronly,o_rdwr these three constants must and can only be specified one.

The following constants can select one or more:

O_append append at end of file

O_creat If this file does not exist, it is created. When you use this option, you use the mode parameter to set the access rights for the new file.

O_EXCL test whether a file exists.

O_trunc If the file is successfully opened, its length is truncated to 0.

O_noctty If the pathname parameter refers to a terminal device, it is not used as the control terminal for this process.

O_nonblock If pathname refers to a FIFO, block special file or character special file, this option sets the non-blocking mode for this open operation of the file and for subsequent I/O operations.

NOTE: * non-blocking mode: When I/O operation cannot complete, the call immediately fails and returns, rather than waiting forever.

O_dsync causes all write operations for the file to wait until all I/O to the file is complete, but do not wait for the file properties to be updated if the write operation does not affect reading the data that was just written.

O_rsync makes all the read operations of the file wait until all write operations on the file are complete.

O_sync causes all write operations for the file to wait until all I/O to the file is complete.

Note: *linux2.4.22 O_dsync and O_rsync are processed to be the same as O_sync, where the data and properties of the files are always updated synchronously.

Close function
#include <unistd.h>

int close (int file_des);

When you close a file, all the record locks on the file are freed. When the process terminates, the kernel automatically closes all the files it opens, but it is more secure to call the close function explicitly.

Lseek function
#include <unistd.h>

off_t lseek (int file_des, off_t offset, int whence);

Whence value:

Seek_set sets the read/write offset of the file to the offset byte from the first paragraph of the file.

Seek_cur sets the read-write offset of the file to the current value plus offset bytes, which can be positive or negative.

Seek_end sets the read/write offset of the file to the offset byte at the end of the file, offset to positive or negative.

Returns a new file offset on success and returns 1 when it fails. The return value allows you to test whether a file descriptor can set a read-write offset (pipe, FIFO, and network sockets cannot set an offset). When the read-write offset is greater than the length of the file, the write operation will form a void in the file, and the void is read as 0, but the hole does not occupy disk space and is handled in relation to the implementation of the file system. The following program creates an empty file:

#include <unistd.h>

#include <stdlib.h>

#include <stdio.h>

#include <fcntl.h>

#include <string.h>

Char buf[] = "1234567890";

Char buf2[] = "ABCDEFGHIJ";

Int

Main (void)

{

Remove ("File.hole");

int file_des = open ("File.hole", o_rdwr| O_creat| O_EXCL, s_irusr| s_iwusr| S_IXUSR);

if (file_des = = 1)

{

Write (Stdout_fileno, "OPEN FILE error!n", 20);

Exit (0);

}

if (Lseek (File_des, 5, seek_set) = = 1)

{

Write (Stdout_fileno, "Error!n", 20);

Exit (0);

}

size_t write_bytes = Write (File_des, buf, strlen (BUF));

if (Write_bytes < strlen (BUF))

{

Write (Stdout_fileno, "Error!n", 20);

Exit (0);

}

if (Lseek (File_des, 5, seek_end) = = 1)

{

Write (Stdout_fileno, "SECOND seek Error!n", 20);

Exit (0);

}

Write_bytes = Write (File_des, Buf2, strlen (BUF));

if (Write_bytes < strlen (BUF2))

{

Write (Stdout_fileno, "SECOND write error!", 20);

Exit (0);

}

Close (file_des);

return 0;

}

To view the contents of a file file.hole using the command od:

[Root@localhost cc++]# od-c File.hole

0000000 1 2 3 4 5 6 7 8 9 0

0000020 a b c d e F g h i J

As you can see, there's a hole in the beginning of the file, and a hole in the middle is read as 0.

Read and Write functions:
#include <unistd.h>

ssize_t Read (int file_des, void *buf, size_t nbytes);

Return value: Returns the number of bytes read successfully, and returns 1 if 0 is returned at the end of the file.

ssize_t write (int file_des, const void *size_t, size_t nbytes);

Return value: Successfully returns the number of bytes written, error returns-1.

Pread and Pwrite functions:
#include <unistd.h>

ssize_t pread (int file_des, void *buf, size_t nbytes, off_t off_set);

ssize_t pwrite (int file_des, const void *buf, size_t nbytes, off_t off_set);

Note: The *pread and Pwrite functions make Lseek and read/write operations an atomic operation, and the important difference between Pread/pwrite and Lseek/read/write is:

The location and read (write) operations cannot be interrupted when the pread/pwrite is invoked;

Pread/pwrite cannot update the file pointer, you can use the Ftell or Fgetpos function to get the current read-write location.

DUP and DUP2 functions:
#include <unistd.h>

int dup (int file_des);

int dup2 (int file_des, int file_des2);

Both DUP and dup2 are used to copy an existing file descriptor, successfully returning a new file descriptor, and error returning-1, the difference being:

DUP must return the currently available minimum file descriptor;

DUP2 specifies that the parameter file_des2 be a new file descriptor, and when File_des2 is opened, it is closed, and if file_des and file_des2 are equal, return file_des2 without closing it.

Note: The *FCNTL function can also copy the file descriptor, which will be described later.

Sync,fsync and Fdatasync functions:
#include <unistd.h>

int sync (void);

int fsync (int file_des);

int fdatasync (int file_des);

The above functions are used to ensure consistency between physical files and cached data. The difference is that sync simply queues all modified block buffers into the write queue, and does not wait for the completion of the write disk operation to return; Fsync is only for a single file pointed to by a file descriptor, and waits for the write disk operation to complete and then return. But it only affects the data portion of the file; Fdatasync and Fsync are similar, but in addition to the data, Fdatasync also synchronizes the properties of the updated file.

Fcntl function:
#include <fcntl.h>

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

The FCNTL function can change the nature of the file that is already open.

CMD parameter values (a total of 10, here first the first 7):

F_DUPFD copies the file descriptor Files_des, and the new file descriptor is returned as a function return value. The new descriptor has its own file descriptor flag, and its fd_cloexec file descriptor flag is cleared.

F_GETFD corresponds to the Files_des file descriptor flag as a function value, and currently defines only a file descriptor flag fd_cloexec.

F_SETFD for Files_des Set file descriptor flags, the new flag value is set by the third parameter.

The F_GETFL corresponds to the Files_des file status flag as the function value returns. The file status flag is already indicated in the open function.

F_SETFL sets the file status flag to the value of the third parameter. The flags that can be changed are: O_append,o_nonblock,o_sync,o_dsync,o_rsync,o_fsync,0_async.

F_getown the process ID or process rent ID of the current receiving Sigio and Sigurg signals.

F_setown sets the process ID or process rent ID for receiving Sigio and Sigurg signals. The positive arg parameter represents a process ID, and the negative arg parameter represents the process rent ID that equals the absolute value of ARG.

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.