
fork() はなぜ、どのようにコピーオンライトを使うのか
How and Why fork() Uses Copy-on-Write

fork() はなぜ、どのようにコピーオンライトを使うのか
Confessions of a Code Addict
要約
Confessions of a Code Addict の Abhinav が、仮想メモリ解説シリーズの続きとして、fork() システムコールにおけるコピーオンライト(COW)の必要性を説明する回。前回の mmap に続く2つ目の経路として、COW の復習から入り、fork が親プロセスのファイル記述子表とアドレス空間を子に複製する仕組みをコード例で示す。後半で Instagram の事例を扱うと予告しているが、収録の文字起こしは fork の基本説明の途中で終わっている。
この回のポイント
- ●COW は mmap だけでなく fork でもカーネルが自動的に使う仕組みで、ユーザーが明示的に有効化するものではないと説明している。
- ●仮想ページと物理フレーム(x86・Linux では通常 4KB)の対応はページテーブルが管理し、COW により複数プロセスが同じ物理フレームを共有できる。
- ●共有中のページテーブルエントリは読み取り専用にされ、書き込みがあるとページフォルトが発生し、カーネルがフレームをコピーして書き込み可能に更新する。
- ●fork は親プロセスから呼ばれ、子は親のファイル記述子表と仮想アドレス空間を引き継ぎ、fork の直後から実行を再開する。
- ●fork の戻り値は子では 0、親では子の PID となり、これで両者を区別する。親が値を書き換えても子には見えない。
- ●Instagram が COW を使ってメモリ使用量を最適化し、期待に反して COW が働いてしまう不具合に遭遇した事例を後半で扱うと予告している。
章立て
前回の振り返りと今回の予定
前回は mmap を例に COW を扱った。今回は fork という第二の経路を解説し、最後に Instagram の事例を紹介すると述べている。
事例を学ぶ意義
日々保守するシステムでも同様のバグは起こり得るため、仕組みの深い理解がデバッグに役立つと述べている。
仮想メモリとページテーブルの復習
仮想ページと物理フレームの対応、ページテーブルによるアドレス変換を簡単な図で振り返る。
COW によるフレーム共有の仕組み
共有ページを読み取り専用にし、書き込み時のページフォルトでカーネルがコピーを作る流れを説明する。
fork とは何か
fork は新しいプロセスを作るシステムコールで、子は親のファイル記述子表と仮想アドレス空間を引き継ぐ。
コード例で見る親と子
malloc と open の後に fork を呼ぶ例で、戻り値による親子の判別と、親の書き込みが子に影響しないことを示す。
解説記事
Confessions of a Code Addict の Abhinav が、仮想メモリ解説シリーズの一編として、fork() とコピーオンライト(COW)の関係を解説した回である。前回は mmap を例に COW の基本を扱っており、今回は COW が働くもう一つの経路である fork に焦点を当てる。なお、提供された文字起こしは fork の基本動作の説明の途中で終わっており、予告された Instagram の事例の中身までは含まれていない。
COW は「裏側で」働く仕組み
Abhinav はまず、COW が mmap と同様に、利用者が明示的に頼まなくてもカーネルが自動的に使う仕組みだと位置づける。前提となるのは仮想メモリの二層構造だ。プロセスのコードは仮想アドレスを使い、ハードウェアがページテーブルを引いて物理アドレスに変換する。仮想ページと物理フレームは、x86 の Linux では通常どちらも 4KB だが、これは固定値ではなくカーネルやアーキテクチャに依存し、近年は変わりつつあると述べている。
共有と書き込み時コピーの流れ
複数プロセスが同じ物理フレームを共有できるのは COW のおかげだ、というのが説明の核である。もし COW がなければ、片方のプロセスの書き込みがもう片方に見えてしまい、各プロセスは独立して動くという実行モデルが崩れる。
そこでカーネルは、共有しているページテーブルエントリを読み取り専用にする。書き込みが起きるとハードウェアが拒否してページフォルトが発生し、カーネルがそれを処理する中で COW だと判断する。共有フレームのコピーを作り、書き込んだプロセスのページテーブルをコピー側に向け直し、読み取り専用の制限を外す。もう一方のプロセスは元のフレームを読み続ける。前回の mmap では、同じファイルを読む複数プロセスで RAM を無駄にしないために有効だと説明されていた。
fork が複製するもの
fork は Unix 系 OS で新しいプロセスを作るシステムコールで、呼び出した側が親、生成された側が子になる。子は親のほぼ複製であり、親が開いたファイルやソケットを含むファイル記述子表のコピーを受け取る。仮想アドレス空間も同じ状態で複製され、さらに RAM 上の実データについても、子は親と同じ内容を持つ必要がある。ただし両者は独立したプロセスなので、共有ではなくコピーでなければならない、と強調している。
ここに COW が必要になる理由がある。ここでの説明は、全データを即座に複製するのではなく、同じフレームを共有しておき書き込み時にコピーするという流れにつながる。ただし、この点を詳しく語る部分は収録範囲に含まれていない。
コード例:戻り値で親子を分ける
具体例として、親が malloc でメモリを確保し、ファイルを open し、配列の先頭に 42 を書き込んでから fork を呼ぶコードが示された。fork はカーネルへの一回の入り口だが、ユーザー空間へは二つの経路で戻る。子では戻り値の PID が 0、親では子のプロセス ID が返るため、これで処理を分岐する。
子は自分で開いていないはずのファイル記述子を閉じられ、確保済みの配列も同じアドレスで読める。一方、親が先頭バイトを 84 に書き換えても、子が見る値は 42 のままである。これが fork のセマンティクスだ。
まとめ
fork の「子は親の完全なコピー」という振る舞いは、メモリを丸ごと複製するという素朴な実装だと高コストになりうる。COW はそれを、読み取り専用マッピングとページフォルトで遅延させる仕組みだと理解できる。日本のエンジニアにとっては、プロセス生成やマルチプロセス構成のメモリ挙動を考える基礎になる。Instagram の事例は本文では確認できないが、COW が意図に反して働く場面があるという問題意識は、本番システムの運用でも参考になるだろう。
文字起こし(英語・自動生成)
Hey everyone, this is Abhinav. Welcome back to our series on virtual memory. In the last video, we started to talk about copy and write. And in that video, I also mentioned that this is such a wide topic that we will need at least two videos to cover it in its entirety. So in the last video, we focused on what copy and write is. and then we took the example of the mmap system call and we understood in depth how copy and write works right from the user space code where we are mapping a file right inside the kernel and at the hardware level when file data is actually accessed. So, and we also analyze what are the pros and cons of having copy and write. And this video is a continuation of that So, in this video we will focus on the fourth system call which is the second pathway where copy on write happens.
And again just like mMAP this is another area where copy on write happens behind the scene. So, it is not something we are deliberately enabling or asking the kernel to do. The kernel just uses copy and write automatically and the same mechanics apply just like mMAP but it is just a very different pathway. So this video will focus on that. So we will discuss why copy on write is actually needed when you use for. And we will discuss the mechanics that of copy and write on this pathway. And towards the end, we will also discuss a very interesting real world war story from Instagram. Because Instagram actually uses copy and write as a way to optimize their memory usage in their production systems. and they found a bug where copy and write was actually working against their expectations. So, which then they had to debug and understand why, what was happening and what was causing that.
So, we'll discuss that. I think that story would make a lot of sense if you understand copy and write. And this is the reason that I wanted to talk about that story is because in our systems as well, So whatever kind of system that we are responsible for maintaining in our day jobs, this kind of behavior, these kind of bugs can also show up. And without having a deep understanding of the mechanics of these kind of features, it can be very difficult to debunk these kind of problems. So I think it would be very beneficial if you watch it till that point of time. So, let us start this video with a quick recap of copy and write and then from there we will go towards fork. So, let us start with a recap. So, we know that the memory of a process has two aspects. Whenever we are talking about the memory of a process, there are two parts to it.
One is the virtual memory and the other is the real physical memory where the real data is actually stored. So, the virtual memory is basically, it consists of virtual pages. So, each page is usually 4KB in size. And a virtual page is mapped to a physical frame, which is also 4KB. 4KB is not something hard-coded or, you know, fixed. It depends on the kernel and the hardware architecture. So, I am using 4KB because for a very long time, it has been the standard everywhere. Most operating systems and most hardware have been using 4KB for a very long time, but now slowly things are changing. But on x86, on Linux kernel, 4KB is still the default. So, a virtual page of 4KB is mapped to a physical frame of 4KB. And the real data is stored in the physical frame. But in the processes machine code, all the instructions actually use virtual addresses.
So, whenever the hardware, whenever in our code, we are doing any memory access, the hardware has to translate the virtual address to a physical address and it has to figure out the translation. So, this mapping of virtual to physical pages, this is where it comes into the picture. So this mapping is maintained by a kernel in a structure called a page table We have talked about Pasteable in a past video so I recommend that you go and watch that So I resume all of us are experts in ah virtual page ah virtual tables at this point of time I will just draw ah a simplistic ah picture to ah depict it. So, let us say this will be ah page table of a process. Ah in reality a page table is ah multi-level structure but here I am just drawing the final level let us say ah make it a bit smaller ok. So, let us say this is the ah page table of a crossword these ah rows that we are seeing are ah virtual pages and then ah let us also draw the physical memory.
So, again I will draw a box here and the physical memory is similarly organized by the kernel in the form of frames physical frames each 4 KB in this case and these virtual pages are mapped to ah these frames. Let us say these two pages are mapped at this point of time. Um now let us say there is another process. So, if we draw each page table. And let us say this for processes page or one of its pages virtual pages is mapped to this frame. So, now you can see that two processes are actually sharing this frame. So, this sharing of frames, this sharing of physical frames in the RAM becomes possible due to copy and write.
So, because so, if copy and write did not exist, this kind of sharing would be very difficult to maintain for the kernel. Because what if one of these processes wants to modify or write to this data? So, in that case, if the first process wants to write and if its write happens, then the second process would be reading the wrong data. Because one process's writes are private. Because the process execution model is that every process executes in isolation. So, it executes as if it is the only process running on a system. But in reality, there can be hundreds and thousands of processes running in parallel or contract key. so if and so if one process is reading or writing its own data it is under the assumption that no one else is actually reading or writing the same you know or looking at that data at the same
time so that so this kind of sharing would not be possible without copy and write so now how does copy and write actually enable this kind of sharing so what the kernel does is whenever this kind of sharing happens. So, these page table entries are actually made either so, the kernel usually makes these page table entries as read only. So, which means that any write from one of these processes is actually not going to go through. If any of these processes wants to do a write, the hardware will refuse to do the write because the page table entry says it is a read only page but it would raise a page fault and a page fault is handled by the kernel and when the kernel is handling the page fault it realizes this is copy and write so it makes a copy of this shared frame which is why it's called a copy and write so make a copy on the write so now it has made a copy and whichever process wanted to do this right now it updates its pasteable to point to this new
copy of the frame and now the pasteable entry it also updates the pasteable entry and makes it you know writable. So, it removes the read only restriction. So, now if the first process wants to do a write its write will go to this frame which is a copy and the second process continues to read the original frame. So, that is how copy and write enables sharing of this data in the RAM between multiple processes. And in the last video, we used the example of the mmap system call because that's a very natural use case of copy and write because most you know many times multiple processes are working with the same file So if every processes if that files data was being copied in the RAM for every process that wanted to read or work with that file then it would be a very inefficient utilization of the RAM which is a very limited resource. But if copy and write is there then the kernel can easily share those frames which contain
file data between those processes. So, we will also share ah those frames which contain file data between those processes. And again the same restrictions apply these processes can share as long as they are reading the ah reading the data rather than writing to it. Whenever they have to write then ah a lot of then the kernel has to step in and do a copy and write. So, we discussed all of that in the last video ah. In this video we will ah instead focus on the fork pathway which is slightly different from the m map pathway. So, some differences will be there which is why I wanted to make this video. So, let us start from fork. What fork is? So, fork is a system call which exists on all Unix like operating systems. It is used for creating a new process. So, because it is a system call, so it can be called only by another process. So, if a process is executing then that process can call fork.
So, the process ah that is calling or executing fork system call is called a parent process. So, because this is the process that is actually creating a new process. So, it becomes a parent and ah process that gets created as a result of fork is called the child process and it is a child of the parent ah the parent process. and another reason for calling these as parent and child processes is that because the child process is almost a replica of the parent. So, what do I mean by that? So, the child process inherits the parent's file descriptor table. So, if the parent process had opened a few files, it had opened a few sockets, then the child process also inherits those. It gets a copy of the same file destructor table. And similarly, it also receives a copy of the parent's virtual address space.
So, whatever was the state of the parent's virtual address space, that state, same state has to be copied for the child process as well. So, the child executes almost as if this was, it was, you know, it was the same process. It almost is executing like that. So, when the fourth system call returns back, the child starts executing right from the point after the fourth system call. So, if the parent had, you know, allocated some memory, created a few variables, the child also will get the same state which is why the parents virtual address space also has to be copied for the child. So, that is another thing. So, which again makes the child a copy of the parent and finally, whatever data that the parent process had actually in the RAM, the child process
also needs to have the same data because the child will execute as if it is the parent process as if it is the same process. So, if the parent had let us say created an array and populated it with some data then the child process should also be able to work with the same data but it will be a copy not the same data because these are two independent processes. So, whatever the parent has with its own data should not be visible to the child. These are two independent processes, but the child is a copy of the parent. So, that's why. So, if I try to give an example, you know, in the form of code. So, it would be like this. So, let's say, in my, if I'm in my parent process, let's say, I did something like this. let's say I allocated some memory using malloc and let's say I opened a file
using open and I am not writing all the code here Let us say I did a few things here I allocated some memory using malloc. I opened a file and let us say I also write some data into this array. So, let us say I write the value 42 into the first file of that array. So, let us say I have done all of this and then after that I call false. And now fork returns the process ID of the cross ah of the child process, but it depends ah ah it actually has two ah written values. I mean it depends ah whether it is returning to the parent process or is it returning to the child. So, basically fork fork is a single entry into the kernel and it has to return pathways
back to the user space. So, one return is to the parent process which continues executing right after fork and the other return is back to or to the child process which also starts executing right after the fork. So, here we call fork now it will return to the parent and the child process. So, how do you distinguish is through the PID itself the PID value the return value. So, in the child process the PID value is 0. So this becomes a child process and here you can do whatever you want to do. will be this is ah the child processes context. So, here for example, I can still access everything. So, here I can ah call close on FD1. So, so, you can see that even though the child process
did not open this file, but it can actually ah it will still inherit the same file descriptor table. So, which means ah the fd1 variable whatever value it holds points to the same file, but it is a different its own file descriptor table. It can also read and write that array. So, it can ah modify this or it can ah you can do assert or something you will get ah this will also work. Because ah at this point of time before fork was called the parent had allocated some memory and the child process has to inherit or get a copy of the same address space. So, whatever was the virtual address where this memory was allocated, the same address will be, the child will also get this pointer allocated at the same address. And whatever was the value at that address in the physical memory, the child will also
get a copy of that. So, that is why. So, I mean child simply should be able to continue executing as if just like the parent. So, which is why all of this has to happen or should be possible. Anyway, after and the other else block is the where the parents code resumes. So, basically in the parent the PID variable would hold the child's process ID. So, if the PID value is non-duo which means it means we are in the parent process. So, here anyway we can do you know whatever we want to do. So, here also we can continue to do for example, I can do this. So, here if the parent goes and modifies this first byte and updates it to 84, it does not mean that the child processes assert would fail. because child process
has received a copy of this data rather than sharing that with the parent. So, if the parent modifies it, it does not mean that the parent or the child will read the updated value. The child will still see 42 at that address in the RAM. So, that's the story of 4. So, in theory, the child process
番組の概要欄(原文)
In this video, we look at why fork() needs copy-on-write, how it works inside the kernel, and a memory usage problem that Instagram encountered with Python.
出典・この記事について
- 番組
- Confessions of a Code Addict(Abhinav Upadhyay)
- 元の回
- How and Why fork() Uses Copy-on-Write
- 配信日
- 要約作成日
- 公式サイト
- blog.codingconfessions.com
この要約・解説記事は、元の音声を文字起こしした内容をもとに AI(Claude)が日本語で作成したものです。 固有名詞や数値に誤りを含む場合があるため、正確な内容は元の音声でご確認ください。制作方法について