0% found this document useful (0 votes)
24 views46 pages

What Is An Operating System (OS) AnswerAn Operating System

Uploaded by

Mayank Fulara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views46 pages

What Is An Operating System (OS) AnswerAn Operating System

Uploaded by

Mayank Fulara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

1. What is an Operating System (OS)?

An Operating System (OS) is essential system software that acts as


an intermediary between computer hardware and users. It manages
hardware components such as the CPU, memory, input/output
devices, and provides services that allow users to run applications.
The OS ensures that applications can run efficiently and that the
hardware resources are utilized effectively. It manages multiple
processes, handles memory allocation, maintains file systems,
controls peripheral devices, and ensures security and access
permissions. Examples of OS include Windows, Linux, macOS, and
Android.

2. What are the key functions of an Operating System?


The Operating System performs several key functions:
a. Process Management: It creates, schedules, and terminates
processes. It ensures that multiple processes can execute
concurrently through multitasking and manages CPU time
among processes.
b. Memory Management: It allocates and deallocates memory
space as needed by processes. The OS tracks memory usage
and ensures that multiple processes can run without
interference by utilizing techniques like paging and
segmentation.
c. File System Management: The OS manages file storage,
organization, access, and permissions. It provides a
hierarchical directory structure to help users organize files.
d. Device Management: It controls and manages the operation of
hardware devices like printers, disk drives, and network cards
through device drivers.
e. Security and Access Control: The OS enforces security
policies to ensure unauthorized users do not access the system
or sensitive data.
f. User Interface: Provides interfaces like command-line or
graphical user interfaces (GUI) to enable user interaction with
the system.

3. Explain Simple Batch Systems.


Simple Batch Systems are one of the earliest types of operating
systems used in the 1960s. In these systems, jobs (or tasks) are
collected in batches and executed sequentially without user
interaction. Users submit jobs, often in the form of punch cards, to a
central operator, and these jobs are processed one after the other.
The OS in a batch system does not provide real-time feedback or
interaction. The key goal is to automate job execution to reduce idle
time and increase throughput. However, these systems had
drawbacks, such as the inability to respond to changes during
execution and inefficient CPU utilization.

4. What are Multi-programmed Batch Systems?


Multi-programmed Batch Systems are an advancement over simple
batch systems. In these systems, the OS keeps several jobs in
memory simultaneously. When one job needs to wait for I/O
operations, the CPU can switch to another job, thus maximizing CPU
utilization. This improves system efficiency by allowing multiple jobs
to make progress concurrently, reducing idle time. Multi-programming
is the foundation of modern multi-tasking operating systems.
However, in batch systems, user interaction is still limited, and jobs
are processed without real-time feedback.

5. What are Time-Sharing Systems?


Time-Sharing Systems are designed to allow multiple users to
interact with the system simultaneously. The OS allocates CPU time
slices to each user or process, allowing multiple tasks to be executed
concurrently. Users interact with the system via terminals, and the OS
switches rapidly between users’ processes, creating the illusion that
all processes are running at the same time. Time-sharing systems
introduced the concept of multitasking and responsiveness,
significantly improving interactivity compared to earlier batch
systems. This concept is commonly used in modern multi-user
environments like mainframes or servers.

6. What is a Personal Computer System?


A Personal Computer System refers to an OS that is designed for
individual users. These systems are user-friendly, support multiple
applications, and are typically found on desktops and laptops.
Personal computer systems include familiar operating systems such
as Microsoft Windows, macOS, and Linux distributions. They provide
an intuitive graphical user interface (GUI), handle various peripheral
devices, and support networking, security, and multimedia
capabilities. Personal computers revolutionized computing by making
powerful hardware and software accessible to everyday users.

7. What are Parallel Systems?


Parallel Systems utilize multiple processors working together to
execute tasks simultaneously. These systems divide a program or
task into smaller sub-tasks, each executed by different processors.
Parallelism can increase computational power, allowing faster
processing for complex tasks like scientific simulations, big data
processing, or AI calculations. Parallel systems can be classified into
symmetric multiprocessing (SMP), where all processors share
memory, or distributed memory systems, where each processor has
its own memory. Parallel systems are widely used in high-
performance computing environments.
8. What are Distributed Systems?
Distributed Systems consist of a collection of independent computers
that work together as a unified system. These computers
communicate over a network, sharing resources and processing
power. The main advantage of distributed systems is fault tolerance,
scalability, and the ability to share and distribute data across multiple
systems. Examples of distributed systems include cloud computing
platforms, where resources are spread across multiple data centers,
or systems like Google’s search infrastructure, where large-scale
computations are distributed across many machines.

9. What are Real-Time Systems?


Real-Time Systems are designed to handle tasks where time
constraints are critical. They guarantee that tasks are completed
within a specified deadline, often in response to external events.
Real-time systems can be classified as hard real-time systems,
where missing a deadline could result in system failure (e.g., in
pacemakers, anti-lock brakes), or soft real-time systems, where
deadlines are important but not critical (e.g., in video streaming).
Real-time systems are crucial in environments like industrial
automation, medical devices, and aviation control systems.

Introduction to Linux
1. What is the Architecture of the Linux Operating System?
The Linux Operating System has a layered architecture, with each
layer interacting with the ones adjacent to it. The core of the Linux OS
is the kernel, which manages hardware resources, processes,
memory, and device drivers. Above the kernel are the system
libraries that provide functionalities like file manipulation and I/O
operations. System utilities provide additional functionalities such as
file management, user management, and system monitoring tools.
The top layer consists of user applications, including desktop
environments, command-line tools, and software applications.

2. Explain the Basic Directory Structure of Linux.


Linux follows a hierarchical directory structure, with the root directory
/ at the top.
a. /bin: Contains essential binary executables like ls, cp, mv.
b. /home: Stores user-specific files and directories. Each user has
a separate home directory under /home/username.
c. /etc: Holds configuration files for the system and installed
applications.
d. /var: Contains variable files like logs and temporary files.
e. /usr: Holds user-installed programs and libraries.
The directory structure is crucial for the organization of the file
system and ensures modular management of files and
directories.

3. What are the functions of the man, info, and help


commands in Linux?
a. man (manual pages): Provides documentation about Linux
commands, explaining how to use them, their options, and
syntax. For example, man ls will display the manual page for
the ls command.
b. info: Similar to man, but provides more detailed documentation
and cross-referencing between topics. It often includes more
extensive tutorials.
c. help: Displays basic help for shell built-in commands. For
example, help cd will show basic usage information about the
cd command.
4. What are basic Linux directory navigation commands?
a. cd: Changes the current directory. For example, cd
/home/user navigates to the /home/user directory.
b. pwd: Displays the current directory’s full path. For example, if
the current directory is /home/user, typing pwd will output
/home/user.
c. ls: Lists files and directories within the current directory.
Options like ls -l show detailed information, including file
permissions, owner, and file size.

5. What are file manipulation commands in Linux?


a. cp: Copies files from one location to another. For example, cp
file1 /home/user/ copies file1 to the /home/user/
directory.
b. mv: Moves or renames files. For example, mv file1 file2
renames file1 to file2.
c. rm: Deletes files. For example, rm file1 deletes file1 from
the file system.
d. cat: Concatenates and displays file content. For example, cat
file1 displays the contents of file1.

6. What are system information commands in Linux?


a. who: Displays users currently logged into the system.
b. whoami: Displays the current user’s name.
c. hostname: Displays the hostname of the machine.
d. uname: Displays system information, including the kernel name,
version, and architecture. For example, uname -a provides
detailed system information.

Vi Editor

1. What are the three modes of the Vi Editor?


a. Command mode: This is the default mode when you open Vi.
In this mode, you can navigate within the text and execute
commands like deleting lines, copying text, and undoing
changes. You cannot edit text directly in this mode.
b. Insert mode: You enter Insert mode by pressing i, and in this
mode, you can input and edit text. Press Esc to return to
Command mode after making changes.
c. Last-line mode: Accessed by pressing : from Command
mode. In this mode, you can enter commands for saving,
quitting, searching, and replacing text.

2. How do you write and save a file in Vi?


To write and save a file in Vi:
a. Enter Command mode by pressing Esc.
b. Type :w to save the file.
c. To save and quit at the same time, type :wq.
d. If you want to quit without saving, type :q!.

3. How do you execute a shell script in Vi Editor?


a. Open Vi and write the shell script in Insert mode.
b. Save the script using :w and quit using :q!.
c. Make the script executable by using the command chmod +x
scriptname.sh.
d. Run the script by typing ./scriptname.sh in the terminal.

Unit – 1
1. Explain multiprogramming ,time sharing, distributed
system and real time system in terms of memory
management, process management and processor
scheduling.
1. Multi-programming Systems

Memory Management:

In multi-programming systems, multiple processes are loaded into the main


memory simultaneously, allowing the CPU to switch between them as
needed. The OS uses memory management techniques like segmentation
or paging to divide memory into segments or pages and allocate memory
to different processes. Swapping is also employed, where processes are
swapped in and out of memory to make room for others. The goal is to
maximize CPU utilization and reduce idle time.

Process Management:

The OS in multi-programming systems handles multiple processes


concurrently. When one process is waiting for I/O operations, the OS can
switch the CPU to another process that is ready to execute. Context
switching is used to store the state of the current process and load the
state of the next one. The OS manages the process life cycle (creation,
execution, termination) and tracks process states (e.g., ready, running,
waiting).

Processor Scheduling:

Processor scheduling in multi-programming systems focuses on


maximizing CPU efficiency. Long-term scheduling decides which
processes are admitted to the system for processing, while short-term
scheduling selects which process will use the CPU next. The CPU
scheduler may use algorithms like First-Come, First-Served (FCFS),
Shortest Job Next (SJN), or Round Robin to determine the order of
execution. The scheduler aims to keep the CPU busy by assigning
processes that are ready to run.

2. Time-Sharing Systems

Memory Management:
Time-sharing systems allow multiple users to interact with the system
simultaneously, each getting a time slice of the CPU. The OS uses
techniques like virtual memory, where processes are given the illusion of
having more memory than what is physically available. This is achieved by
swapping data between the main memory and the disk. Each user’s
program is loaded into memory using paging or segmentation, and the
system manages memory allocation efficiently to avoid overlap between
users.

Process Management:

Processes in time-sharing systems are managed in a way that ensures


fairness among users. Each user’s process gets a time slice, and the OS
ensures that the system switches between processes frequently to create
the illusion that all users are running their processes simultaneously. The
OS must manage multiple user sessions, track user processes, and
handle their I/O requests.

Processor Scheduling:

In time-sharing systems, processor scheduling is crucial for ensuring that


each user gets a fair share of CPU time. The OS typically uses Round
Robin scheduling, where each process is given a time slice (or quantum),
and the CPU switches to the next process once the time slice is over. The
scheduler must minimize response time to maintain a good user
experience, balancing between multiple processes while ensuring that no
process monopolizes the CPU.

3. Distributed Systems

Memory Management:

In distributed systems, memory management is decentralized since


multiple independent computers are working together. Each computer
(node) has its own memory, and the OS manages the local memory. In
some cases, distributed shared memory (DSM) may be implemented,
allowing processes to access memory across multiple nodes as if it were a
single memory space. The OS must ensure data consistency and
coherence across nodes, which can be challenging due to the distributed
nature of memory.

Process Management:

Processes in distributed systems can be spread across different machines.


The OS must manage processes running on various nodes, handle
communication between them, and coordinate their execution. Inter-
process communication (IPC) mechanisms, such as message passing,
are used for processes on different machines to interact. The OS also
needs to deal with process synchronization and failure recovery since
processes may run on systems that could fail independently.

Processor Scheduling:

Processor scheduling in distributed systems is more complex because


multiple processors across different nodes need to be coordinated.
Scheduling is done both locally (on individual nodes) and globally (across
the distributed system). Load balancing becomes critical to ensure that no
node is overwhelmed while others remain idle. The OS may use algorithms
to distribute the load of processes across different nodes and adjust
dynamically based on the system’s performance and resource availability.

4. Real-Time Systems

Memory Management:

In real-time systems, memory management is deterministic, meaning that


the time it takes to allocate and access memory must be predictable. Real-
time systems typically avoid using virtual memory due to its unpredictable
delays, and instead, they allocate physical memory to processes to
guarantee fast, real-time access. The OS may also pre-load data into
memory to avoid delays caused by loading data during process execution.

Process Management:
Process management in real-time systems is focused on ensuring that
processes meet their strict deadlines. Processes are prioritized based on
their urgency, with higher-priority processes preempting lower-priority
ones. The OS must ensure that critical tasks are completed within their
time constraints, often using techniques like priority inheritance to prevent
priority inversion (where a lower-priority process holds up a higher-priority
one). The OS handles periodic tasks (tasks that must run at regular
intervals) and aperiodic tasks (tasks triggered by specific events).

Processor Scheduling:

Processor scheduling in real-time systems is based on meeting deadlines


rather than maximizing throughput. Two common types of scheduling are:

 Static priority scheduling: Priorities are assigned at the time of


process creation and do not change. The highest-priority process
always runs first (e.g., Rate Monotonic Scheduling (RMS)).
 Dynamic priority scheduling: Priorities can change over time, often
based on the deadline of the task (e.g., Earliest Deadline First
(EDF) scheduling). The scheduler must be capable of preemption,
meaning it can interrupt a lower-priority task if a higher-priority task
becomes ready to run.

Summary

Syste Processor
Memory Management Process Management
m Scheduling
Multi-
Segmentation, paging, Manages concurrent CPU scheduling to
progra
swapping to load processes using maximize utilization
mmin
multiple processes. context switching. (e.g., FCFS, RR).
g
Time- Virtual memory, paging, Manages multiple user Round Robin
sharin efficient memory processes, ensuring scheduling for equal
g allocation. fairness. CPU time slices.
Processes distributed Local and global
Distrib Decentralized memory,
across nodes, IPC for scheduling, load
uted DSM for shared access.
communication. balancing.
Physical memory, Manages time-critical Scheduling based on
Real-
deterministic access, processes, priority- deadlines, using RMS
time
avoids virtual memory. based. or EDF.

2. write a shell program to find the factorial of a number


accepted from user.
Here's a simple shell script to calculate the factorial of a number
entered by the user.
# Ask the user to enter a number
echo "Enter a number: "
read num
# Initialize factorial to 1
factorial=1
# Check if the input is valid (positive integer)
if [ $num -lt 0 ]; then
echo "Factorial of a negative number doesn't exist."
else
# Calculate factorial
for (( i=1; i<=num; i++ ))
do
factorial=$((factorial * i))
done
# Display the result
echo "The factorial of $num is: $factorial"
Fi

How it works:

1. The script prompts the user to enter a number.


2. It checks if the input is a valid positive number.
3. If valid, it calculates the factorial using a for loop.
4. Finally, it displays the factorial result.

3. explain the linux architecture withe diagram. describe the


basic directory structure of linux.

Linux Architecture

Linux follows a modular architecture, meaning that it is divided


into distinct layers, each responsible for specific functions. The
Linux operating system is composed of several layers: Hardware,
Kernel, Shell, and User Applications. Each layer interacts with
the one above or below it, providing a structured way to manage
resources and execute applications.

Components of Linux Architecture:

1. Hardware Layer:
2. This is the lowest level of the architecture, consisting of
physical hardware components like CPU, memory, storage
devices, input/output devices, etc. The Linux kernel interacts
directly with the hardware through device drivers.

3. Kernel Layer:

The kernel is the core of the Linux operating system and is


responsible for managing system resources such as CPU,
memory, and devices. It provides essential services such as:

a. Process Management: Handles process creation,


scheduling, and termination.
b. Memory Management: Manages RAM allocation and
virtual memory.
c. Device Management: Controls hardware devices
through drivers.
d. File System Management: Provides a structured way
to store, retrieve, and organize data. The kernel
operates in a privileged mode called kernel mode,
which gives it unrestricted access to hardware.
4. Shell Layer:

The shell is an interface between the user and the kernel. It


translates user commands (from the terminal or scripts) into
instructions that the kernel can execute. The shell can be either:

a. Command-line interface (CLI): Bash, Zsh, etc.


b. Graphical user interface (GUI): GNOME, KDE, etc.
Shells also provide scripting capabilities to automate
tasks.
5. User Applications Layer:
This is the top layer where user programs run. It includes all
software applications, utilities, and programs that the user
interacts with, such as text editors, browsers, and games.
Applications access the kernel’s services via system calls.

Below is a diagram representing the Linux architecture:

+------------------------------------+
| User Applications |
+------------------------------------+
|
+------------------------------------+
| Shell |
+------------------------------------+
|
+------------------------------------+
| Kernel |
+------------------------------------+
| Process | Memory | Device | File |
| Management | Management | Mgmt. |
+------------------------------------+
|
+------------------------------------+
| Hardware |
+------------------------------------+
Basic Directory Structure of Linux

Linux follows a hierarchical directory structure where all


directories and files are organized under a single root directory /.
The directory structure is similar to a tree, with / being the root
and all other directories branching from it.

Key Directories in Linux:

1. / (Root Directory):

The root directory is the base of the Linux file system. All other
files and directories are contained within /.

2. /bin (Binaries):

This directory contains essential binary executables required for


the system to operate, such as ls, cp, and mv.

3. /boot:

Contains files required to boot the system, including the Linux


kernel and bootloader files (e.g., grub).

4. /dev (Device Files):

This directory holds device files, which represent hardware


components like hard drives, terminals, and printers. Device files
allow software to interact with hardware as if they were files.

5. /etc (Configuration Files):

Stores system-wide configuration files and shell scripts used to


initialize system settings. For example, /etc/passwd contains
user account information.
6. /home:

This directory contains the personal directories of all users. For


example, /home/user1 is the home directory for the user user1,
where user-specific files are stored.

7. /lib (Libraries):

Holds shared libraries needed by programs in /bin and /sbin.


These libraries are essential for executing binaries and running
applications.

8. /media:

This directory is used as a mount point for removable media


devices such as USB drives, CDs, and DVDs.

9. /mnt:

Temporarily mounts external file systems. This is often used for


mounting partitions, NFS, or other remote file systems.

10. /opt:

Contains optional or third-party software packages. Applications


installed from external vendors or sources may store files here.

11. /proc:

A virtual filesystem that provides information about system


processes and other kernel-related information. For example,
/proc/cpuinfo provides information about the CPU.

12. /root:
This is the home directory of the root user (superuser). It is
different from / which is the root of the entire file system.

13. /sbin (System Binaries):

Stores essential system binaries for system administration tasks.


These include commands used by the superuser, such as
ifconfig and reboot.

14. /tmp (Temporary Files):

Contains temporary files created by system processes or


applications. The contents of this directory are often deleted upon
system reboot.

15. /usr (User Binaries and Data):

Contains user applications and utilities, libraries, and


documentation. For example, /usr/bin contains non-essential
binaries, while /usr/lib contains additional libraries.

16. /var (Variable Files):

Stores variable data like logs, mail spools, print queues, and
temporary files that are generated by system services and
applications. For instance, /var/log contains system log files.

Diagram of Linux Directory Structure:

/ (root)
|
|-- /bin
|-- /boot
|-- /dev
|-- /etc
|-- /home
| |-- user1
| |-- user2
|-- /lib
|-- /media
|-- /mnt
|-- /opt
|-- /proc
|-- /root
|-- /sbin
|-- /tmp
|-- /usr
| |-- bin
| |-- lib
| |-- share
|-- /var
|-- log
|-- mail

Summary of the Linux Directory Structure:

 /bin, /sbin, /lib: Contain essential binaries, system binaries, and


libraries needed for the system to function.
 /etc: System configuration files.
 /home: User directories.
 /var: Variable files like logs and caches.
 /tmp: Temporary files.
 /usr: Non-essential user binaries, applications, and libraries.

4. explain the following linux commands with syntax and the


output of the command
a.cat
b.mv
c.who
d.pwd
e.tty
f.apropos

4. Linux Commands: Explanation, Syntax, and Output

a. cat (Concatenate and Display Files)

Description:

cat is used to display the contents of a file, concatenate multiple


files, and create or append to files.

Syntax:

cat [options] [file...]

Common Usage:

 Display contents of a file: cat filename.txt

 Concatenate two files:cat file1.txt file2.txt


Example Output:

$ cat file.txt
This is the content of the file.

b. mv (Move or Rename Files)

Description:

mv is used to move files or directories from one location to


another, or to rename files and directories.

Syntax:

mv [source] [destination]

Common Usage:

 Rename a file: mv oldname.txt newname.txt

 Move a file to another directory: mv file.txt


/home/user/documents/

Example Output:

$ mv test.txt /home/user/docs/
$ ls /home/user/docs/
test.txt
c. who (Show Who is Logged On)

Description:

who displays information about users who are currently logged


into the system.

Syntax:

who [options]

Common Usage:

 Display all logged-in users: who

Example Output:

$ who
user1 pts/0 2024-10-11 12:34
user2 pts/1 2024-10-11 13:20

d. pwd (Print Working Directory)

Description:

pwd prints the current working directory, showing the full path to
where the user is located in the filesystem.

Syntax:

pwd

Common Usage:
 Show the current working directory:pwd

Example Output:

$ pwd
/home/user/documents

e. tty (Print Terminal Name)

Description:

tty prints the name of the terminal or pseudo-terminal that the


user is currently using.

Syntax:

tty

Common Usage:

 Display the terminal name:tty

Example Output:

$ tty
/dev/pts/0
f. apropos (Search for Commands by Description)

Description:

apropos searches the manual pages (man pages) for commands


based on a keyword or description.

Syntax:

apropos [keyword]

Common Usage:

 Search for commands related to network: apropos network

Example Output:

$ apropos network
ifconfig (8) - configure a network interface
ping (8) - send ICMP ECHO_REQUEST to
network hosts
netstat (8) - print network connections,
routing tables, interface statistics, etc.

Summary of Command Functions:

Comma
Function
nd
cat Displays, concatenates, or creates files.
mv Moves or renames files or directories.
Shows who is currently logged into the
who
system.
pwd Prints the current working directory.
Displays the terminal or pseudo-terminal
tty
in use.
Searches manual pages for commands
apropos
by description.

Unit – 2
1. What is process synchronisation ? explain how
reader-writer problem can be solved using semaphore
with the help of pseudocode.

What is Process Synchronization?

Process synchronization is a technique to ensure that two or more


processes do not simultaneously access shared resources (such
as variables, files, or memory) in a way that causes data
inconsistency or conflict. It helps coordinate the order of process
execution to avoid issues like race conditions where multiple
processes attempt to modify the same resource concurrently.
Reader-Writer Problem

The reader-writer problem is a classical synchronization problem


that deals with a shared resource (e.g., a file or database) being
accessed by multiple readers and writers. It has two constraints:

1. Multiple readers can read the resource simultaneously.


2. Only one writer can write at a time (exclusive access).
3. No reader should read while a writer is writing.

Solution to Reader-Writer Problem using Semaphores

To solve this, we use the following semaphores:

 mutex: Ensures mutual exclusion when updating the reader


count.
 wrt: Controls access to the shared resource so that only one
writer or multiple readers access it at any point.
 readcount: A counter to track the number of readers
currently accessing the resource.

Pseudocode for Reader-Writer Problem Using Semaphores


// Initialization
semaphore mutex = 1; // For controlling access to readcount
semaphore wrt = 1; // For controlling access to the shared
resource
int readcount = 0; // Number of active readers

// Reader Process
Reader() {
wait(mutex); // Lock the mutex to update readcount
readcount++; // Increment the number of readers
if (readcount == 1) // If this is the first reader
wait(wrt); // Lock the shared resource from writers
signal(mutex); // Release the mutex

// Reading section (Access the shared resource)


Read();

wait(mutex); // Lock the mutex to update readcount


readcount--; // Decrement the number of readers
if (readcount == 0) // If this is the last reader
signal(wrt); // Unlock the shared resource for writers
signal(mutex); // Release the mutex
}

// Writer Process
Writer() {
wait(wrt); // Lock the shared resource (exclusive
access)

// Writing section (Modify the shared resource)


Write();

signal(wrt); // Release the shared resource


}

Explanation

1. Reader Process:
a. A reader locks the mutex to safely increment the
readcount.
b. If the readcount becomes 1 (first reader), it locks wrt
to prevent any writer from accessing the shared
resource.
c. After reading, the reader locks the mutex again to
decrement the readcount.
d. If the readcount becomes 0 (last reader), it unlocks
wrt to allow writers to access the shared resource.
2. Writer Process:
a. A writer locks the wrt semaphore to get exclusive
access to the shared resource.
b. After writing, it releases wrt so other writers or readers
can access the resource.

Key Points of the Solution

 Readers get concurrent access unless there is a writer


active.
 Writers get exclusive access, blocking both other writers
and readers.
 The mutex ensures atomic updates to the reader count to
avoid race conditions.

This solution ensures mutual exclusion, synchronization, and


fairness between readers and writers.
2. consider the following five process, with the length of the
CPU burst time given in milliseconds

process arrival time Burst time

p1 0 3

p2 1 2

p3 3 6

p4 4 5

p5 5 3

Let’s walk through the execution of the processes using different


scheduling algorithms and compute the average turnaround
time and average waiting time for each one.
1. First-Come-First-Serve (FCFS) Scheduling

Processes are executed in the order of their arrival time.

Gantt Chart (FCFS)

Copy code
| P1 | P2 | P3 | P4 | P5 |
0 3 5 11 16 19

Turnaround Time (TAT) = Completion Time - Arrival Time

 P1: 3 - 0 = 3
 P2: 5 - 1 = 4
 P3: 11 - 3 = 8
 P4: 16 - 4 = 12
 P5: 19 - 5 = 14

Average TAT = (3 + 4 + 8 + 12 + 14) / 5 = 8.2 ms

Waiting Time (WT) = Turnaround Time - Burst Time

 P1: 3 - 3 = 0
 P2: 4 - 2 = 2
 P3: 8 - 6 = 2
 P4: 12 - 5 = 7
 P5: 14 - 3 = 11

Average WT = (0 + 2 + 2 + 7 + 11) / 5 = 4.4 ms


2. Shortest Job First (SJF) - Non-Preemptive

Selects the process with the shortest burst time next (only once
a process is ready to execute).

Gantt Chart (SJF - Non-Preemptive)

Copy code
| P1 | P2 | P5 | P4 | P3 |
0 3 5 8 13 19

Turnaround Time (TAT)

 P1: 3 - 0 = 3
 P2: 5 - 1 = 4
 P3: 19 - 3 = 16
 P4: 13 - 4 = 9
 P5: 8 - 5 = 3

Average TAT = (3 + 4 + 16 + 9 + 3) / 5 = 7 ms

Waiting Time (WT)

 P1: 3 - 3 = 0
 P2: 4 - 2 = 2
 P3: 16 - 6 = 10
 P4: 9 - 5 = 4
 P5: 3 - 3 = 0

Average WT = (0 + 2 + 10 + 4 + 0) / 5 = 3.2 ms
3. Shortest Remaining Time Next (SRTN) - Preemptive
SJF

At every moment, the process with the shortest remaining burst


time is executed.

Gantt Chart (SRTN)

go
Copy code
| P1 | P2 | P3 | P4 | P5 |
0 3 5 7 11 19
3.a. what is critical section problem? how it can be solved
using semaphore.
b. explain the linux command to view currently running
process on the system. explain nice and renice command in
linux with exmaple
c. explain three different types of schedulers in operating
system with the help of neat diagram, explain specific role of
each type of scheduler.

3a. What is the Critical Section Problem? How can it be solved using
Semaphore?

Critical Section Problem:

 A critical section is a part of a program where shared


resources (like variables, files, etc.) are accessed by multiple
processes or threads.
 The critical section problem arises when multiple
processes try to access and modify shared resources
simultaneously, leading to race conditions and inconsistent
results.

Solution Using Semaphores:

 Semaphores are synchronization tools used to control


access to the critical section and prevent race conditions.
They use two atomic operations:
o wait() (or P operation): Decreases the semaphore
value by 1. If the value becomes negative, the process
is blocked.
o signal() (or V operation): Increases the semaphore
value by 1. If any process was blocked, it is unblocked.

Algorithm using Semaphore:

Semaphore S = 1; // Binary semaphore initialized to


1

Process 1:
wait(S);
// Critical Section
signal(S);

Process 2:
wait(S);
// Critical Section
signal(S);

 Explanation:
o The semaphore ensures that only one process enters
the critical section at a time.
o If one process is in the critical section, other processes
are blocked until the semaphore is released (using
signal()).

3b. View Currently Running Processes in Linux + nice and


renice Commands

1. View Currently Running Processes:

 Command: ps
o Shows information about active processes.
o Example:
bash
Copy code
ps -aux

 -a: Show processes for all users.


 -u: Display user information.
 -x: Show processes without a terminal (like
background services).
 Command: top
o Continuously displays real-time information about
running processes, including CPU and memory usage.

2. nice Command:

 nice sets the priority of a process at the time of starting it.


 Usage:

nice -n <priority> <command>

o Priority values range from -20 (highest priority) to 19


(lowest priority).
o Example:
nice -n 10 ./my_program

o This command starts my_program with a nice value of


10 (lower priority).
3. renice Command:

 renice changes the priority of an already running process.


 Usage:
renice -n <new_priority> -p <PID>

o PID: Process ID of the target process.


o Example:
renice -n -5 -p 1234

o This command changes the priority of the process with


PID 1234 to -5 (higher priority).

3c. Three Types of Schedulers in an Operating System

Schedulers decide which processes will run and when.

1. Long-Term Scheduler (Job Scheduler)

 Role: Controls the admission of processes into the


system.
 When Used: When a new process is submitted for
execution.
 Function: Determines which processes are placed in the
ready queue.
 Goal: To maintain a good mix of I/O-bound and CPU-bound
processes.
2. Short-Term Scheduler (CPU Scheduler)

 Role: Decides which process from the ready queue will be


assigned to the CPU.
 When Used: During context switching (whenever the CPU
becomes free).
 Function: Chooses the process that will execute next on the
CPU.

3. Medium-Term Scheduler

 Role: Manages swapping of processes between main


memory and disk.
 When Used: If the system is overloaded, it temporarily
removes (swaps out) some processes to reduce load.
 Function: Suspends and resumes processes to optimize
CPU and memory usage.

Diagram of Schedulers in OS

plaintext
Copy code
+---------------------+
| New Processes |
+---------------------+
|
v
+--------------------+
| Long-Term Scheduler |
+--------------------+
|
v
+--------------------+
| Ready Queue |
+--------------------+
|
v
+--------------------+
| Short-Term Scheduler (CPU Scheduler) |
+--------------------+
|
v
+---------------------+
| Running Process |
+---------------------+
^
| (Swapping)
+--------------------+
| Medium-Term Scheduler |
+--------------------+

Summary of Roles:

1. Long-Term Scheduler: Controls which processes enter the


ready queue.
2. Short-Term Scheduler: Selects which process to execute
next on the CPU.
3. Medium-Term Scheduler: Manages swapping to optimize
resource usage.
The three modes of the Vi editor are:
1. Command Mode:
a. This is the default mode when you open a file in Vi.
b. In this mode, you can navigate through the file, delete
or copy lines, and perform various other operations.
c. Any key you press is interpreted as a command (e.g.,
dd deletes a line, yy copies a line).
d. To switch to Insert Mode, press i, a, or o.
2. Insert Mode:
a. This mode is used for inserting or editing text.
b. When you're in this mode, anything you type is treated
as text input.
c. To return to Command Mode, press the Esc key.
3. Last Line Mode (or Command-Line Mode):
a. This mode is used to execute extended commands
such as saving or quitting.
b. You enter this mode by pressing : from Command
Mode.
c. Examples of commands:
i. :w to save the file.
ii. :q to quit.
iii. :wq to save and quit.

These modes make Vi a powerful editor by separating navigation,


text editing, and command operations.
Real-Time Operating Systems (RTOS) are specialized
operating systems designed to manage hardware
resources and run tasks within strict timing
constraints. Here are several applications of RTOS
across various industries:

1. Aerospace and Defense

 Flight control systems: Manages avionics and autopilot


functions with precise timing.
 Missile guidance systems: Ensures real-time response
during trajectory adjustments.
 Radar systems: Processes large volumes of data in real
time for accurate detection.

2. Automotive Industry

 Engine Control Units (ECUs): Coordinates ignition, fuel


injection, and emission control.
 Advanced Driver Assistance Systems (ADAS): Manages
features like automatic braking and lane-keeping assist.
 Airbag systems: Ensures immediate deployment during
collisions.

3. Telecommunications

 Base stations and network routers: Handles millions of


packets with low latency.
 Voice over IP (VoIP) systems: Maintains seamless real-
time communication.
 5G infrastructure: Requires precise timing for data
transmission between devices.

4. Medical Devices

 Patient monitoring systems: Tracks vital signs (heart rate,


oxygen levels) in real time.
 MRI and CT scanners: Synchronizes imaging hardware and
software for detailed scans.
 Robotic surgeries: Executes precise movements with
minimal latency for safe operations.

5. Industrial Automation

 Robotics: Real-time control of industrial robots on assembly


lines.
 Programmable Logic Controllers (PLCs): Executes
automated processes without delays.
 Manufacturing systems: Coordinates sensors, actuators,
and control systems efficiently.

6. Consumer Electronics

 Smart TVs and home automation: Manages user input and


media playback without delays.
 Drones: Controls flight and video capture with real-time
responsiveness.
 Wearable devices: Tracks fitness data and health metrics
instantaneously.
7. Power Systems and Utilities

 Smart grids: Monitors and adjusts power distribution based


on demand in real time.
 Nuclear power plants: Ensures precise control of reactors
and cooling systems.
 Renewable energy systems: Manages energy production
from solar or wind sources efficiently.

Key Characteristics of RTOS

 Predictability: Ensures tasks complete within defined


deadlines.
 Multitasking: Manages multiple processes simultaneously
with priority scheduling.
 Low Latency: Critical in applications where even
microsecond delays can cause failure.

RTOS are essential for systems where failure to meet timing


requirements can result in catastrophic outcomes, ensuring
safety, reliability, and performance.

Short-Term, Long-Term, and Medium-Term


Scheduler in Operating Systems
Schedulers are responsible for deciding which processes will run
on the CPU. They are categorized into three types: Long-Term
Scheduler, Short-Term Scheduler, and Medium-Term
Scheduler. Below is a detailed explanation of short-term and
long-term schedulers:
1. Long-Term Scheduler (Job Scheduler)

 Purpose: Controls which processes are admitted to the


system for execution.
 Function:
o Selects processes from the job pool (stored on disk)
and loads them into the ready queue (in memory).
o Regulates the degree of multiprogramming (i.e., the
number of active processes in memory).
o Affects system throughput and performance by
maintaining a mix of I/O-bound and CPU-bound
processes.
 Frequency of Execution: Infrequently, only when the OS
decides it can admit more processes.
 Impact: Influences the long-term performance by
balancing workloads.
 Example Usage:
o In batch processing systems, it decides when new jobs
should be moved from disk storage to memory for
processing.

2. Short-Term Scheduler (CPU Scheduler)

 Purpose: Allocates the CPU to one of the processes in the


ready queue.
 Function:
o Chooses the next process to execute when the CPU
becomes available.
o Uses algorithms like Round Robin, Shortest Job Next
(SJN), or Priority Scheduling to decide which process
runs next.
o Responsible for context switching—saving and
loading process states.
 Frequency of Execution: Very frequently (milliseconds), as
it runs every time the CPU needs a new process.
 Impact:
o Improves CPU utilization and system responsiveness
by quickly switching between processes.
 Example Usage:
o In a multitasking system, it ensures the CPU switches
between processes efficiently to give the illusion of
simultaneous execution.

3. Medium-Term Scheduler (Swapper)

 Purpose: Temporarily removes processes from memory to


reduce the load and free up resources.
 Function:
o Swaps out processes that are not currently active (e.g.,
waiting for I/O operations) to the disk, and swaps them
back into memory when needed.
o Helps maintain a balance between memory usage
and CPU load by adjusting the number of processes in
memory.
o Supports suspended processes, which can be
resumed later when resources are available.
 Frequency of Execution: Runs occasionally—when
memory is overloaded or the OS detects a bottleneck.
 Impact:
o Reduces memory pressure and prevents thrashing
(frequent swapping of processes).
o Improves short-term scheduling efficiency by
ensuring that only active processes occupy memory.
 Example Usage:
o In a system with limited RAM, processes waiting for I/O
might be swapped out, making room for other active
processes.

Comparison Table: Long-Term, Short-Term, and Medium-Term


Scheduler

Long-Term Short-Term
Feature Medium-Term Scheduler
Scheduler Scheduler
Primary Degree of Manage memory and
CPU Allocation
Focus Multiprogramming process load
Execution Infrequently Occasionally (when Very Frequently
Frequency (minutes) memory overloaded) (milliseconds)
Loads processes Swaps processes in/out of Selects process for
Function
into memory memory CPU
Ensure balanced Maximize CPU
Goal Avoid memory bottlenecks
workloads usage
Example Batch jobs Swapping inactive Round Robin
Usage admission processes scheduling

Summary

 Long-Term Scheduler: Manages which processes enter


memory for execution.
 Medium-Term Scheduler: Temporarily suspends processes
to free up resources, helping maintain system stability.
 Short-Term Scheduler: Handles process switching on the
CPU to ensure smooth multitasking.

Each scheduler works in coordination to manage resources


efficiently and optimize system performance.

You might also like