I. Why Are System Calls Needed?
Every day, the applications we use are constantly invoking capabilities provided by the operating system:
- Opening a file requires the operating system to access the disk.
- Creating a process requires the operating system to allocate process resources.
- Requesting memory requires the operating system to manage the virtual address space.
- Sending a network request requires the operating system to operate the network card and the network protocol stack.
- Creating a thread requires the operating system to create and schedule the execution entity.
- Obtaining the system time requires the operating system to provide clock services.
But an application itself cannot freely operate all hardware resources.
For example, an ordinary user program cannot directly modify the disk controller registers, cannot arbitrarily read the memory of other processes, and certainly cannot directly modify the data structures of the operating system kernel.
This is because the operating system must manage computer resources in a unified way and isolate access between different programs.
Therefore, the operating system provides a controlled set of service entry points, allowing applications to use kernel capabilities while obeying permission and security rules.
This mechanism is the system call.
1. A Simple Example
In Linux, an application can read a file with the following code:
#include <fcntl.h>
#include <unistd.h>
int main() {
char buffer[128];
int fd = open("hello.txt", O_RDONLY);
if (fd < 0) {
return 1;
}
ssize_t n = read(fd, buffer, sizeof(buffer));
close(fd);
return 0;
}
Three familiar functions appear in the code:
open(): open a file.read(): read the file contents.close(): close the file.
These functions look like ordinary C functions, but in Linux they usually enter the kernel through a system call, requesting that the kernel complete the file operation.
The application does not need to control the disk hardware itself, nor does it need to understand the internal data structures of the file system.
It only needs to make a request, and the operating system will complete the corresponding operation after permission checks and resource management.
2. What Problems Do System Calls Solve?
| Problem | Capability provided by system calls |
|---|---|
| How applications access files | File read/write interface |
| How applications create processes | Process management interface |
| How applications request memory | Memory management interface |
| How applications use the network | Socket interface |
| How applications create threads | Thread and task management interface |
| How applications wait for events | Blocking, waiting, and event notification interfaces |
| How to protect the kernel | Controlled privilege boundary |
| How to isolate different programs | The kernel uniformly manages resources and access permissions |
The essence of a system call is not simply calling a function, but entering a protected kernel execution environment from a restricted user execution environment to request a service from the operating system.
II. User Mode and Kernel Mode: Why Are Two Execution Modes Needed?
To understand system calls, you must first understand CPU execution privileges.
Modern operating systems typically use the privilege-level mechanisms provided by the CPU to divide the program execution environment into different privilege levels.
In common operating systems, the two most important concepts are:
- User mode.
- Kernel mode.
1. User Mode
User mode is the environment in which ordinary applications run.
For example:
- Browsers.
- Python programs.
- Java applications.
- Database clients.
- Command-line tools.
User-mode programs can typically access only the memory regions they are permitted to, and cannot directly execute CPU instructions that require high privileges.
Key characteristics of user mode:
- Memory access is limited by the process address space.
- Privileged instructions cannot be executed directly.
- The memory of other processes cannot be accessed arbitrarily.
- Kernel data structures cannot be modified directly.
- Kernel services must be requested through system calls.
For example, an ordinary program cannot directly modify page tables, nor can it arbitrarily control disk devices.
2. Kernel Mode
Kernel mode is the high-privilege environment in which the operating system kernel runs.
The kernel can perform many more protected operations, such as:
- Managing processes and threads.
- Allocating and reclaiming physical memory.
- Modifying page tables and managing address spaces.
- Operating device drivers.
- Managing the file system.
- Processing network protocols.
- Configuring interrupt controllers.
- Scheduling the CPU.
Kernel mode has higher privileges, but that does not mean the kernel can ignore all security rules.
The operating system still needs to guarantee the consistency of its internal data structures through mechanisms such as permission checks, resource reference counting, locking, and access control.
3. User Mode vs. Kernel Mode
| Comparison aspect | User mode | Kernel mode |
|---|---|---|
| Execution subject | Ordinary applications | Operating system kernel |
| Execution privileges | Restricted | High privileges |
| Access kernel memory | Direct access not allowed | Can access |
| Execute privileged instructions | Usually not allowed | Allowed |
| Access devices | Through controlled interfaces | Can operate through mechanisms such as drivers |
| Address space | Process user space | Kernel space |
| Scope of error impact | Usually confined to the process | May affect the entire system |
4. User Space and Kernel Space
Taking a common 64-bit Linux system as an example, each process has its own virtual address space.
Logically, it can be divided into:
Process virtual address space
High address
┌──────────────────────────────────┐
│ Kernel space │
│ │
│ Kernel code │
│ Kernel data │
│ Kernel mappings │
├──────────────────────────────────┤
│ User space │
│ │
│ Stack │
│ Shared libraries │
│ Memory-mapped region │
│ Heap │
│ Data segment │
│ Code segment │
└──────────────────────────────────┘
Low address
Note that this is only a logical schematic diagram.
The actual address layout depends on factors such as CPU architecture, operating system version, kernel configuration, and address space randomization.
A user program cannot directly access kernel memory just because it knows the address of kernel space.
The CPU's privilege checks and memory page access permissions prevent ordinary user-mode programs from performing unauthorized access.
5. Why Can't All Programs Run Directly in Kernel Mode?
If all applications had kernel privileges, it would cause serious problems:
First, security risks.
Malicious programs could directly access the memory of other processes, modify system data, and even control devices.
Second, stability risks.
A pointer error in an ordinary application could damage the entire system.
Third, resource management out of control.
Multiple programs could modify device and memory management structures at the same time, causing inconsistent system state.
Fourth, failure of isolation mechanisms.
Different applications could not be effectively isolated from one another, and a program crash could also cause the entire system to crash.
Therefore, the operating system needs to establish privilege boundaries.
System calls are the controlled entry points for crossing this boundary.
III. What Exactly Is a System Call?
A system call is the kernel service interface provided by the operating system to user programs.
An application uses a system call to request that the kernel complete a certain task; the kernel checks whether the request is valid, then performs the corresponding operation and returns the result.
For example:
read(fd, buffer, 1024);
The program wants to read data from the file corresponding to the file descriptor fd.
However, the actual work of reading the file usually requires kernel involvement:
- Check whether the file descriptor is valid.
- Check whether the process has read permission.
- Determine the current file offset.
- Query the page cache.
- Request the underlying storage device when necessary.
- Provide the data to user space.
- Return the actual number of bytes read or an error.
These tasks cannot be completed directly by an ordinary user program.
1. System Calls Are Not Ordinary Function Calls
Ordinary function calls mainly occur within the execution environment of the current process.
For example:
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(10, 20);
return 0;
}
When executing add(), the CPU usually only needs to:
- Save the necessary return address.
- Pass parameters.
- Jump to the function entry point.
- Execute the function code.
- Return to the call site.
The entire process does not cross the privilege boundary between user mode and kernel mode.
System calls are different.
They need to switch to the kernel execution environment through a specialized mechanism provided by the CPU.
Comparison of the two:
| Comparison aspect | Ordinary function call | System call |
|---|---|---|
| Call target | Ordinary function | Kernel service |
| Execution environment | Usually remains at the current privilege level | Enters kernel mode from user mode |
| Privilege change | None | Yes |
| Execution overhead | Usually lower | Usually higher |
| Security checks | Depends on the function implementation | Requires kernel execution privileges and parameter checks |
| Return method | Function return | System call returns to user mode |
2. What Is the Difference Between System Calls and Library Functions?
It is easy to confuse three concepts here:
- API.
- Library function.
- System call.
They are not at the same level.
Take Linux as an example:
Application
│
▼
POSIX API or C standard library interface
│
▼
System call wrapper
│
▼
Linux system call entry
│
▼
Kernel service implementation
For example, when calling:
read(fd, buffer, size);
what is usually called is actually the read() wrapper function provided by the C standard library.
The wrapper function is responsible for passing arguments according to the system call ABI and entering the kernel via a system call instruction.
It is important to note:
- An API is an interface contract used by programmers.
- A library function is an implementation provided by a software library.
- A system call is a service entry point provided by the kernel.
Not every library function requires a system call.
For example:
strlen("hello");
strlen() usually only calculates the string length in user mode and does not need to enter the kernel.
By contrast:
read(fd, buffer, 100);
usually needs to request that the kernel read data through a system call.
3. Relationship Between APIs, Library Functions, and System Calls
flowchart TD
A["Application"] --> B["Call API"]
B --> C{"Need kernel service?"}
C -->|No| D["Execute user-space library function"]
D --> E["Return to application"]
C -->|Yes| F["Call system call wrapper"]
F --> G["Trigger system call instruction"]
G --> H["Enter kernel mode"]
H --> I["Execute kernel service"]
I --> J["Return to user mode"]
J --> E
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#FFF2CC,stroke:#E8D28A,color:#755A18
style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
style G fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
style H fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style I fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
IV. How Is a System Call Executed?
The core process of a system call is:
The application prepares the arguments, executes the system call instruction, the CPU switches to kernel mode, the kernel finds and executes the corresponding service, and finally returns to user mode.
The following explains this using the Linux x86-64 architecture as an example.
1. The Application Prepares Arguments
Suppose the program executes:
read(fd, buffer, 1024);
In the Linux x86-64 system call ABI, arguments are usually passed through registers.
For read(), the arguments are:
- The first argument: file descriptor
fd. - The second argument: user buffer address
buffer. - The third argument: read length
1024.
2. Preparing the System Call Number
Each system call has a corresponding system call number.
For example, in the common Linux x86-64 ABI:
| System call | Number |
|---|---|
| read | 0 |
| write | 1 |
| open | 2 |
| close | 3 |
| mmap | 9 |
| mprotect | 10 |
| munmap | 11 |
| getpid | 39 |
| socket | 41 |
| clone | 56 |
| execve | 59 |
| exit | 60 |
These numbers belong to a specific architecture and ABI, and cannot be applied directly to other architectures.
3. Entering the Kernel via the syscall Instruction
Linux x86-64 uses the syscall instruction to trigger a system call.
A simplified assembly example:
mov rax, 0 ; system call number for read
mov rdi, 3 ; file descriptor
mov rsi, buffer ; user buffer address
mov rdx, 1024 ; read length
syscall ; enter the kernel
Where:
| Register | Role |
|---|---|
| RAX | System call number |
| RDI | First argument |
| RSI | Second argument |
| RDX | Third argument |
| R10 | Fourth argument |
| R8 | Fifth argument |
| R9 | Sixth argument |
The system call return value is usually returned via RAX.
Here is a detail that is easy to overlook:
The fourth argument of a Linux x86-64 system call uses R10, whereas the fourth integer argument in the ordinary System V AMD64 function calling convention typically uses RCX.
Therefore, the ordinary function calling ABI and the system call ABI must not be conflated.
4. The CPU Switches to Kernel Mode
After syscall is executed, the CPU transfers to the kernel execution environment according to the system call entry configuration.
On the x86-64 architecture, the relevant mechanisms include:
IA32_LSTAR: holds the address of the 64-bit system call entry point.IA32_FMASK: specifies the flag bits to be cleared when entering a system call.STAR: holds the relevant segment selector configuration.RCX: holds the user-mode return address.R11: holds the user-mode flags register information.
These are architecture-level details.
The operating system needs to handle register saving, kernel stack switching, execution context, and security checks in the entry code.
Particular attention should be paid to the following:
The syscall instruction itself does not automatically complete all kernel stack management work. The Linux kernel entry code still needs to perform the corresponding context handling.
5. The Kernel Dispatches the Request Based on the System Call Number
After entering the kernel, the kernel needs to find the corresponding handler based on the system call number.
For example:
system call number
│
▼
system call entry
│
▼
check system call number
│
▼
system call dispatch table
│
▼
corresponding kernel handler
If the system call number is invalid, the kernel returns the corresponding error.
6. The Kernel Performs the Specific Operation
For read(), the kernel performs a series of checks and processing steps:
- Check the file descriptor.
- Obtain the corresponding kernel file object.
- Check the file access mode.
- Check the user buffer address.
- Invoke the read operation of the specific file system.
- Query the page cache or submit device I/O.
- Copy the data to user space.
- Update the file offset.
- Return the read result.
The actual implementation may involve the VFS, the page cache, the file system, and the block device layer.
7. Return to User Mode
After the kernel completes the operation, it places the return value into the agreed-upon register.
It then restores the user-mode execution environment through an architecture-specific return path.
On Linux x86-64, the common return path uses sysretq; in some cases, mechanisms such as iretq may also be used.
The program then continues execution from after the system call.
8. The Complete System Call Flow
flowchart TD
A["Application calls read"] --> B["C library wrapper function"]
B --> C["Prepare system call number"]
C --> D["Prepare argument registers"]
D --> E["Execute syscall instruction"]
E --> F["CPU enters kernel entry"]
F --> G["Set up kernel execution context"]
G --> H["Check system call number"]
H --> I["Dispatch to sys_read"]
I --> J["Check file descriptor and permissions"]
J --> K["Call filesystem read logic"]
K --> L["Fetch file data"]
L --> M["Return read result"]
M --> N["Restore user-mode execution environment"]
N --> O["Return to application"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style D fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style E fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#FFF2CC,stroke:#E8D28A,color:#755A18
style I fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
style J fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style K fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style L fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style M fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style N fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style O fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
5. How Are System Call Arguments Passed?
A system call not only needs to know what operation the application wants to perform; it also needs the parameters required to perform that operation.
For example:
write(fd, buffer, size);
The kernel needs to know:
- Which file to write to.
- Where to read the data from.
- How many bytes to write.
Different CPU architectures use different argument-passing conventions.
1. Register Passing
Modern processors typically pass system call arguments through registers.
Taking Linux x86-64 as an example:
| Argument Position | Register |
|---|---|
| System call number | RAX |
| Argument 1 | RDI |
| Argument 2 | RSI |
| Argument 3 | RDX |
| Argument 4 | R10 |
| Argument 5 | R8 |
| Argument 6 | R9 |
| Return value | RAX |
This approach is more efficient and does not require constructing a complex data structure for every system call.
2. Why Are Pointers Still Necessary?
Some system calls need to pass larger amounts of data.
For example:
read(fd, buffer, 4096);
4096 bytes of data are not suitable for being placed entirely in registers.
Therefore, the application typically passes a user-space address.
The kernel then accesses the corresponding user-space memory based on this address.
3. Why Can't the Kernel Directly Trust User-Supplied Addresses?
Because user programs may pass in:
- Invalid addresses.
- Unmapped addresses.
- Read-only addresses.
- Addresses that do not belong to the current process.
- Addresses outside the valid range.
If the kernel trusted these addresses directly, malicious programs could exploit system calls to compromise kernel security.
Therefore, the kernel must validate user-space addresses.
For example, common user-space data access mechanisms in the Linux kernel include:
copy_from_user();
copy_to_user();
get_user();
put_user();
These interfaces are used to safely transfer data between the kernel and user space.
4. Data Copying Between User Space and Kernel Space
Taking write() as an example:
User buffer
│
▼
Kernel validates user address
│
▼
Read user-space data
│
▼
Copy to kernel-managed buffer or page cache
│
▼
Perform subsequent write operation
Taking read() as an example, the data direction is usually the opposite.
Note that not all system calls must copy the complete data.
For example:
mmap()establishes a mapping relationship.sendfile()can reduce some user-space relay copies.splice()can transfer data between kernel-managed objects such as pipes and files.io_uringprovides an asynchronous I/O submission and completion mechanism.
These mechanisms can reduce data copies or the number of system calls in specific scenarios.
VI. What are the common Linux system calls?
There are many system calls, but they can be divided into different categories by function.
1. Process management
Process management system calls are used to create, execute, wait for, and terminate processes.
Common interfaces:
| System call | Purpose |
|---|---|
| fork | Create a child process |
| clone | Create a process or thread execution entity |
| execve | Load and execute a new program |
| exit | Terminate the current process or thread |
| wait4 | Wait for a state change in a child process |
| getpid | Get the process ID |
| getppid | Get the parent process ID |
| kill | Send a signal to a process |
For example:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
printf("child process\n");
} else if (pid > 0) {
wait(NULL);
printf("parent process\n");
}
return 0;
}
fork() requests the kernel to create a child process.
wait(), in turn, makes the parent process wait for a state change in the child process.
2. File management
File system-related system calls are responsible for creating, opening, reading, writing, and managing files.
| System call | Purpose |
|---|---|
| openat | Open a file |
| read | Read a file |
| write | Write to a file |
| close | Close a file |
| lseek | Change the file offset |
| stat | Get file attributes |
| fstat | Get attributes via a file descriptor |
| unlink | Remove a file's directory entry |
| rename | Rename or move a directory entry |
| fsync | Synchronize file data and related metadata |
| mkdir | Create a directory |
In modern Linux, open() is usually implemented or wrapped through interfaces such as openat().
3. Memory management
Memory management system calls are used to control a process's virtual address space.
| System call | Purpose |
|---|---|
| mmap | Create a memory mapping |
| munmap | Remove a memory mapping |
| mprotect | Change memory protection attributes |
| brk | Adjust the process heap boundary |
| madvise | Give the kernel advice on memory usage |
| mremap | Resize an existing mapping region |
For example:
#include <sys/mman.h>
#include <stdio.h>
int main() {
size_t size = 4096;
void *ptr = mmap(
NULL,
size,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS,
-1,
0
);
if (ptr == MAP_FAILED) {
return 1;
}
munmap(ptr, size);
return 0;
}
It is important to distinguish:
malloc() is a C standard library interface, not a system call.
The memory allocator may request virtual memory from the kernel via brk() or mmap(), and then manage the actual memory blocks in user space.
4. Network communication
Linux provides network communication capabilities through Socket-related system calls.
| System call | Purpose |
|---|---|
| socket | Create a socket |
| bind | Bind a local address |
| listen | Listen for connections |
| accept | Accept a connection |
| connect | Initiate a connection |
| sendto | Send a datagram |
| recvfrom | Receive a datagram |
| shutdown | Shut down part or all of a communication direction |
A typical TCP server involves:
socket()
bind()
listen()
accept()
recv()
send()
close()
In actual programs, these steps are completed through the cooperation of the network protocol stack and the kernel networking subsystem.
5. Threads and Synchronization
Common related interfaces:
| System call or interface | Purpose |
|---|---|
| clone | Create a task execution entity |
| futex | Provide kernel support required by user-space synchronization primitives |
| set_tid_address | Set the address related to thread exit |
| sched_yield | Voluntarily yield the CPU |
| sched_setaffinity | Set CPU affinity |
| sched_setscheduler | Set scheduling policy |
Note that pthread_create() is a POSIX thread library interface, not a raw Linux system call.
On Linux, the thread library usually requests that the kernel create a thread execution entity through clone() or related mechanisms, and uses mechanisms such as futex to implement some synchronization functionality.
6. Time and System Information
| System call | Purpose |
|---|---|
| clock_gettime | Get clock time |
| gettimeofday | Get time information |
| uname | Get system information |
| getuid | Get user ID |
| geteuid | Get effective user ID |
| getrandom | Get random data |
| sysinfo | Get system runtime information |
Some system information interfaces may be completed in user space through mechanisms such as vDSO, and may not actually enter the kernel every time.
VII. What Are the Differences Between System Calls, Interrupts, and Exceptions?
System calls, hardware interrupts, and CPU exceptions can all cause the CPU to change its current execution flow, but they are triggered for different reasons.
1. System Calls
A system call is usually actively initiated by a running user program.
For example:
read(fd, buffer, 1024);
The program explicitly requests that the kernel read data.
On x86-64 Linux, the common entry point is the syscall instruction.
2. Hardware Interrupts
Hardware interrupts are usually triggered by external devices or an interrupt controller.
For example:
- A network card receives a data packet.
- A keyboard generates input.
- A timer generates a clock event.
- A storage device completes I/O.
Hardware interrupts are not actively requested by an application through ordinary function calls.
3. CPU Exceptions
CPU exceptions are usually caused by the execution of the current instruction.
For example:
- Divide-by-zero exception.
- Illegal instruction.
- Page fault.
- Access permission error.
For example, when a program accesses a virtual address that has not yet been mapped, a page fault may be triggered.
The operating system needs to determine whether this is legitimate demand paging or an illegal memory access.
4. Comparison of the Three
| Comparison dimension | System call | Hardware interrupt | CPU exception |
|---|---|---|---|
| Trigger source | User program request | External hardware event | Execution of the current instruction |
| Actively requested? | Usually active | Usually passive | Usually caused by execution behavior |
| Typical example | read, write | Network card interrupt | Page fault |
| Main purpose | Request kernel services | Respond to external events | Handle execution exceptions or special conditions |
| Handling location | Kernel | Kernel interrupt handler | Kernel exception handler |
5. Relationship Among the Three
flowchart TD
A["CPU is executing a program"] --> B{"What event occurs"}
B -->|Program requests service| C["System call"]
B -->|External device event| D["Hardware interrupt"]
B -->|Instruction execution exception| E["CPU exception"]
C --> F["Enter kernel processing"]
D --> F
E --> F
F --> G["Execute corresponding kernel processing logic"]
G --> H["Restore or adjust execution state"]
H --> I["Continue execution or terminate task"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF2CC,stroke:#E8D28A,color:#755A18
style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style D fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
style E fill:#FCE8E6,stroke:#E6B2AA,color:#854B45
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style H fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
Note that a system call is not equivalent to a hardware interrupt.
It is a dedicated control-transfer mechanism provided by the CPU, usually with synchronous, predictable call semantics.
8. Why do system calls incur performance overhead?
System calls are usually more expensive than ordinary function calls.
The reason is not just that a special instruction is executed; the entire process of switching across the user-mode/kernel-mode boundary involves extra work.
1. Privilege-level switching
A system call requires entering kernel mode from user mode and then returning to user mode.
The CPU must perform the corresponding control transfer and, depending on the architecture and kernel implementation, save and restore the necessary execution state.
2. Context management
The kernel entry point must handle:
- User-mode register state.
- Kernel stack.
- Execution context.
- Security checks.
- System call arguments.
All of this work introduces some overhead.
3. Data copying
For example:
read(fd, buffer, 4096);
If the ordinary buffered I/O path is used, data may need to be copied from the kernel page cache to user space.
For large-scale data transfers, the data copying itself may become a performance bottleneck.
4. Kernel-internal processing
A system call may also execute complex kernel logic.
For example:
- File system lookup.
- Permission checks.
- Lock contention.
- Memory allocation.
- Network protocol processing.
- Disk I/O.
This work may take much longer than the privilege-level switch itself.
5. A system call does not necessarily imply a process switch
This is a very important concept.
Entering kernel mode does not mean a process context switch occurs.
For example:
getpid();
The kernel can quickly return the current process ID and usually does not need to schedule another process to run.
But if the program executes:
read(fd, buffer, size);
and the file data is temporarily unavailable, the process may enter a waiting state.
At this point, the kernel may schedule other runnable tasks.
Therefore, it is necessary to distinguish:
| Operation | Meaning |
|---|---|
| User mode to kernel mode switch | Execution privilege and control flow change |
| Kernel mode to user mode switch | Return to user program execution |
| Process context switch | The CPU switches from one execution task to another |
| Blocking | The current task is temporarily unable to continue running |
| Scheduling | The kernel selects a runnable task to occupy the CPU |
6. How can system call overhead be reduced?
Common optimization methods: