> For the complete documentation index, see [llms.txt](https://codexpress.gitbook.io/operating-system-showdown/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://codexpress.gitbook.io/operating-system-showdown/components-of-os/system-calls.md).

# System Calls

### System Calls & It's Working&#x20;

System calls are a fundamental part of the **interaction between user-level processes and the kernel** in an operating system. They allow user **processes to request services provided by the kernel, such as file operations, process management, and hardware access**. Switching between user and kernel mode is necessary to maintain security and stability while executing these system calls. Let's dive into these concepts and explore them with examples:

**1. System Calls:**

* **Purpose:** System calls are a way for user-level processes to request privileged services from the operating system's kernel.
* **Examples:**
  * Opening, reading, writing, and closing files (e.g., `open`, `read`, `write`, `close`).
  * Managing processes (e.g., `fork`, `exec`, `exit`).
  * Allocating and deallocating memory (e.g., `malloc`, `free`).
  * Managing devices (e.g., `ioctl` for device control).
* **How it works:** When a user process wants to perform an operation that requires kernel privileges, it makes a system call by invoking a specific function or instruction provided by the operating system API.

**2. Switching Between User and Kernel Mode:**

* **Purpose:** User and kernel modes exist to separate user-level processes from the privileged operations that only the kernel should perform. Switching between these modes ensures that user processes cannot directly access or modify critical system resources.
* **How it is achieved:**
  * **Hardware Support:** Modern CPUs have built-in support for switching between user and kernel modes. They use special CPU instructions, such as `syscall` or `int`, to transition between these modes.
  * **Context Switch:** When a user process makes a system call or encounters an exception, the CPU performs a context switch. This involves saving the state of the user process (registers, program counter, etc.) and loading the state of the kernel.
* **Example:**

  * Consider the `read` system call in a Unix-like operating system. When a user-level program invokes `read`, the CPU switches from user mode to kernel mode, where the kernel reads data from the file and returns it to the user-level program. Once the operation is complete, the CPU switches back to user mode, and the user program continues executing.

  <figure><img src="https://1794968486-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmr8TiLFLTzUjsTWGBqMp%2Fuploads%2FtOXqRjrKo7TJgHtyMXAk%2Fimage.png?alt=media&amp;token=72296472-2b0b-4d8d-a1d9-d55124b22142" alt="" width="375"><figcaption></figcaption></figure>

**3. System Call Interface (SCI):**

* **Purpose:** The System Call Interface (SCI) is a set of functions or instructions that provide a bridge between user-level processes and the kernel. It defines how system calls are invoked by user programs and how the kernel should handle these requests.
* **Example:** In Unix-like systems, the SCI includes C library functions like `open`, `read`, `write`, and `close`. When a user program calls these functions, they internally invoke the corresponding system call to interact with the kernel.

**Example: Reading a File Using the `read` System Call (Unix-like systems):**

```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main() {
    int fd;  // File descriptor
    char buffer[1024];
    ssize_t bytes_read;

    // Open a file in read-only mode
    fd = open("example.txt", O_RDONLY);

    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    // Read data from the file
    bytes_read = read(fd, buffer, sizeof(buffer));

    if (bytes_read == -1) {
        perror("read");
        close(fd);
        exit(EXIT_FAILURE);
    }

    // Close the file
    close(fd);

    // Process the data
    // ...

    return 0;
}
```

In this example, the `open` and `read` functions are part of the SCI. When `read` is called, a system call is made to the kernel, which switches to kernel mode to perform the file read operation. Afterward, it switches back to user mode, and the user program continues executing.

<figure><img src="https://1794968486-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmr8TiLFLTzUjsTWGBqMp%2Fuploads%2FSgmXOzQS0Zv7R8H5YkB6%2Fimage.png?alt=media&amp;token=3417a28f-7493-4544-aac5-75bbd0af6693" alt="" width="433"><figcaption></figcaption></figure>

### Types of System Calls

System calls in an operating system provide a way for user-level processes to request services from the kernel. These services encompass a wide range of operations that interact with hardware, manage processes, access files, and perform other essential tasks. Here are some common types of system calls in an operating system:

1. **Process Control:**
   * `fork()`: Create a new process.
   * `exec()`: Replace the current process with a new one.
   * `wait()`: Wait for a child process to terminate.
   * `exit()`: Terminate the current process.
2. **File Management:**
   * `open()`: Open a file or create a new one.
   * `close()`: Close an open file.
   * `read()`: Read data from a file.
   * `write()`: Write data to a file.
   * `seek()`: Move the file pointer to a specific location in a file.
   * `rename()`: Rename a file.
   * `unlink()`: Delete a file.
3. **Device Management:**
   * `read()`: Read data from a device.
   * `write()`: Write data to a device.
   * `ioctl()`: Perform device-specific control operations.
   * `open()`: Open a device.
   * `close()`: Close a device.
4. **File and Directory Operations:**
   * `mkdir()`: Create a new directory.
   * `rmdir()`: Remove a directory.
   * `chdir()`: Change the current working directory.
   * `getcwd()`: Get the current working directory.
   * `stat()`: Get information about a file or directory.
   * `chmod()`: Change file permissions.
   * `chown()`: Change file ownership.
5. **Communication:**
   * `pipe()`: Create a pipe for interprocess communication.
   * `socket()`: Create a network socket.
   * `connect()`: Establish a connection to a network socket.
   * `send()`: Send data over a network socket.
   * `recv()`: Receive data from a network socket.
6. **Time Management:**
   * `time()`: Get the current time.
   * `sleep()`: Suspend a process for a specified period.
   * `alarm()`: Set an alarm to receive a signal after a specified time.
7. **User and Group Management:**
   * `getuid()`: Get the user ID of the calling process.
   * `getgid()`: Get the group ID of the calling process.
   * `setuid()`: Set the user ID of the calling process.
   * `setgid()`: Set the group ID of the calling process.
8. **Memory Management:**
   * `brk()`: Change the end of a process's data segment.
   * `mmap()`: Map files or devices into memory.
9. **Signal Handling:**
   * `kill()`: Send a signal to a process or group of processes.
   * `signal()`: Set a signal handler for a specific signal.
10. **Resource Management:**
    * `getrlimit()`: Get resource limits.
    * `setrlimit()`: Set resource limits.
11. **Networking (Socket API):**
    * Functions like `bind()`, `listen()`, `accept()`, and `connect()` for network socket operations.

These system calls provide a standardized interface for user programs to interact with the underlying operating system and perform various tasks. Different operating systems may have additional or slightly different system calls to support their specific features and functionalities.
