linux cow(Copy-on-Write)fork为什么很快?

Copy-on-Write是Linux内存管理非常经典的机制。


示例讲解

假设:

1
2
3
4
5
Parent Process
│
│ fork()
▼
Child Process

如果父进程有:

1
2
3
Page A
Page B
Page C

Linux并不会立即复制所有页面而是:

1
2
3
Parent ──┐
├──→ Page A
Child ───┘

两个进程暂时共享同一个物理页,页表设置成只读:

1
2
3
4
5
Parent → Page A ──┐
│
Child → Page A ──┘
│
Read Only

如果Child尝试CPU触发Page Fault。

1
PageA[0] = 100;

Linux发现:

1
这是Copy-on-Write

于是:

1
2
3
4
5
6
7
8
9
原Page A
│
├── Parent
│
└── Child
↓
Copy Page
↓
新Page B

最终:

1
2
3
Parent → Page A

Child → Page B

这就是:

COW(Copy-on-Write) 它广泛用于fork()以及其他内存共享场景。