


How to call the underlying system of Linux operating files
The Linux operating system pursues the concept that everything is a file. Almost all file devices can be operated with a set of system calls, namely open()/close()/write()/read(), etc. System calls are similar to C library calls in operating files. The man manual that comes with Linux is the most authoritative. Check the system call usage by checking the man manual.
Code name—— Meaning
- ##1 —— Commands that users can operate/execute in the shell environment
- 2 —— Functions and tools that can be called by the system kernel
- 3 —— Some commonly used functions and function libraries, mostly Part of the function library of C
- 4 —— Description of the device file, usually the device under /dev
- 5 — — Configuration files or formats of certain files ##6 —— Games
- 7 —— Management and protocols, etc., For example, Linux file system, network protocols, etc.
- ##8 —— Commands available to system administrators
- 9 —— With Kernel Relevant files
- Note that system header files are generally stored in the /usr/include
open()——Open or create a file
Return Value type:
Failure: -1
- Success: >= 0, which is the file descriptor;
- mode_t is a type alias, which is actually a signed integer. For the open function, the third parameter is only used when creating a new file
- flag: open Flags
Note:
|” to form multiple flag parameters can also be used together with the following method:
write()
Return value:
If successful, it has been written The number of bytes entered;
If an error occurs, it is -1;
Note: The number of bytes planned to be written and the return value of the function When not equal, it means there is an error in writing, which can be used to check whether the writing is successful;
fd
- : File descriptor for writing files;
-
buf : Cache for storing data to be written; -
count : The number of bytes required to write data once; -
Note:
For ordinary files, write The operation starts from the current offset of the file. If the O_APPEND option is specified when opening the file, the file offset is set to the current end of the file before each write operation. After a successful write, the file offset is increased by the number of bytes actually written. read()
Return value: Number of bytes read
If the end of the file has been reached, it is 0; if there is an error, it is -1;
- Parameters
fd
- : File descriptor for reading files;
-
buf : Cache for storing read data; -
count : The number of bytes required to read data once; note that the return value is the actual number of bytes read, and they are not the same; -
Note: The reading operation starts from the
. Before successfully returning, the displacement is increased by the number of bytes actually read (this displacement can be set by yourself); close()
Note: When a process terminates, all files it opens are automatically closed by the kernel.
Note: These functions without caching are system calls provided by the kernel; this is exactly the same as the IO we learned in C language Operations differ in that they are not part of standard C, but are part of POSIX.
When standard C operates on files, it operates on the structure pointer of FILE, and the file descriptor is used here.
The range of file descriptors is 0-OPEN MAX. The upper limit adopted by early Unix was 19 (that is, each process is allowed to open 20 files). Now many systems will soon increase to 63. Linux is 1024, the specific number can be found in the header file of
##File descriptor and file pointer
- FILE * fdopen(int fd,const char *mode), convert the file descriptor into a file pointer;
- int fileno(FILE *stream), convert the file pointer into a file descriptor;
Function: Locate an open file
off_t lseek(int fd,off_t offset,int whence);
fd
: File descriptor that has been opened;
offset
: Displacement amount;
whence
: Positioning position, that is, the reference point
SEEK_SET
: Set the displacement of the file to offset bytes from the beginning of the file;
SEEK_CUR
: Set the displacement of the file to its current value plus offset. The offset can be positive or negative;
-
SEEK_END
: Set the displacement of the file to the file length plus offset. The offset can be positive or negative (if it is a positive value at this time, it involves a hole file, please see the explanation below);
- Return value: **If successful, return the new file displacement (absolute displacement) **If an error occurs, it is -1; when the end of the file is positioned, the size of the file can be returned;
- The lseek function can also be used to determine whether the file involved can set the displacement. If the file descriptor refers to a pipe or FIFO, lseek returns -1 and errno Set to EPLPE;
Hole file example:
#include<stdio.h> #include<fcntl.h> #include<string.h> #include<stdlib.h> #include<unistd.h> #include<errno.h> //生成空洞文件 char *buffer = "0123456789"; int main(int argc,char *argv[]) { if(argc < 2) { fprintf(stderr,"-usage:%s [file]\n",argv[0]); exit(1); } int fd = open(argv[1],O_WRONLY | O_CREATE | O_TRUNC,0777); if(fd < 0) { perror("open error"); exit(1); } size_t size = strlen(buffer) * sizeof(char); //将字符串写入到空洞文件中 if(write(fd,buffer,size) != size) { perror("write error"); exit(1); } //定位到文件尾部的10个字节处 if(lseek(fd,10L;SEERK_END) < 0) { perror("lseek error"); exit(1); } //从文件尾部的10个字节处再写入字符串 if(write(fd,buffer,size) != size) { perror("write error"); exit(1); } close(fd); return 0; }
Example:
file table on the internal PCB of the system , the file descriptor opened by recording is actually the subscript of the file table
- #0——FILE* stdin, standard input
- 1——FILE* stdout, standard output
- 3——FILE* stderr, standard error output
- This program has opened three files by default, fd is ranked fourth, so the number is 3
The running results are as follows:
Application: Copy files using reading and writing
First Statement: We do not distinguish between text files and binary files
To complete the copy of an image, we can use the following solution:
- Open the original binary file first
Open a new file
Read part of the original binary file and write it to the new file
Read and write repeatedly
Until reading is finished, stop after writing [read() == 0 is used as the condition for loop stop, if it cannot be read, it is finished]
Copying completed
Copying completed
After opening the file, Can the child process of fork share access to the same file as the parent process?
Every time we open a file, a structure such as struct file will be generated in the kernel to represent the open file and record the following information:
File offset (starts from 0, the file pointer offsets as data is written)
Reference count (several processes are using this Open file)
inode node (stores the attribute information of the process: who created it, what is the name, and where is it stored on the disk. Through this inode node, we can find the corresponding specific file)
Opening method: For example, read-only mode, write-only mode open
Test 1: Open the file first and then fork
close (fd) is written on the outermost side, and both the parent and child processes will be closed. Each time they are closed, the reference count will be decremented by 1 until it reaches 0.
The running results are as follows:
The reasons are as follows:
Test 2: First fork and then open the file
After modifying the code, the running results change as follows:
Because the parent and child processes opened their own files after they were separated, Their own struct files are generated, and file offsets are no longer shared.
In actual application scenarios, we mostly use files opened by the parent process and child processes to access this form.
The above is the detailed content of How to call the underlying system of Linux operating files. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

Troubleshooting steps for failed Docker image build: Check Dockerfile syntax and dependency version. Check if the build context contains the required source code and dependencies. View the build log for error details. Use the --target option to build a hierarchical phase to identify failure points. Make sure to use the latest version of Docker engine. Build the image with --t [image-name]:debug mode to debug the problem. Check disk space and make sure it is sufficient. Disable SELinux to prevent interference with the build process. Ask community platforms for help, provide Dockerfiles and build log descriptions for more specific suggestions.

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.
