今日已更新 317 条资讯 | 累计 37222 条内容
关于我们

What Linux actually does when you read a file

Valentyn Kit 2026年08月08日 01:53 9 次阅读 来源:Dev.to

I asked Linux for one 4 KiB page from the start of a cold file. Four pages came back. I moved the same read one page further in, ran it again, and got one. Same file, same syscall, same kernel. The only thing that changed was where I started reading, and I spent twenty minutes assuming the tool I'd just written was miscounting. It wasn't. A read that starts at byte zero is treated as a promise. There's a branch in mm/readahead.c that reads, in full, if (!index) goto initial_readahead; . Offset zero means the kernel takes you for a program that's about to stream the whole file, and it fetches ahead immediately. Start anywhere else and you're assumed to be seeking randomly until a pattern proves otherwise. Nothing in my call said a word about my intentions. It inferred them from an offset. I spent two weeks on this sort of thing recently. Not for work, and not toward anything shippable. The short version of what I found is that a surprising amount of the machinery under a running program isn't carrying out instructions at all. It's guessing. The bench , because it changes how you should read every number here: an ext4 filesystem on a loop device, inside an OrbStack Linux VM on an Apple Silicon Mac, kernel 7.0.14, 4 KiB pages, read_ahead_kb at 128. That's a container sharing the host's kernel, not bare metal, and the host reclaims memory aggressively enough that a fully cached file can go cold in fifteen seconds. Reads came from dd ; the page-by-page counting came from a small C tool I wrote that mmap s a file and asks mincore() which of its pages are resident. You're not addressing the disk, you're addressing the page cache The model most of us carry is that read() goes and gets bytes off a device. It doesn't. It copies bytes out of the page cache into your buffer, and the page cache is just RAM the kernel uses to remember parts of files. If what you want is already there, no device is involved. If it isn't, the kernel fills the cache first and then copies. Either way

本文内容来源于互联网,版权归原作者所有
查看原文