🧠 What are System Calls in Linux?

πŸ“Š Visual Understanding

Image

Image

Image

Image


⚑ Simple Definition

A system call is a way for a program (user space) to request services from the Linux kernel.

πŸ‘‰ Because:

  • Apps cannot directly access hardware

  • Only the kernel has full control

So apps say:

β€œKernel, please do this for me”


πŸ” Real-Life Analogy

Think of it like this:

  • πŸ‘¨β€πŸ’» You (user/app)

  • πŸ§‘β€πŸ³ Waiter (system call interface)

  • πŸ‘¨β€πŸ³ Kitchen (kernel)

πŸ‘‰ You don’t go into the kitchen directly
πŸ‘‰ You place an order via waiter β†’ kitchen executes


πŸ”§ Why System Calls Exist

Without system calls:

  • Apps could directly access hardware ❌ (dangerous)

  • System would crash easily ❌

  • No security ❌

πŸ‘‰ System calls ensure:

  • βœ… Security

  • βœ… Stability

  • βœ… Controlled access


🧱 How System Calls Work (Step-by-Step)

Example: cat file.txt

  1. You run command β†’ cat

  2. cat needs to read file

  3. It makes a system call β†’ read()

  4. Kernel:

  • Checks permissions

  • Reads file from disk

  1. Kernel returns data β†’ app prints it

πŸ”₯ Flow:

User App β†’ System Call β†’ Kernel β†’ Hardware β†’ Response β†’ App

πŸ“‚ Types of System Calls (Important for Interviews)

1. File Management

  • open(), read(), write(), close()

πŸ‘‰ Used when:

  • Reading logs

  • Writing files


2. Process Management

  • fork(), exec(), exit(), wait()

πŸ‘‰ Example:

  • Running any command β†’ new process created

3. Device Management

  • Interacting with hardware (disk, printer, etc.)

4. Information Management

  • getpid(), getuid()

πŸ‘‰ Used to get system/process info


5. Communication (IPC)

  • Pipes, shared memory, sockets

πŸ‘‰ Used in:

  • Microservices

  • Network apps


🧠 Important Concepts

πŸ”Ή User Mode vs Kernel Mode

ModeDescription
User ModeApps run here (restricted)
Kernel ModeFull access (danger zone)

πŸ‘‰ System call = switch from user mode β†’ kernel mode


πŸ”Ή Context Switching

  • CPU switches between user & kernel

  • Slight overhead (important in performance tuning)


πŸ”₯ DevOps-Level Examples

1. Reading Logs

cat /var/log/syslog

πŸ‘‰ Internally:

  • open() β†’ read() β†’ close()

2. Running a Command

ls

πŸ‘‰ Internally:

  • fork() β†’ exec()

3. Network Call

curl google.com

πŸ‘‰ Uses:

  • socket(), connect(), send(), recv()

πŸ§ͺ How to SEE System Calls (VERY IMPORTANT)

Use:

strace ls

πŸ‘‰ Output shows:

  • All system calls used by ls

Example:

open("/etc/ld.so.cache", O_RDONLY)
read(3, ...)

πŸ’‘ This is how real debugging is done