💾 Archived View for yujiri.xyz › software › guide › syscalls.gmi captured on 2023-06-16 at 16:54:48. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2023-03-20)
-=-=-=-=-=-=-
Learn programming for good instead of profit
So, normally your operating system kernel monopolizes access to most of your hardware, including your storage disk. Every other process is stuck in a little box where it can only access its own assigned region of memory. To do anything outside "itself", like draw something on the screen, read input, or save a file, it needs to call the kernel to do it for it. This is called a syscall (system call). There are a couple hundred syscalls on Linux, but here are some of the most important ones:
The others probably look intuitive enough, but you might wonder what `close` really does and why it's necessary. There are a couple of parts to the answer.
The kernel keeps track of something called a file descriptor table for each running process. This table tells it which file descriptor number corresponds to which file on disk. When a process opens a file, the kernel adds an entry to the file descriptor table for that process. This requires it to allocate memory to store the new entry in the table. The kernel can't free that memory until you use the `close` syscall on that file descriptor (or the program exits). If a program keeps opening files but never closes them, memory usage will keep going up and never go down, which is called a memory leak.
Another reason is that when you use the `write` syscall, the kernel doesn't actually necessarily write the data immediately. Actually writing data to the disk is relatively expensive. So, the kernel might just keep the written data in a temporary in-memory buffer for a while, until there's more of it to write. If the process that called `write` exits without ever calling `close`, the data might not actually get saved. (There is also a syscall called `sync` that makes sure everything written is really written, but without closing the file descriptor.)
When you call `close`, the kernel will make sure all the data you wrote is actually written, since it knows there won't be any more.