System Calls Explained | Interface Between Programs & Operating System Kernel

System Calls Explained | Interface Between Programs & Operating System Kernel

⚙️ System Calls Explained (The Interface Between User Programs & the OS Kernel)

A system call is a request made by a user program to the operating system kernel to perform a privileged operation on its behalf. System calls provide a controlled and secure way for user-mode applications to access hardware resources, manage processes, and interact with the file system. In this guide, you will learn how system calls work, the different types, and real-world examples.

👉 System Call = Request from user program → OS Kernel → Privileged operation → Return result to user program. System Calls provide controlled access to OS services like files, processes, memory, and hardware.

📘 What is a System Call?

A system call is a protected gateway that allows user-mode programs to request services from the operating system kernel. User programs cannot directly access hardware or perform privileged operations, so they must use system calls to:

  • Read/write files and interact with the file system.
  • Create and manage processes.
  • Allocate and manage memory.
  • Communicate over networks.
  • Access hardware devices (printers, network cards, etc.).

✔ Key Characteristics

  • Requires transition from user mode to kernel mode.
  • Validated by the kernel for security and correctness.
  • Executes privileged instructions on behalf of the user program.
  • Returns control to user mode with the result.
  • Adds performance overhead due to context switching.

⚙️ How System Calls Work

System calls follow a specific flow that involves transitions between user mode and kernel mode:

  1. User Program: Application in user mode calls a library function (e.g., read()).
  2. System Call Wrapper: Library prepares arguments and invokes the system call.
  3. Trap to Kernel: A software interrupt (trap) switches CPU from user mode to kernel mode.
  4. Kernel Services: The OS kernel validates the request and performs the privileged operation.
  5. Return to User: Kernel returns the result to the user program and switches back to user mode.

This mode switching and context preservation ensures security and stability.

📊 Types of System Calls

1. Process Control System Calls

Manage process creation, termination, and execution.

  • fork() - Create a new process.
  • exec() - Execute a program, replacing current process image.
  • wait() - Wait for a child process to terminate.
  • exit() - Terminate the current process.
  • getpid() - Get process identifier.

2. File Management System Calls

Interact with the file system and manage files.

  • open() - Open a file or device.
  • close() - Close a file descriptor.
  • read() - Read data from a file.
  • write() - Write data to a file.
  • unlink() - Delete a file.

3. Device Management System Calls

Control hardware devices and request device-specific operations.

  • ioctl() - Send device control commands.
  • read() - Read from a device.
  • write() - Write to a device.
  • mmap() - Map device memory into process address space.

4. Information Maintenance System Calls

Retrieve system and process information.

  • getpid() - Get process ID.
  • getuid() - Get user ID.
  • time() - Get current time.
  • stat() - Get file information.

5. Communication System Calls

Enable inter-process communication and networking.

  • pipe() - Create a pipe for IPC.
  • socket() - Create a network socket.
  • send() - Send data over a socket.
  • recv() - Receive data from a socket.
  • msgget() - Create a message queue.

6. Protection System Calls

Manage permissions and access control.

  • chmod() - Change file permissions.
  • chown() - Change file owner.
  • umask() - Set file creation permission mask.

📊 Common System Calls Reference

System CallCategoryDescription
read()File ManagementRead data from a file or device
write()File ManagementWrite data to a file or device
open()File ManagementOpen a file or device
close()File ManagementClose a file or device
fork()Process ControlCreate a new process
exec()Process ControlReplace process with new program
wait()Process ControlWait for child process
exit()Process ControlTerminate calling process
getpid()InformationGet process ID
socket()CommunicationCreate network socket
chmod()ProtectionChange file permissions

🔄 System Call Flow (Detailed)

  1. User Program: Application running in user mode calls a library function (wrapper).
  2. Library Prepares Arguments: The C library (libc) prepares system call arguments and sets up registers.
  3. Software Interrupt (Trap): A special CPU instruction (e.g., int 0x80 on x86 or syscall) triggers a trap.
  4. CPU Mode Switch: CPU switches from user mode to kernel mode.
  5. Kernel Trap Handler: Kernel's trap handler intercepts the call and validates it.
  6. Kernel Execution: Kernel performs the requested privileged operation.
  7. Return Value: Kernel places the result in a register.
  8. Mode Switch Back: CPU switches from kernel mode back to user mode.
  9. User Program Continues: Control returns to the user program with the system call result.

👨‍💻 Real-World System Call Examples

Example 1: Opening and Reading a File

#include <fcntl.h>
#include <unistd.h>

int fd = open("/path/to/file", O_RDONLY);  // System call
char buffer[100];
read(fd, buffer, sizeof(buffer));           // System call
close(fd);                                    // System call
  

Each function (open(), read(), close()) is a system call that transitions to kernel mode.

Example 2: Creating a Process

pid_t pid = fork();     // System call: create new process
if (pid == 0) {
  // Child process
  execve("/bin/ls", args, env);  // System call: execute program
} else {
  // Parent process
  wait(NULL);             // System call: wait for child
}
  

fork() creates a new process, execve() replaces it with a new program, and wait() waits for completion.

Example 3: Network Communication

int sock = socket(AF_INET, SOCK_STREAM, 0);  // System call
connect(sock, &addr, sizeof(addr));           // System call
send(sock, data, length, 0);                  // System call
recv(sock, buffer, size, 0);                  // System call
close(sock);                                   // System call
  

All network operations require system calls to access the network stack.

🛡️ Security & System Calls

System calls are critical for security. The kernel validates every request to ensure:

  • Access Control: User processes cannot access other processes' memory or files without permission.
  • Resource Limits: Processes are limited in CPU time, memory, and file descriptors they can use.
  • Operation Validation: Kernel checks that requested operations are legal and safe.
  • Privilege Enforcement: Privileged operations (like disk I/O) cannot be performed directly by user programs.

⚡ System Call Performance Considerations

System calls have measurable performance overhead due to:

  • Context Switching: Saving and restoring CPU context (registers, stack) between modes.
  • Mode Transition: CPU switching between user and kernel mode.
  • Kernel Validation: Kernel must validate arguments and access permissions.
  • TLB Flush: Translation lookaside buffer may need to be flushed.

Modern systems minimize this overhead, but system calls are slower than regular function calls. Applications that make excessive system calls (e.g., reading one byte at a time) suffer performance penalties.

🔗 Internal Links

Learn more about related OS topics:

Kernel vs User Mode | Process Management | File System Explained | Interrupts Explained

🎯 Key Takeaways

  • System calls are the interface between user programs and the OS kernel.
  • They provide controlled access to privileged operations and hardware.
  • Every system call involves a transition from user mode to kernel mode.
  • The kernel validates all requests for security and correctness.
  • System calls have performance overhead, so minimize their usage in performance-critical code.
  • Understanding system calls is essential for systems programming and OS design.

📝 10 System Calls MCQs

1. What is a system call?
2. Which mode does the CPU switch to when a system call is invoked?
3. Which of the following is a process control system call?
4. What does the fork() system call do?
5. Which system call is used to open a file?
6. What is the main reason for system call overhead?
7. Which of the following is a file management system call?
8. What does the exec() system call do?
9. Which system call is used for inter-process communication?
10. Why does the kernel validate system call requests?

❓ FAQ

Are all library functions system calls?
No. Library functions like strlen() or printf() execute in user mode. Only functions that request kernel services (like read(), write()) are system calls.

Can I make system calls directly?
Yes, but it's rare. Most programs use C library wrappers. Direct system calls require assembly language on most systems.

How many system calls are there?
Linux has 300+ system calls. Windows has hundreds. The exact number varies by OS and version.

Popular posts from this blog

Indecision Candle Meaning

Indecision at Key Levels (Reversal Signal)

Understanding Indecision in Depth