System Calls and APIs

How programs talk to the operating system?

The tools they use are called System Calls and APIs.

Why Do We Need Them?

Programs cannot do everything on their own.

They need help from the operating system (OS).

πŸ› οΈ Example: A text editor wants to save a file. It can't do that alone. It asks the OS: "Please save this file for me."

System calls and APIs help the program ask for things from the OS.

What is a System Call?

A system call is a request from a program to the operating system.

It asks the OS to do something important.

Only the OS can directly talk to hardware, like the disk or memory.

Examples of System Calls:

πŸ“ž Think of it like a phone call: Your program "calls" the OS to get something done.

What is an API?

API stands for Application Programming Interface.

It’s a set of functions that make system calls easier to use.

The API is like a friendly middleman between the program and the OS.

Real-Life Example:

πŸ§‘β€πŸ³ You want a pizza. Instead of calling the chef directly, you use a waiter (API). The waiter knows how to speak to the kitchen (OS).

In C, the standard library gives you API functions like fopen(), fprintf(), and fclose().

These functions use system calls like open(), write(), and close() inside.

System Call Flow

Here's what happens when a system call is made:

  1. The program wants to do something (e.g., read a file).
  2. It calls an API like fread().
  3. The API makes a system call like read().
  4. The system call enters kernel mode.
  5. The OS talks to the hardware (e.g., reads the file).
  6. The result is sent back to the program.

User Mode vs Kernel Mode

System calls switch the program from user mode to kernel mode.

In kernel mode, the OS can safely access hardware and memory.

πŸšͺ Example: It’s like knocking on a locked door (user mode). The owner (OS) lets you in and helps you (kernel mode).

Types of System Calls

Why Not Use System Calls Directly?

System calls are hard to use.

They are different on each OS.

APIs are easier and the same across many systems.

Example:

// Using system call (Linux)
int fd = syscall(SYS_open, "file.txt", O_RDONLY);

// Using API
FILE *fp = fopen("file.txt", "r");

Summary

πŸ“š Key Terms

🧠 Practice Time!

Try writing a simple C program that opens a file, writes some text, and closes it using API functions like fopen(), fprintf(), and fclose().

Great work! You now understand how programs get help from the OS using system calls and APIs. πŸŽ‰

s