


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!

Linux maintenance mode can be entered through the GRUB menu. The specific steps are: 1) Select the kernel in the GRUB menu and press 'e' to edit, 2) Add 'single' or '1' at the end of the 'linux' line, 3) Press Ctrl X to start. Maintenance mode provides a secure environment for tasks such as system repair, password reset and system upgrade.

The steps to enter Linux recovery mode are: 1. Restart the system and press the specific key to enter the GRUB menu; 2. Select the option with (recoverymode); 3. Select the operation in the recovery mode menu, such as fsck or root. Recovery mode allows you to start the system in single-user mode, perform file system checks and repairs, edit configuration files, and other operations to help solve system problems.

The core components of Linux include the kernel, file system, shell and common tools. 1. The kernel manages hardware resources and provides basic services. 2. The file system organizes and stores data. 3. Shell is the interface for users to interact with the system. 4. Common tools help complete daily tasks.

The basic structure of Linux includes the kernel, file system, and shell. 1) Kernel management hardware resources and use uname-r to view the version. 2) The EXT4 file system supports large files and logs and is created using mkfs.ext4. 3) Shell provides command line interaction such as Bash, and lists files using ls-l.

The key steps in Linux system management and maintenance include: 1) Master the basic knowledge, such as file system structure and user management; 2) Carry out system monitoring and resource management, use top, htop and other tools; 3) Use system logs to troubleshoot, use journalctl and other tools; 4) Write automated scripts and task scheduling, use cron tools; 5) implement security management and protection, configure firewalls through iptables; 6) Carry out performance optimization and best practices, adjust kernel parameters and develop good habits.

Linux maintenance mode is entered by adding init=/bin/bash or single parameters at startup. 1. Enter maintenance mode: Edit the GRUB menu and add startup parameters. 2. Remount the file system to read and write mode: mount-oremount,rw/. 3. Repair the file system: Use the fsck command, such as fsck/dev/sda1. 4. Back up the data and operate with caution to avoid data loss.

This article discusses how to improve Hadoop data processing efficiency on Debian systems. Optimization strategies cover hardware upgrades, operating system parameter adjustments, Hadoop configuration modifications, and the use of efficient algorithms and tools. 1. Hardware resource strengthening ensures that all nodes have consistent hardware configurations, especially paying attention to CPU, memory and network equipment performance. Choosing high-performance hardware components is essential to improve overall processing speed. 2. Operating system tunes file descriptors and network connections: Modify the /etc/security/limits.conf file to increase the upper limit of file descriptors and network connections allowed to be opened at the same time by the system. JVM parameter adjustment: Adjust in hadoop-env.sh file

This guide will guide you to learn how to use Syslog in Debian systems. Syslog is a key service in Linux systems for logging system and application log messages. It helps administrators monitor and analyze system activity to quickly identify and resolve problems. 1. Basic knowledge of Syslog The core functions of Syslog include: centrally collecting and managing log messages; supporting multiple log output formats and target locations (such as files or networks); providing real-time log viewing and filtering functions. 2. Install and configure Syslog (using Rsyslog) The Debian system uses Rsyslog by default. You can install it with the following command: sudoaptupdatesud


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.