1. What is the difference between a program and a process?
When learning about operating systems, programs and processes are two very important concepts.
They look very similar, but they represent completely different things.
1. What is a program?
A program is a set of instructions and data written to accomplish a certain task.
For example:
#include <stdio.h>
int main(void) {
int a = 10;
int b = 20;
int result = a + b;
printf("result = %d\n", result);
return 0;
}
This is a C language program.
After compilation and linking, an executable file can be generated:
gcc main.c -o app
At this point, an executable file named app appears on the disk.
A program has the following characteristics:
- It is stored on a disk or another persistent storage device.
- It contains machine instructions, constants, initialized data, and other contents.
- When it is not running, it does not need to occupy a process that is executing.
- It can be started multiple times.
- The program itself does not have an independent CPU execution state.
A program can be understood as a static set of execution instructions.
2. What is a process?
A process is an instance of a program while it is running and an important unit for resource allocation and management by the operating system.
When the user executes:
./app
the operating system creates a corresponding process and prepares the resources and execution environment required for it to run.
A process usually contains:
- Program code.
- Global variables and static data.
- Heap memory.
- Stack memory.
- CPU register state.
- Virtual address space.
- Open files and file descriptors.
- Process control information.
- Other resources allocated by the operating system.
A process contains not only the program itself but also the state generated while the program is running.
3. Core differences between programs and processes
| Aspect | Program | Process |
|---|---|---|
| Nature | Static instructions and data | Dynamic execution entity |
| Storage location | Usually on disk | Mainly uses memory when running |
| Lifecycle | For as long as the file exists | From creation to termination |
| Execution state | No execution state | Has an execution state |
| CPU state | Not included | Includes execution context such as registers |
| Memory space | Data layout in the file | Independent virtual address space |
| Resource management | Does not directly occupy runtime resources | Resources are managed by the operating system |
| Count relationship | One program can be started multiple times | Each start can form an independent process |
For example, the same browser program can start multiple processes.
Browser executable
│
├── Browser process A
│
├── Browser process B
│
└── Browser process C
These processes may run the same program code, but they have their own process identifiers, virtual address spaces, and execution states.
Note that modern browsers may also, depending on their architecture, assign different tabs, rendering tasks, and plug-ins to different types of processes; it is not necessarily one process per tab.
2. Where does a program begin to become a process?
For a program to become a process, it usually has to go through stages such as compilation, linking, loading, and process initialization.
First, let's look at the overall process:
flowchart TD
A["Write source code"] --> B["Compile"]
B --> C["Assemble"]
C --> D["Link"]
D --> E["Generate executable file"]
E --> F["User launches program"]
F --> G["Operating system creates process"]
G --> H["Load program image"]
H --> I["Set up virtual address space"]
I --> J["Initialize runtime environment"]
J --> K["Enter program entry point"]
K --> L["Execute main function"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style D fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style F fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style I fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style J fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style K fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style L fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
This process can be divided into two stages:
Stage one: program construction.
The source code goes through compilation, assembly, and linking to produce an executable file that the operating system can recognize.
Stage two: program execution.
The user launches the executable file, the operating system creates a process, sets up the runtime environment, and finally hands control over to the program.
Note that compilation and linking usually happen before the program runs. The operating system does not recompile the source code every time the program is started.
III. Step One: How Does Source Code Become an Executable File?
The operating system cannot directly execute source code written in high-level languages such as C, C++, or Java.
Such code must first be compiled or otherwise transformed before it can enter the corresponding runtime environment.
1. The Compilation Stage
The compiler is responsible for converting a high-level language into a form closer to what the machine executes.
Taking the C language as an example, a typical compilation process includes:
- Preprocessing.
- Compilation.
- Assembly.
- Linking.
For example:
gcc -E main.c -o main.i
The preprocessing stage handles:
#includeheader files.#definemacros.- Conditional compilation.
- Other preprocessing directives.
Next:
gcc -S main.i -o main.s
The compiler converts the preprocessed code into assembly code.
Then run:
gcc -c main.s -o main.o
The assembler converts the assembly code into an object file.
The object file contains machine instructions, data, symbol information, relocation information, and more.
2. The Linking Stage
A program may consist of multiple source files.
For example:
main.c
math.c
utils.c
Each source file can be compiled into an object file separately:
gcc -c main.c -o main.o
gcc -c math.c -o math.o
gcc -c utils.c -o utils.o
They are then linked into a single executable file:
gcc main.o math.o utils.o -o app
The linker is mainly responsible for:
- Merging the code and data in the object files.
- Resolving symbol references.
- Handling relocations.
- Organizing the layout of the executable file.
- Handling static and dynamic library dependencies.
3. What Is an Executable File?
On Linux systems, the common executable file format is ELF.
ELF stands for Executable and Linkable Format.
An ELF file may contain:
| Content | Purpose |
|---|---|
| ELF Header | Describes the file type, architecture, entry point, and other information |
| Program Header Table | Describes the segments that need to be loaded when the program runs |
| Section Header Table | Describes the sections needed for linking and analysis |
| .text | Usually holds the program's machine instructions |
| .data | Holds initialized writable global data |
| .bss | Describes uninitialized or zero-initialized data |
| .rodata | Holds read-only data |
| Symbol table | Holds symbol information |
| Relocation information | Assists with address adjustment |
Two important concepts need to be distinguished here:
- Section: mainly oriented toward compilation, linking, and debugging.
- Segment: mainly oriented toward program loading and execution.
When the operating system loads an ELF file, it builds the process image mainly from the load information in the program header table, rather than simply copying all sections into memory as-is.
4. Inspecting the ELF File Structure
You can use the tools provided by Linux to examine an executable file:
file app
To check the file type and architecture:
readelf -h app
To view the program headers:
readelf -l app
To view the section table:
readelf -S app
To view symbol information:
readelf -s app
You can also use:
objdump -d app
to disassemble the program and inspect its machine instructions.
These tools help us understand how a program is organized on disk.
IV. Step Two: What Happens When the User Starts the Program?
When the user types the following in the terminal:
./app
the operating system must determine whether this file can be executed and prepare the corresponding runtime environment for it.
On Linux, the terminal typically runs inside a shell process.
After receiving the command, the shell parses it and starts the corresponding program.
1. How Does the Shell Start a Program?
The common way to start a program on Unix/Linux is:
- Use
fork()to create a child process. - The child process calls
execve()to execute the target program.
Here:
fork() is responsible for creating a new process.
execve() replaces the current process's user-space image with a new program image.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid == 0) {
char *args[] = {"./app", NULL};
execve("./app", args, environ);
perror("execve");
_exit(127);
}
waitpid(pid, NULL, 0);
return 0;
}
The example above shows a parent process creating a child process, which then executes the new program.
In practice, you need to properly declare or pass the environment variable array, for example by adding the following at the top of the file:
extern char **environ;
2. What Does fork() Do?
fork() creates a new child process.
After a successful call:
- The parent process receives the child's PID.
- The child process receives a return value of 0.
- Both processes continue executing from the code position following the
fork()call.
For example:
pid_t pid = fork();
if (pid == 0) {
printf("我是子进程\n");
} else if (pid > 0) {
printf("我是父进程\n");
}
The parent and child processes have different process identifiers.
Modern Linux typically implements fork()'s memory management through copy-on-write.
That is, when a child process is created, all of the parent's physical memory pages are usually not copied in full right away; instead, the parent and child temporarily share the relevant physical pages, and those pages are marked as copy-on-write.
When either side attempts to modify a shared page, the kernel then creates a separate copy for it.
This reduces the memory-copying cost of creating a process.
3. What Does execve() Do?
The role of execve() is not to create a new process, but to replace the current process's program image.
For example:
execve(
"/usr/bin/ls",
(char *[]){"ls", "-l", NULL},
environ
);
After a successful call:
- The current process's user-space program image is replaced.
- The new program's code and data are loaded.
- The new program's entry point becomes the starting point of execution.
- The current process's PID usually remains unchanged.
- The process continues to use its original process identity.
Therefore:
fork creates a process, exec loads a new program.
These two operations are often used together, but they have different responsibilities.
4. The relationship between fork and exec
flowchart TD
A["Shell parses the command"] --> B["Call fork"]
B --> C["Create child process"]
C --> D["Parent process continues running"]
C --> E["Child process calls execve"]
E --> F["Replace child process program image"]
F --> G["Load target program"]
G --> H["Execute new program"]
D --> I["Wait for child process or continue processing commands"]
H --> J["Program execution ends"]
J --> I
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style D fill:#F1F3F5,stroke:#CBD5E1,color:#334155
style E fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style F fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style I fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style J fill:#F1F3F5,stroke:#CBD5E1,color:#334155
Note that a shell can also start programs in other ways, for example through interfaces such as posix_spawn(), and does not necessarily directly perform the traditional fork() plus exec() pattern every time.
V. Step 3: How Does the Operating System Load an Executable File?
After a process is created, the operating system needs to organize the executable file into a memory image that the process can run.
In Linux, when execve() is executed, the kernel selects the corresponding loading logic based on the file format.
For ELF files, the ELF loader is usually responsible for parsing the program headers in the file and establishing the corresponding memory mappings.
1. Check the executable file
The kernel first needs to check:
- Whether the file exists.
- Whether the current process has execute permission.
- Whether the file format is valid.
- Whether the target architecture is supported.
- Whether it can handle the interpreter the file depends on.
- Whether security policies and resource limits are satisfied.
If the file does not exist, it may return:
ENOENT
If there is no execute permission, it may return:
EACCES
If the file format cannot be recognized, it may return:
ENOEXEC
Therefore, executing a program does not mean the kernel will necessarily be able to load it successfully.
2. Parse the ELF file
For ELF files, the kernel reads their file header and program header table.
It focuses on program segments of type PT_LOAD.
These program segments describe the content that needs to be mapped into the process address space, such as:
- Program code.
- Read-only data.
- Writable data.
- The memory range corresponding to zero-initialized data.
For example, an ELF file may contain:
LOAD permissions R E
LOAD permissions R
LOAD permissions RW
Where:
- R: readable.
- W: writable.
- E: executable.
Different program segments are mapped to different virtual address ranges, and the corresponding access permissions are set.
3. The program is not necessarily copied completely into memory
A common misunderstanding is:
When the operating system starts a program, it copies the entire executable file into memory all at once.
In reality, modern operating systems usually use virtual memory and file mapping mechanisms.
For example:
mmap()
can map part of a file into the process's virtual address space.
Program code pages may use demand paging:
- Establish virtual address mappings.
- The pages have not yet actually entered physical memory.
- The CPU accesses a non-resident page for the first time.
- A page fault occurs.
- The kernel reads the corresponding file content into physical pages.
- Establish page table mappings.
- Resume program execution.
This means the program can load the relevant pages into physical memory gradually, only when the code and data are actually accessed.
4. How are dynamic libraries loaded?
Many programs are not entirely self-contained.
For example, a C program on Linux may depend on:
libc.so
dynamic libraries such as this one.
For a dynamically linked ELF, the file usually contains a PT_INTERP program header, which specifies the path of the dynamic linker.
For example:
/lib64/ld-linux-x86-64.so.2
During loading, the kernel recognizes this interpreter and establishes the corresponding execution image.
The dynamic linker is then responsible for:
- Loading the required shared libraries.
- Resolving dynamic symbols.
- Performing the necessary relocations.
- Completing dynamic linking initialization.
- Handing control over to the program's runtime entry point.
You can view dynamic library dependencies with the following command:
ldd ./app
Note that ldd is intended for trusted executables. For programs of unknown origin, you should not casually use inspection methods that may execute the target's code.
One of the safer static inspection methods is:
readelf -d ./app
It can show the ELF's dynamic segment information.
5. The overall program loading process
flowchart TD
A["Call execve"] --> B["Kernel checks the file"]
B --> C{"Is the file format valid?"}
C -->|"No"| D["Return execution error"]
C -->|"Yes"| E["Parse the ELF file"]
E --> F["Read the program header table"]
F --> G["Create PT_LOAD memory mappings"]
G --> H["Set code and data permissions"]
H --> I{"Is there a dynamic interpreter?"}
I -->|"Yes"| J["Load the dynamic linker"]
I -->|"No"| K["Prepare the program entry point"]
J --> L["Load shared libraries and complete relocations"]
L --> K
K --> M["Prepare the user stack and initial registers"]
M --> N["Enter the program execution entry"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style D fill:#FCE7E7,stroke:#D99A9A,color:#7F3333
style E fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style F fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style I fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style K fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style L fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style M fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style N fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
Six. Step Four: How does the operating system establish a process's memory space?
Once a program is loaded, it needs to have its own .
One of the most important components of this environment is the virtual address space.
1. What is a virtual address space?
The virtual address space is an address-space abstraction that the operating system provides to a process.
Each process usually has its own independent virtual address space.
For example:
Process A: Virtual address space
0x00000000
│
▼
┌──────────────────┐
│ Code segment │
├──────────────────┤
│ Data segment │
├──────────────────┤
│ Heap │
│ ↓ │
│ │
│ │
│ ↑ │
│ Stack │
├──────────────────┤
│ Kernel space │
└──────────────────┘
This is a simplified, typical layout; the specific address layout may differ across operating systems, processor architectures, and process types.
The virtual address space usually contains:
| Region | Main purpose |
|---|---|
| Code segment | Stores program machine instructions |
| Read-only data segment | Stores read-only data such as string constants |
| Data segment | Stores initialized global and static variables |
| BSS segment | Stores uninitialized or zero-initialized global and static variables |
| Heap | Manages dynamically allocated memory |
| Memory-mapped region | Maps shared libraries, files, and anonymous memory |
| Stack | Stores function call information and local variables |
| Kernel space | Address region used by the operating system kernel |
2. Why does every process need an independent virtual address space?
Suppose there are two processes:
Process A:
Virtual address 0x1000 -> Data A
Process B:
Virtual address 0x1000 -> Data B
Although they use the same virtual address, they can be mapped to different physical memory locations.
Therefore, when Process A modifies its own data, it does not directly affect Process B's data.
This mechanism provides:
- Memory isolation between processes.
- Independent address spaces.
- Memory access permission control.
- A simplified programming model.
- More flexible memory allocation.
3. How does the MMU perform address translation?
MMU stands for Memory Management Unit; in Chinese, it is called 内存管理单元.
It is responsible for converting virtual addresses issued by the CPU into physical addresses according to the page table, and it participates in checking access permissions.
Typical process:
flowchart TD
A["CPU issues a virtual address"] --> B["Look up TLB"]
B --> C{"TLB hit?"}
C -->|"Yes"| D["Obtain physical address"]
C -->|"No"| E["Look up page table"]
E --> F{"Page table mapping valid?"}
F -->|"Yes"| G["Update TLB"]
G --> D
F -->|"No"| H["Trigger page fault"]
H --> I["Operating system handles the page"]
I --> J["Update page table"]
J --> K["Re-execute access instruction"]
K --> B
D --> L["Access physical memory"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style E fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style F fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#FCE7E7,stroke:#D99A9A,color:#7F3333
style I fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style J fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style K fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style L fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
Here:
- The TLB is an address-translation cache.
- The page table stores the mapping between virtual pages and physical pages.
- A page fault does not necessarily mean the program has an error; it may simply mean the page has not been loaded yet.
- If the accessed address is invalid or permissions do not allow access, the operating system may send signals such as
SIGSEGVto the process.
4. How are the heap and stack established?
While a process is running, it needs to dynamically allocate memory and also needs to save function call information.
The heap and stack have different responsibilities.
Stack:
- Stores function call-related information.
- Stores local variables.
- Stores return addresses and part of the register state.
- Is usually managed automatically by function calls and returns.
Heap:
- Used for dynamic memory allocation.
- Requested by the program through interfaces such as
malloc(),calloc(), etc. - Released by the program through
free(). - At the lower level, it is usually managed jointly by the memory allocator and the operating system.
For example:
#include <stdlib.h>
int main(void) {
int local = 10;
int *heap_data = malloc(sizeof(int));
if (heap_data == NULL) {
return 1;
}
*heap_data = 20;
free(heap_data);
return 0;
}
Here:
localis usually located on the stack.- The pointer variable
heap_datais usually located on the stack. - The integer object allocated by
malloc()is located in the memory region managed by the heap.
Note that the exact storage location also depends on compiler optimizations and the program implementation.
7. Step 5: How Does the Operating System Create Process Control Information?
Setting up the memory space is only one part of creating a process.
The operating system also needs to record the process's identity, state, resources, and execution context.
This requires a process control block.
1. What Is a PCB?
PCB stands for Process Control Block (进程控制块 in Chinese).
It is an important data structure that the operating system uses to manage processes.
A PCB usually contains:
| Information category | Main contents |
|---|---|
| Process identity | PID, parent process PID |
| Process state | Running, ready, blocked, etc. |
| CPU context | Program counter, registers, etc. |
| Scheduling information | Priority, scheduling policy, time slice, etc. |
| Memory management information | Address space, page tables, etc. |
| File information | Open files, file descriptors |
| Signal information | Signal handling methods and pending signals |
| Resource information | User identity, resource limits, etc. |
The PCB enables the operating system to accurately identify and manage each process.
2. task_struct in Linux
In the Linux kernel, process-related information is mainly managed by the task_struct structure.
The relevant definition can be found in the Linux kernel source code.
Internally it contains a great deal of information, for example:
struct task_struct {
/* process state */
volatile long state;
/* process identity */
pid_t pid;
pid_t tgid;
/* process scheduling information */
/* scheduling entities, etc. */
/* memory management information */
struct mm_struct *mm;
/* file system related information */
struct files_struct *files;
/* signal related information */
struct signal_struct *signal;
};
The above is only a conceptual, simplified example; it is not a complete structure that can directly replace the real Linux kernel definition.
Linux abstracts both processes and threads as schedulable tasks.
Therefore, task_struct is not merely a simple counterpart of a traditional PCB; it also takes on management responsibilities such as the thread execution entity.
3. What Is a PID?
PID stands for Process Identifier.
On Linux, you can view processes with the following command:
ps -ef
To view a specific process:
ps -p 1234 -o pid,ppid,stat,comm
To view the process ID of the current shell:
echo $$
In C:
#include <stdio.h>
#include <unistd.h>
int main(void) {
printf("PID: %d\n", getpid());
printf("PPID: %d\n", getppid());
return 0;
}
Where:
getpid()returns the PID of the current process.getppid()returns the PID of the current process's parent process.
The PID is an important identifier for process management, but it is not the entirety of a process's identity information. A process also has attributes such as user, namespace, resources, and security context.
8. Step 6: How Does the Program Entry Point Get into the main() Function?
Many beginners believe that after the operating system loads a program, it directly executes main().
But for common C programs, the actual process usually also goes through runtime startup code.
1. The ELF Entry Point
The ELF file header contains an important field:
e_entry
It indicates the program entry address.
You can view it with the following command:
readelf -h ./app
The output may contain:
Entry point address: 0x1050
This means an entry address is defined in the program image.
However, this entry address usually does not point directly to main().
2. What Is _start?
In common Linux C programs, the ELF entry point usually points to _start.
_start is the entry symbol provided by the runtime startup code.
It is responsible for preparing the C runtime environment and ultimately calling the program's main() function.
The typical startup process includes: