📞 系统调用:程序找操作系统的“前台”📞 System Call: Programs Ring the OS Front Desk
上一片里,硬盘冒充内存,摆下更多程序。可程序想读文件、想上网,能自己动手吗?不能,得先给前台打电话。Last leaf, the disk pretended to be memory, fitting more programs on the table. But when a program wants to read a file or go online, may it just help itself? No — it must first call the operating system's front desk.
第 1 步:客人不能进后厨Step 1: Guests may not enter the kitchen
先看清餐厅的两块地盘,再说谁能碰啥。First see the restaurant's two zones — then decide who may touch what.
左边客人区,叫用户态。只能动自己桌上的东西。算个数、改内存里的数字,都行。右边后厨,叫内核态。硬盘网络屏幕,全归内核管。门上写着:客人止步。想碰硬件,先按铃。The dining room on the left is user mode. You may only touch things on your own table. Arithmetic, or changing numbers in memory — all fine. The kitchen on the right is kernel mode. Disk, network and screen all belong to the kernel. The door reads: staff only. To touch hardware, ring the bell first.
铃按下去后,一道菜是怎么上桌的?After the bell rings, how does a dish reach the table?
第 2 步:按铃四步,请前台代办Step 2: Four steps of a ring — let the front desk handle it
程序想读菜谱.txt,按下 read 铃。CPU 切进内核态,前台来接单。先查权限,再去硬盘取文件。最后把结果端回桌上。程序没碰过硬盘,却吃到了菜。The program wants recipes.txt, so it rings the read bell. The CPU steps into kernel mode, and the front desk takes the order. First it checks permission, then fetches the file from the disk. Finally the result is served back to the table. The program never touched the disk — yet got its dish.
一次铃只办一件事,日常程序按多少次?One ring handles one job — how many rings does an everyday program make?
第 3 步:说声“你好”,按铃几十次Step 3: Saying "hello" rings the bell dozens of times
屏幕上打印一行 Hello,背后按铃几十次。启动、打开、读、写、退出,一样不少。strace 是计数器,铃声全记下:execve、open、read、write、exit。API 是电话号码本,帮你按对铃。权限不够,前台拒绝,这就是沙盒。Printing one line of Hello hides dozens of rings. Start up, open, read, write, exit — none missing. The strace counter writes down every ring: execve, open, read, write, exit. APIs are a phone book that helps you ring the right bell. Wrong permission, and the front desk refuses — that is the sandbox.
🎮 自己做,还是按铃?(30 秒)🎮 Mini-game: do it yourself, or ring the bell? (30 seconds)
道理讲完了,先看一次按铃进出后厨。再判 6 个操作:自己做,还是按铃?Theory done. First watch one ring go in and out of the kitchen. Then judge 6 actions: do it yourself, or ring the bell?
一句话记住它:系统调用 = 程序请内核代办的按铃。自己桌上的自己做,碰硬件就进后厨。Remember it in one line: a system call is the bell a program rings for the kernel's help. Your own table, your own hands; hardware, ask the kitchen.
用户态动桌上东西,内核态才能碰硬件User mode touches your own table; only kernel mode touches hardware读文件按 read 铃:切态、查权限、取数据、端回结果Reading a file rings read: switch mode, check permission, fetch data, serve it backAPI 是号码本;权限不够被拒绝,就是沙盒APIs are the phone book; denied permission is the sandbox
内容参考 OpenStax 等公开教材,多来源核对 · AI 生成、人工审核 · 发现错误欢迎指正,帮这片叶子长得更好。Based on OpenStax and other open textbooks, cross-checked across sources · AI-generated, human-reviewed · Spotted a mistake? Tell us — help this leaf grow.