System calls in Operating System

Aditya LadAditya Lad
2 min read

What is a System Call?

  • It is a method for a program to request a service from an operating system.

  • It is a method of interacting with the operating system via programs.

  • The Kernel system can only be accessed via system calls.

  • It is required for any program that uses resources.


Need of System Call

  • When file system wants to create, read, write and delete a file.

  • Network connections need them to send and receive data packets.

  • For accessing hardware devices like printer, scanner, etc.

  • For creating and managing new resources.


Working of System Call

  • When application creates a system call, it will first obtain permission from kernel.

  • It achieves this using an interrupt request, which pauses the current process and transfers control to the kernel.

  • Kernel executes requests, passes output to application, which resumes upon input reception.

  • When the operation is finished, the kernel returns the results to the application.

  • Modern operating system are multi-threaded, hence they can handle various system calls at same time.


Types of System Call

  1. Process control

    Used to direct the processes. Ex. load, abort, create, end, execute, terminate, etc.

  2. File Management

    Used to handle the files. Ex. create, delete, open, close, read, write.

  3. Device Management

    Used to deal with devices. Ex. read, write, get, delete.

  4. Information Maintenance

    Used to maintain information. Ex. getData, setData.

  5. Communication

    Used for communication. Ex. createConnection, deleteConnection, sendMessage, receiveMessage.

Example

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>


int main() {

    write(STDOUT_FILENO, "Hello, world!\n", 14);
    int fd = open("example.txt", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);
    if (fd == -1) {
        perror("open");
        return 1;
    }


    const char *text = "Aditya Lad.\n";
    ssize_t bytes_written = write(fd, text, strlen(text));
    if (bytes_written == -1) {
        perror("write");
        close(fd);
        return 1;
    }


    close(fd);


    char buffer[100];
    fd = open("example.txt", O_RDONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    ssize_t bytes_read = read(fd, buffer, sizeof(buffer));
    if (bytes_read == -1) {
        perror("read");
        close(fd);
        return 1;
    }

    write(STDOUT_FILENO, buffer, bytes_read);
    close(fd);

    return 0;
}

This code uses write, open, read and close system call.

0
Subscribe to my newsletter

Read articles from Aditya Lad directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aditya Lad
Aditya Lad