- Input and output are the process of replicating data between main memory and external devices.
Input is the replication of data from I/O devices to main memory, and output is the replication of data from main memory to I/O devices.
- linuxThe file is a sequence of M bytes, all I/O devices are modeled as files, and all inputs and outputs are read and written as corresponding files.
- Open the file. An application declares that it wants to access an I/O device by requiring the kernel to open the corresponding file.
- Linux shellEach process created starts with three open files: standard input (descriptor 0), standard output (descriptor 1), and standard error (descriptor 2).
- Change the file location of the current file. For each open file, the kernel maintains a file location k, initially 0. This file location is a byte offset from the beginning of the file.
- Read and write files: A read operation is to copy n> from a file; 0 bytes to memory. Writing is copying n> from memory; 0 bytes to a file.
Close the file: When the application has finished accessing the file, it notifies the kernel to close the file. In response, the kernel releases the data structure created when the file is opened and restores the descriptor to the available descriptor pool.
Each Linux file has a type to represent its role in the system:
- Ordinary file: Contains arbitrary data. Applications are divided into text files and binary files.
- Directory: A file that contains a set of links.
Socket: A file used to communicate across networks with another process.
Open or Close Files
- O_WRONLY：Write only
- O_CREAT：If the file does not exist, create a truncated (empty) file for it
- O_TRUNC：If the file already exists, truncate it
O_APPEND：Before each write, set the file location to the end of the file
Read and Write Files
ssize_t read(int fd,void *buf,size_t n); ssize_t write(int fd,const void *buf,size_t n);