yujiri.xyz

Software

Learn programming for good instead of profit

What is a syscall?

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 read or write a file, it needs to ask 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:

Why do we need to close files?

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. 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. (There is also a syscall called `sync` that makes sure everything is really written, but without closing the file.)

Proxied content from gemini://yujiri.xyz/software/guide/syscalls.gmi

Gemini request details:

Original URL
gemini://yujiri.xyz/software/guide/syscalls.gmi
Status code
Success
Meta
text/gemini; lang=en
Proxied by
kineto

Be advised that no attempt was made to verify the remote SSL certificate.

What is Gemini?