Operating Systems 2 | PDF | Scheduling (Computing) | Process (Computing)
0% found this document useful (0 votes)
5 views

Operating Systems 2

Hbnbv

Uploaded by

Aanchal Shukla
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Operating Systems 2

Hbnbv

Uploaded by

Aanchal Shukla
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Introduction of Lab Subject

The Operating System Lab focuses on providing practical experience with concepts and algorithms
used in operating systems. This lab includes a variety of programming exercises that aim to enhance
the understanding of CPU scheduling, memory management, synchronization mechanisms, and file
organization techniques.
Programming exercises in the lab enhance understanding of CPU scheduling, memory management,
synchronization mechanisms, and file organization techniques.
Implementation of CPU scheduling algorithms such as FCFS, SJF, Priority Scheduling, and Round
Robin are covered in the lab.
Page replacement policies such as LRU, FIFO, and Optimal are explored to manage memory
efficiently.
Memory management techniques like First Fit, Best Fit, and Worst Fit algorithms are studied to
simulate memory allocation to processes.
Synchronization mechanisms using semaphores are implemented for solving the Reader/Writer
Problem and the Producer/Consumer Problem.
The Banker's algorithm for deadlock avoidance is introduced in the lab to ensure safe resource
allocation.
Various file organization techniques like Sequential, Indexed Sequential, and Direct (Random) file
organization are implemented for efficient data storage and retrieval.

Overall, the Operating System Lab equips students with hands-on experience in implementing and
understanding essential concepts and algorithms used in operating systems. Through these exercises,
students gain a deeper understanding of the inner workings of an operating system and its various
components.

1
HARDWARE & SOFTWARE REQUIREMENT

CPU :Intel core i5


8GB RAM
1 TB HDD
Keyboard
Mouse
TFT

Printer : Laser Jet Printer


Software : Operating System (UNIX/LINUX/UBUNTU)

2
LIST OF PRACTICALS (AS PER SYLLABUS
PRESCRIBED BY G.G.S.I.P.U)
OPERATING SYSTEMS
Paper code: CIC 353 L T P
Paper: Operating systems 0 2 1

(Operating System Lab)

List of Experiments
1. Write a program to implement CPU scheduling for first come first serve.
2. Write a program to implement CPU scheduling for shortest job first.
3. Write a program to perform priority scheduling.
4. Write a program to implement CPU scheduling for Round Robin.
5. Write a program for page replacement policy using a) LRU b) FIFO c) Optimal.
6. Write a program to implement first fit, best fit and worst fit algorithm for memory management.
7. Write a program to implement reader/writer problem using semaphore.

8. Write a program to implement Producer‐Consumer problem using semaphores.


9. Write a program to implement Banker’s algorithm for deadlock avoidance.
10. Write C programs to implement the various File Organization Techniques

3
LIST OF PRACTICALS (BEYOND THE LIST
PRESCRIBED BY G.G.S.I.P.U)

11. Study various operating systems and their comparisons.


Cloud Os netvibes,Cloud me,Amoeba Os, Eye Os Ghost Os ,OSv, Joli Os ,Slap Os,Slive
OS,LucidLink OS Mobile OS Android OS,Bada(Samsung Electronics),Black Berry OS,iPhone
OS/iOS,Symbian OS,Windows mobile OS,Harmony OS,Palm S,WebOS(Palm/HP)
12. Study various commands of linux operating system.
13. Write a shell script to add two numbers.
14. Write a shell script to check whether number enter by user is even or odd.
15. Write a shell script to read from a fie.

4
FORMAT OF THE LAB RECORDS TO BE
PREPARED BY THE STUDENTS

The students are required to maintain the lab records as per the instruction:
1. All the record files should have a cover page as per the format.
2. All the record files should have an index as per the format.
3. All the record should have the following:
I. Date
II. Aim
III. Algorithm or The Procedure to be followed
IV. Program
V. Output
VI. Viva Questions

5
MARKING SCHEME
FOR THE
PRACTICAL EXAMINATION

There will be two practical exams in each semester.


1. Internal Practical Exam
2. External Practical Exam

INTERNAL PRACTICAL EXAMINATION


It is taken by the concerned faculty of the batch.
MARKING SCHEME FOR INTERNAL EXAM IS:
Total Marks: 40
Division of 40 Marks is as follows:

1. Regularity/ Attendance
2. File
3. Quiz
4. Viva Voce

6
EXTERNAL PRACTICAL EXAMINATION
It is taken by the concerned faculty of the batch and by an external
examiner. In this exam, student needs to perform the experiment allotted at
the time of the examination, a sheet will be given to the student in which
some details asked by the examiner needs to be written and at the last viva
will be taken by external examiner.

MARKING SCHEME FOR THIS EXAM IS:


Total Marks : 60
Division of 60 marks is as follows
1. Sheet filled by the student : 15
2. Viva Voce : 20
3. Experiment performance : 15
4. File submitted : 10
NOTE:
● Internal marks + External marks = Total marks given to the students
▪ (40 marks) (60 marks) (100 marks)

ANNEXURE I

7
COVER PAGE OF THE LAB RECORD TO BE
PREPARED BY THE STUDENTS
OPERATING SYSTEMS
CIC-353
(Size 20”, italics bold, Times New Roman)

Faculty Name:
(16”, Times New Roman) Student Name:
Roll No.:
Semester:
Batch:
(16”, Times New Roman)

Department of Information Technology


Maharaja Agrasen Institute of Technology, PSP area,
Sector-22, Rohini, New Delhi -110085
(18” bold Times New Roman)

8
ANNEXURE II
FORMAT OF THE INDEX TO BE PREPARED BY
THE STUDENTS
Student’s Name:
Roll No.:
1. Index for the Lab File is as follows:

OPERATING SYSTEMS
PAPER CODE : CIC-353
Name of the student :
University Roll No. :
Branch :
Section/ Group :
PRACTICAL DETAILS
a) Experiments according to the list provided by GGSIPU

Experiment Date Experiment Name Marks (0-3) Total Signature


No. Marks
(15)

R1 R2 R3 R4 R5

1.

2.

3.

4.

5.

9
b) Experiments beyond the list provided by GGSIPU

Experiment Date Experiment Name Marks (0-3) Total Signature


No. Marks
(15)

R1 R2 R3 R4 R5

1.

2.

3.

4.

5.

10
EXPERIMENT – 1

AIM:
To write a C program for implementation of FCFS scheduling algorithm.

THEORY:
FCFS (First-Come, First-Served) scheduling algorithm is a simple CPU scheduling algorithm. In this
algorithm, the process that arrives first is executed first. The processes are executed in the order they
arrive in the ready queue.

The FCFS scheduling algorithm works as follows:

The processes are maintained in a ready queue.When a process arrives, it is added to the end of the
ready queue.The CPU scheduler selects the process at the front of the ready queue for execution.The
selected process is then executed until it completes its burst time.Once the process completes its
execution, it is removed from the ready queue.The CPU scheduler selects the next process from the
front of the ready queue until all processes have been executed.

Following are the basic terminologies:

Turnaround Time: Difference between completion time and arrival time.

Turnaround Time = Completion Time – Arrival Time

Waiting Time: Time Difference between turnaround time and burst time.

Waiting Time = Turnaround Time – Burst Time

The average waiting time and average turnaround time can be calculated using the following
formulas:

Average Waiting Time = Total Waiting Time / Number of Processes Average Turnaround Time =
Total Turnaround Time / Number of Processes

The waiting time of a process is the time it spends waiting in the ready queue, while the turnaround
time is the total time taken by a process from its arrival to its completion.

It is important to note that the FCFS scheduling algorithm suffers from the "convoy effect" where a
long process in the front of the ready queue can delay the execution of shorter processes waiting

11
behind it. This can lead to poor performance in certain scenarios.

To implement FCFS scheduling algorithm in C, you can create a structure to represent a process with
attributes like process ID, arrival time, burst time, waiting time, and turnaround time. The processes
can be read from user input or generated randomly. Then, you can calculate the waiting time and
turnaround time for each process using the FCFS algorithm. Finally, the average waiting time and
average turnaround time can be calculated and displayed.

ALGORITHM:
1.Start the program.
2.Declare and initialize the necessary variables such as "n" (number of processes), "burst_time"
(array to store burst time of each process), "waiting_time" (array to store waiting time of each
process), "turnaround_time" (array to store turnaround time of each process), and
"average_waiting_time" and
"average_turnaround_time" variables.
3.Accept the number of processes from the user.
4.Accept the burst time of each process from the user and store it in the "burst_time" array.
5.Initialize the first process arrival time as 0 and store it in the "waiting_time" array.
6.Calculate the waiting time of each process as the sum of burst times of previous processes.
for i=1 to n-1 waiting_time[i] = waiting_time[i-1] + burst_time[i-1]
7.Calculate the turnaround time of each process as the sum of burst time and waiting time of that
process.
for i=0 to n-1 turnaround_time[i] = burst_time[i] + waiting_time[i]
8.Calculate the average waiting time by summing up all waiting times and dividing it by the number
of processes.
average_waiting_time = sum of waiting times/n
9.Calculate the average turnaround time by summing up all turnaround times and dividing it by the
number of processes.
average_turnaround_time = sum of turnaround times/n
10.Display the waiting time and turnaround time of each process.

11.Display the average waiting time and average turnaround time. End the program.

Note: The above algorithm assumes that the processes have arrived in increasing order of their
arrival time and no two processes have the same arrival time. If the processes have different arrival

12
times, you can modify the algorithm to accommodate that.

VIVA QUESTIONS:
1.How does the FCFS scheduling algorithm work?
2.What is the main advantage of using the FCFS scheduling algorithm?
3.Can you provide an example scenario where the FCFS scheduling algorithm may not be ideal?
4.What is the average waiting time for processes when using the FCFS scheduling algorithm?
5.Are there any limitations or disadvantages to using the FCFS scheduling algorithm?
.

13
EXPERIMENT – 2

AIM:
To write a C program for implementation of SJF scheduling algorithms.

THEORY:
The Shortest Job First (SJF) algorithm is a popular scheduling algorithm used in operating systems
to minimize the waiting time and turnaround time of processes. This algorithm works by selecting
the process with the shortest burst time and executing it first.In this algorithm, the user inputs the
number of processes and their burst times. The processes are then sorted based on their burst time in
ascending order.The algorithm starts by initializing the current time to 0 and the number of
completed processes to 0. It then repeatedly selects the process with the shortest remaining time
among the processes that have not been executed. The selected process is executed for one unit of
time, and the current time is incremented. The remaining time of the process is decremented.If the
remaining time of the process becomes 0, the algorithm updates its turnaround time as the current
time, increments the number of completed processes, and calculates its waiting time as the difference
between the turnaround time and burst time. This process continues until all processes are
completed.Finally, the algorithm calculates the average waiting time and average turnaround time by
summing up the waiting times and turnaround times of all processes and dividing them by the
number of processes. The process details, including process ID, burst time, waiting time, and
turnaround time, are printed along with the average waiting time and average turnaround time.
The SJF algorithm is advantageous as it prevents long processes from experiencing starvation.
However, it may not be efficient when the arrival time of processes is unknown or cannot be
accurately predicted.

ALGORITHM:

1.Sort the processes based on their burst in ascending order.


2.Set the current time to 0 and initialize the waiting time and total turnaround time to 0.
3.Repeat until all the processes are completed:
a. Find the process with the shortest burst time that arrives before or at the current time.
b. Set the current process as the next shortest job and update the current time by adding the burst
time of the current process.
c. Calculate the waiting time of the current process as the difference between the current time and the

14
arrival time of the current process.
d. Calculate the turnaround time of the current process as the sum of its waiting time and burst time.
e. Update the total waiting time by adding the waiting time of the current process and the total
turnaround time by adding the turnaround time of the current process.
f. Mark the current process as completed.
4.Calculate the average waiting time by dividing the total waiting time by the number of processes.
5.Calculate the average turnaround time by dividing the total turnaround time by the number of
processes.
6.Display the average waiting time and average turnaround time. End of Algorithm.

VIVA QUESTIONS:
1. Explain the concept of shortest job first scheduling algorithm.
2. Can you mention a scenario where shortest job first scheduling algorithm would be less efficient?
3. How does the shortest job first algorithm minimize waiting time or turnaround time?
4. How does the arrival time of jobs affect the performance of shortest job first algorithm?
5. Can you provide an example to illustrate the working of shortest job first scheduling algorithm?

15
EXPERIMENT –3

AIM:

To write a C program for implementation of Priority scheduling algorithms.

THEORY:
Priority Scheduling is a method of scheduling processes that is based on priority. In this algorithm,
the scheduler selects the tasks to work as per the priority.
The processes with higher priority should be carried out first, whereas jobs withequal priorities are
carried out on a round-robin or FCFS basis. Priority dependsupon memory requirements, time
requirements, etc.
Types of Priority Scheduling
Priority scheduling divided into two main types:
Preemptive Scheduling
In Preemptive Scheduling, the tasks are mostly assigned with their priorities.Sometimes it is
important to run a task with a higher priority before another lower priority task, even if the lower
priority task is still running. The lower priority task holds for some time and resumes when the
higher priority task finishes its execution.
Non-Preemptive Scheduling
In this type of scheduling method, the CPU has been allocated to a specific process. The process that
keeps the CPU busy, will release the CPU either by switching context or terminating. It is the only
method that can be used for various hardware platforms. That’s because it doesn’t need special
hardware (for example,a timer) like preemptive scheduling.
Characteristics of Priority Scheduling
● A CPU algorithm that schedules processes based on priority.
● It used in Operating systems for performing batch processes.
●If two jobs having the same priority are READY, it works on a FIRST COME, FIRST SERVED basis.
● In priority scheduling, a number is assigned to each process that indicates its priority level.
● Lower the number, higher is the priority.
● In this type of scheduling algorithm, if a newer process arrives, that is having a higher priority than the
currently running process, then the currently running process is preempted.

16
EXAMPLE OF PRIORITY SCHEDULING

Consider following five processes P1 to P5. Each process has its uniquepriority, burst time, and
arrival time.
Process Priority Burst time Arrival time P1 1 4 0

P2 2 3 0
P3 1 7 6
P4 3 4 11
P5 2 2 12
Step 0) At time=0, Process P1 and P2 arrive. P1 has higher priority than P2. The execution begins
with process P1, which has burst time 4.

Step 1) At time=1, no new process arrive. Execution continues with P1.

Ste

p 2) At time 2, no new process arrives, so you can continue with P1. P2is in the waiting queue.

Ste

p 3) At time 3, no new process arrives so you can continue with P1. P2process still in the waiting
queue.

17
Ste

p 4) At time 4, P1 has finished its execution. P2 starts execution.

Ste

p 5) At time= 5, no new process arrives, so we continue withP2.

Ste
p 6) At time=6, P3 arrives. P3 is at higher priority (1) compared toP2 having priority (2). P2 is
preempted, and P3 begins its execution.
ALGORITHM:
1.Initialize an empty ready queue.
2.Create a list of processes with their respective arrival time, burst time, and priority.
3. Sort the list of processes based on their priority, with the highest priority being the highest
number.
4.Set the current time to 0.
5.Repeat steps 6-9 until all processes have been executed.
6.Check if any process has arrived at the current time; if so, add it to the ready queue.
7.If the ready queue is not empty, select the process with the highest priority from the ready queue.

18
8.Execute the selected process for its burst time.
9.Update the waiting time, turnaround time, and current time based on the execution of the process.
10.If all processes have been executed, go to step 11; otherwise, go to step 6.
11.Calculate the average waiting time and average turnaround time by summing up the waiting times
and turnaround times, respectively, and dividing them by the total number of processes.
12.Display the average waiting time and average turnaround time as outputs.

VIVA QUESTIONS:
1. How does the Priority Scheduling algorithm determine the priority of different tasks in a job
queue?
2. What are the advantages of using Priority Scheduling algorithm over other scheduling algorithms
like First-Come, First-Serve or Round Robin?
3. Can you explain the concept of preemption in Priority Scheduling algorithm? How does it affect
the execution of high-priority tasks?
4. How can you ensure fairness in Priority Scheduling algorithm when multiple tasks have the same
priority?
5. What are the factors to consider while assigning priorities to different tasks in Priority Scheduling
algorithm?

EXPERIMENT –4

19
AIM:

To write a C program for implementation of Round Robin scheduling algorithms.

THEORY:

Round Robin Scheduling is a CPU scheduling algorithm in which each process isexecuted for a
fixed time slot. Since the resources are snatched after the time slot, round robin is preemptive.
Preemptive: In this type, resources can be voluntarily snatched.
Non-Preemptive: In this type, if a process is once started, it will execute completely i.e resources
cannot be snatched.
ADVANTAGES:
● There is no starvation of resources as each process gets equal share.
● Every Process gets equal allocation of CPU.
● Increases Performance time in terms of response time.
DISADVANTAGES:
● More time is wasted on context switching.
● Frequent context switching increases CPU overhead.
● Average Waiting time increases for each process.

ALGORITHM:
Step 1: Start the Program.
Step 2: Input the number of processes.
Step 3: Input the burst time and arrival time of each process and the limit of thetime slot.
Step 4: Push all processes into the ready queue according to their arrival time.Then execute each
process upto time slot and push the left over process in queueagain for execution.
Step 5: After a process is completely executed, print its turn around time andwaiting time.

VIVA QUESTIONS:
1.How does the round-robin scheduling algorithm work?
2.How is the round-robin algorithm different from other scheduling algorithms?
3.How is context switching handled in the round-robin scheduling algorithm?
4.How is the performance of round-robin scheduling affected by the length of the time quantum?

20
5.What is the relationship between time quantum and context switching overhead in round-robin
scheduling?

EXPERIMENT –5

21
AIM-

Write a program for page replacement policy using a) LRU b) FIFO c) Optimal.

THEORY:
In an operating system that uses paging for memory management, a page replacement algorithm is
needed to decide which page needs to be replaced when a new page comes in.
Page Fault: A page fault happens when a running program accesses a memory page that is mapped
into the virtual address space but not loaded in physical memory. Since actual physical memory is
much smaller than virtual memory, page faults happen. In case of a page fault, Operating System
might have to replace one of the existing pages with the newly needed page. Different page
replacement algorithms suggest different ways to decide which page to replace. The target for all
algorithms is to reduce the number of page faults.
First In First Out (FIFO): This is the simplest page replacement algorithm. In this algorithm, the
operating system keeps track of all pages in the memory in a queue, the oldest page is in the front of
the queue. When a page needs to be replaced page in the front of the queue is selected for removal.
Example 1: Consider page reference string 1, 3, 0, 3, 5, 6, 3 with 3 page frames. Find the number of
page faults.

Initially, all slots are empty, so when 1, 3, 0 came they are allocated to the empty slots —> 3 Page
Faults.

22
when 3 comes, it is already in memory so —> 0 Page Faults. Then 5 comes, it is not available in
memory so it replaces the oldest page slot i.e 1. —>1 Page Fault. 6 comes, it is also not available in
memory so it replaces the oldest page slot i.e 3 —>1 Page Fault. Finally, when 3 come it is not
available so it replaces 0 1 page fault.
Belady’s anomaly proves that it is possible to have more page faults when increasing the number of
page frames while using the First in First Out (FIFO) page replacement algorithm. For example, if
we consider reference strings 3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4, and 3 slots, we get 9 total page faults, but
if we increase slots to 4, we get 10-page faults.
2. Optimal Page replacement: In this algorithm, pages are replaced which would not be used for the
longest duration of time in the future.
Example-2: Consider the page references 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 3 with 4 page frame. Find
number of page fault.

Initially, all slots are empty, so when 7 0 1 2 are allocated to the empty slots —> 4Page faults
0 is already there so —> 0 Page fault. when 3 came it will take the place of 7 because it is not used
for the longest duration of time in the future.—>1 Page fault. 0 is already there so —> 0 Page fault. 4
will takes place of 1 —> 1 Page Fault.
Now for the further page reference string —> 0 Page fault because they are alreadyavailable in the
memory.
Optimal page replacement is perfect, but not possible in practice as the operatingsystem cannot know
future requests. The use of Optimal Page replacement is to set up a benchmark so that other
replacement algorithms can be analyzed against it.
3. Least Recently Used: In this algorithm, page will be replaced which is least recently used.
Example-3: Consider the page reference string 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 3 with 4 page frames.

23
Find number of page faults.

Initially, all slots are empty, so when 7 0 1 2 are allocated to the empty slots —> 4Page faults
0 is already their so —> 0 Page fault. when 3 came it will take the place of 7 because it is least
recently used —>1 Page fault
0 is already in memory so —> 0 Page fault.
4 will takes place of 1 —> 1 Page Fault
Now for the further page reference string —> 0 Page fault because they are already available in the
memory.
4. Most Recently Used (MRU): In this algorithm, page will be replaced which has been used
recently. Belady’s anomaly can occur in this algorithm.

Initially, all slots are empty, so when 7 0 1 2 are allocated to the empty slots —> 4 Page faults
0 is already their so–> 0 page fault

24
when 3 comes it will take place of 0 because it is most recently used —>1 Page fault
when 0 comes it will take place of 3 —>1 Page fault
when 4 comes it will take place of 0 —>1 Page fault
2 is already in memory so —> 0 Page fault
when 3 comes it will take place of 2 —>1 Page fault
when 0 comes it will take place of 3 —>1 Page fault
when 3 comes it will take place of 0 —>1 Page fault
when 2 comes it will take place of 3 —>1 Page fault
when 3 comes it will take place of 2 —>1 Page fault

ALGORITHM (FIFO):

Step 1: Start the program.


Step 2: Declare the necessary variables.
Step 3: Enter the number of frames.
Step 4: Enter the reference string end with zero.
Step 5: FIFO page replacement selects the page that has been in memory the longest time and when
the page must be replaced the oldest page is chosen. Step 6: When a page is brought into memory, it
is inserted at the tail of the queue. Step 7: Initially all the three frames are empty.
Step 8: The page fault range increases as the no of allocated frames also increases. Step 9: Print the
total number of page faults.
Step 10: Stop the program.

ALGORITHM (LRU):

Step 1: Start the process


Step 2: Declare the size
Step 3: Get the number of pages to be inserted
Step 4: Get the value
Step 5: Declare counter and stack
Step 6: Select the least recently used page by counter value
Step 7: Stack them according to the selection.

25
Step 8: Display the values
Step 9: Stop the process

ALGORITHM (Optimal):

1.Create an empty page table to keep track of the pages in.


2.Initialize a counter to keep track of the number of page faults3. For each memory reference, do the
following steps:
a. If the requested page is not present in memory (i.e., a page fault occurs), increment the page fault
counter. b. If there is an empty frame in memory, allocate the requested page to that frame and
update the page table accordingly. c. If all frames are occupied, determine the page that will be
referenced furthest in the
future. d. Replace the page in memory that will be referenced furthest in the future with the requested
page. Update the page table accordingly.
a)Continue the above steps until all memory references have been processed.
b)At the end, the page fault counter will give the total number of page faults that occurred during the
execution.
This algorithm assumes that we have knowledge of all future memory references. In practice, this is
not always possible. However, it serves as an optimal benchmark for evaluating other page
replacement algorithms.

VIVA QUESTIONS:
1) How does the FIFO algorithm decide which page to discard from the cache?
2) What are the advantages and disadvantages of using FIFO compared to other page replacement
algorithms?
3) Can you explain why FIFO may not always be the optimal choice for cache replacement?
4) How does FIFO handle situations where specific pages are accessed more frequently than others?
5) Can you provide an example scenario where FIFO could result in poor cache performance?
6) How does the LRU algorithm determine which page to replace in the cache?
7) In what scenarios does LRU perform well and why?

EXPERIMENT –6

26
AIM:
To write a C program for implementation memory allocation methods for fixed partition using a)
first fit b)Best Fit c)Worst Fit

THEORY:
FIRST FIT
In the first fit approach is to allocate the first free partition or hole large enough which can
accommodate the process. It finishes after finding the first suitable free partition.
ADVANTAGE:-
Fastest algorithm because it searches as little as possible.
DISADVANTAGE:-
The remaining unused memory areas left after allocation become waste if it is too smaller. Thus
request for larger memory requirement cannot be accomplished.

BEST FIT
The best fit deals with allocating the smallest free partition which meets the requirement of the
requesting process. This algorithm first searches the entire list of free partitions and considers the
smallest hole that is adequate. It then tries to find a hole which is close to actual process size needed.
ADVANTAGE:
Memory utilization is much better than first fit as it searches the smallest free partition first available.
DIADVANTAGE:
It is slower and may even tend to fill up memory with tiny useless holes.

WORST FIT:
In worst fit approach is to locate largest available free portion so that the portion left will be big
enough to be useful. It is the reverse of best fit.
ADVANTAGE:
Reduces the rate of production of small gaps.
DISADVANTAGE:
If a process requiring larger memory arrives at a later stage then it cannot be accommodated as the
largest hole is already split and occupied.

27
ALGORITHM FIRST FIT:
First Fit Algorithm:
Start by initializing an empty list of memory blocks.
Iterate through the list of processes in the order they are given.
For each process, iterate through the list of memory blocks and find the first block that can
accommodate the process.
If a block is found, allocate the process to that block and update the remaining space in the block.
If no suitable block is found, create a new memory block with the size of the process and allocate the
process to that block.
Continue this process for each process in the list until all processes are allocated. Finally, display the
memory blocks with their allocated processes. Example:
Let's say we have 5 processes with sizes 100KB, 200KB, 50KB, 300KB, and 150KB. We also have
three memory blocks with sizes 300KB, 150KB, and 500KB.
Process Sizes: [100, 200, 50, 300, 150] Memory Block Sizes: [300, 150, 500]
Allocate process 100KB to the first memory block (size 300KB). Remaining space in the block:
200KB.
Current Memory Blocks: [100]
Allocate process 200KB to the third memory block (size 500KB). Remaining space in the block:
300KB.
Current Memory Blocks: [100, 200]
Allocate process 50KB to the third memory block (size 300KB). Remaining space in the block:
250KB.
Current Memory Blocks: [100, 200, 50]
Allocate process 300KB to the third memory block (size 250KB). As it cannot accommodate the
process, create a new memory block (size 300KB) and allocate the process to it.
Current Memory Blocks: [100, 200, 50, 300]
Allocate process 150KB to the second memory block (size 150KB). Remaining space in the block:
0KB.
Current Memory Blocks: [100, 200, 50, 300, 150]
Final Memory Blocks: [100], [200], [50, 300], [150]
Note: The first fit algorithm prioritizes the first available block that can accommodate the process. If
there are multiple blocks that can satisfy the process size, it will allocate the process to the earliest

28
block in the list of memory blocks.

ALGORITHM BEST FIT:


The best fit algorithm is used for memory allocation in a computer system. It aims to find the
smallest free partition in the memory that is large enough to accommodate a process.
Here is the algorithm for best fit:
Initialize a list of free memory partitions.
When a process requests memory allocation:
a. Iterate through the list of free memory partitions.
b. Find the smallest partition that is large enough to hold the process.
c. If no such partition is found, inform the process that there is not enough memory available.
d. If a suitable partition is found, allocate the process to that partition and update the list of free
partitions accordingly:
i. If the partition is exact (the same size as the process), remove it from the list.
ii. If the partition is larger than the process, split it into two partitions - one allocated for the process
and the other remaining as free memory. Adjust the sizes and addresses accordingly.
e. Return the starting address of the allocated partition to the process.
When a process is deallocated:
a. Add the freed partition back to the list of free memory partitions.
b. Sort the list of free memory partitions based on their sizes in ascending order.
c. Consolidate adjacent free partitions if any.
Repeat steps 2 and 3 as necessary.
This algorithm ensures efficient memory utilization and minimizes fragmentation by allocating the
smallest suitable free partition for each process.

ALGORITHM WORST FIT:


1.Start by initializing a list of free memory blocks with their respective addresses and sizes.
2.Sort the list of free memory blocks in descending order based on their sizes.
3.Iterate through the list of processes and allocate each process to the first free memory block that
can accommodate it.
4.If a suitable memory block is found, update the free memory block list by splitting the allocated
memory block into two parts: one for the allocated process and the other for the remaining free

29
memory.
5.If no suitable memory block is found, skip the process or wait until a suitable memory block
becomes available.
6.Repeat steps 3-5 until all processes have been allocated or skipped.
7.After all processes have been allocated or skipped, check if there are any remaining unallocated
free memory blocks.
8.If there are unallocated free memory blocks, merge adjacent free blocks together to form larger
free blocks.
9.If necessary, perform further optimizations such as compacting the memory to minimize
fragmentation.
10.Finally, output the memory allocation status, including the allocated addresses for each process
and any remaining free memory blocks.

VIVA QUESTIONS:
1.Can you explain the concept of first fit, best fit, and worst fit memory allocation strategies?
2.How does the first fit algorithm work in memory allocation?
3.What are the advantages and disadvantages of using the best fit strategy for memory allocation?
4.Can you provide a scenario where the worst fit strategy would be the most efficient for memory
allocation?
5.How do these memory allocation strategies affect the fragmentation of memory?

EXPERIMENT –7
AIM:

30
Write a program to implement reader/writer problem using semaphore.

THEORY:
The readers-writers problem relates to an object such as a file that is shared between multiple
processes. Some of these processes are readers i.e. they only want to read the data from the object
and some of the processes are writers i.e. they want to write into the object.
The readers-writers problem is used to manage synchronization so that there are no problems with
the object data. For example - If two readers access the object at the same time there is no problem.
However if two writers or a reader and writer access the object at the same time, there may be
problems.
To solve this situation, a writer should get exclusive access to an object i.e. when a writer is
accessing the object, no reader or writer may access it. However, multiple readers can access the
object at the same time.
This can be implemented using semaphores

READER-WRITER PROBLEM ALGORITHM


SHARED VARIABLES:
readers_count: Number of active readers.
write_lock: A lock to ensure exclusive access for writers.
read_lock: A lock to coordinate access for readers.
resource: The shared resource being read/written.
READER FUNCTION:
A reader arrives and tries to enter the reading section.
Before entering, the reader checks if it's the first reader. If yes, it acquires the write_lock to prevent
writers.
Once inside the reading section:
Read from the resource.
Increment the readers_count.
After reading, the reader leaves the reading section.
Before leaving, it checks if it's the last reader. If yes, it releases the write_lock to allow writers.
WRITER FUNCTION:
A writer arrives and tries to enter the writing section.

31
It acquires the write_lock to ensure exclusive access to the resource. Once inside the writing section:
Write to the resource.
After writing, the writer leaves the writing section and releases the write lock.

VIVA QUESTIONS:
1.What is the reader/writer problem?
2.Explain how semaphores are used to solve the reader/writer problem.
3.What is the difference between a reader and a writer in the context of the reader/writer problem?
4.What are the potential issues that can arise if the reader/writer problem is not properly handled?
5.How does the use of semaphores ensure mutual exclusion between multiple readers and writers?
6.What is the purpose of the readerCount semaphore in the reader/writer problem solution?

EXPERIMENT –8
AIM:
32
Write a program to implement Producer‐Consumer problem using semaphores.

THEORY:
The producer consumer problem is a synchronization problem. There is a fixed size buffer and the
producer produces items and enters them into the buffer. The consumer removes the items from the
buffer and consumes them.
A producer should not produce items into the buffer when the consumer is consuming an item from
the buffer and vice versa. So the buffer should only be accessed by the producer or consumer at a
time.

The producer consumer problem can be resolved using semaphores. The codes for the producer and consume

Producer Process
The code that defines the producer process is given below
do {
PRODUCE ITEM
wait(empty);
wait(mutex)
PUT ITEM IN BUFFER
.
signal(mutex);
signal(full);
} while(1);
In the above code, mutex, empty and full are semaphores. Here mutex is initialized to 1, empty is
initialized to n (maximum size of the buffer) and full is initialized to 0.
The mutex semaphore ensures mutual exclusion. The empty and full semaphores count the number
of empty and full spaces in the buffer.
After the item is produced, wait operation is carried out on empty. This indicates that the empty
space in the buffer has decreased by 1. Then wait operation is carried out on mutex so that consumer
process cannot interfere.
After the item is put in the buffer, signal operation is carried out on mutex and full. The former
indicates that consumer process can now act and the latter shows that the buffer is full by 1.
Consumer Process

33
The code that defines the consumer process is given below:
do {
wait(full);
wait(mutex);
REMOVE ITEM FROM BUFFER
signal(mutex);
signal(empty);
CONSUME ITEM
} while(1);
The wait operation is carried out on full. This indicates that items in the buffer have decreased by 1.
Then wait operation is carried out on mutex so that producer process cannot interfere.
Then the item is removed from buffer. After that, signal operation is carried out on mutex and empty.
The former indicates that consumer process can now act and the latter shows that the empty space in
the buffer has increased by 1.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the required variables.
Step 3: Initialize the buffer size and get maximum item you want to produce. Step 4: Get the option,
which you want to do either producer, consumer or exit from the
operation.
Step 5: If you select the producer, check the buffer size if it is full the producer should not
produce the item or otherwise produce the item and increase the value buffer size. Step 6: If you
select the consumer, check the buffer size if it is empty the consumer should not
consume the item or otherwise consume the item and decrease the value of buffer size.
Step 7: If you select exit come out of the program.
Step 8: Stop the program.

VIVA QUESTIONS:
1.What is the producer-consumer problem and why is it important in concurrent programming?
2.How can we ensure that the producer and consumer processes synchronize their actions properly?
3.What are the possible solutions to the producer-consumer problem, and what are the advantages
and disadvantages of each?

34
4.How does the use of semaphores help in solving the producer-consumer problem?
5.Can you explain the concept of bounded buffer and how it relates to the producer-consumer
problem?

EXPERIMENT –9

35
AIM:
Write a program to implement Banker’s algorithm for deadlock avoidance.

THEORY:
Banker's algorithm is a resource allocation and deadlock avoidance algorithm developed by Edsger
Dijkstra that tests for safety by simulating the allocation of predetermined maximum possible
amounts of all resources, and then makes an "s-state" check to test for possible deadlock conditions
for all other pending activities, before deciding whether allocation should be allowed to continue.
For the Banker's algorithm to work, it needs to know three things:
● How much of each resource each process could possibly request [MAX] ● How much of each
resource each process is currently holding [ALLOCATED] ● How much of each resource the system
currently has available [AVAILABLE]
Resources may be allocated to a process only if it satisfies the following conditions:
1. request available , else process waits until resources are available.
Some of the resources that are tracked in real systems are memory, semaphores and interface access.
The Banker's Algorithm derives its name from the fact that this algorithm could be used in a banking
system to ensure that the bank does not run out of resources, because the bank would never allocate
its money in such a way that it can no longer satisfy the needs of all its customers. By using the
Banker's algorithm, the bank ensures that when customers request money the bank never leaves a
safe state. If the customer's request does not cause the bank to leave a safe state, the cash will be
allocated, otherwise the customer must wait until some other customer deposits enough.
Basic data structures to be maintained to implement the Banker's Algorithm:
Let n be the number of processes in the system and m be the number of resource types. Then we
need the following data structures:
● Available:A vector of length m indicates the number of available resources ofeach type. If
Available[j] = k, there are k instances of resource type Rj available.
● Max:An n×m matrix defines the maximum demand of each process. If Max [i, j] = k, then Pimay
request at most k instances of resource type Rj.
● Allocation:An n×m matrix defines the number of resources of each typecurrently allocated to each
process. If Allocation [i, j] = k, then process Pi is currently allocated k instances of resource type Rj.
● Need:An n×m matrix indicates the remaining resource need of each process. IfNeed[i, j] = k, then P i
may need k more instances of resource type Rj tocomplete the task.
36
Note: Need [i, j] = Max [i, j] - Allocation [i, j].

VIVA QUESTIONS:
1.Explain the Banker's algorithm and its purpose in operating systems.
2.How does the Banker's algorithm ensure safe execution of processes in a resource allocation
system?
3.What are the key components of the Bank's algorithm and how do they work together to ensure
resource safety?
4.Can you describe a scenario in which the Banker's algorithm would be used and how it would
prevent a deadlock?
5.Are there any limitations or drawbacks to the Banker's algorithm? If so, please explain.

EXPERIMENT –10
37
AIM-
Write C programs to implement the various File Organization Techniques .

THEORY:
a) Single Level Directory
ALGORITHM:
Step-1: Start the program.
Step-2: Declare the count, file name, graphical interface.
Step-3: Read the number of files
Step-4: Read the file name
Step-5: Declare the root directory
Step-6: Using the file eclipse function define the files in a single level Step-7: Display the files
Step-8: Stop the program
ALGORITHM:
Step-1: Start the program.
Step-2: Declare the count, file name, graphical interface.
Step-3: Read the number of files
Step-4: Read the file name
Step-5: Declare the root directory
Step-6: Using the file eclipse function define the files in a single level Step-7: Display the files
Step-8: Stop the program

VIVA QUESTIONS:
1. How can the index blocks be implemented in the Indexed AllocationScheme?
2. How free-space is managed using Bit Vector Implementation?

EXPERIMENT – 11
38
AIM-1. Study various operating systems and their comparisons.
Cloud Os netvibes,Cloud me,Amoeba Os, Eye Os Ghost Os ,OSv, Joli Os ,Slap Os,Slive
OS,LucidLink OS Mobile OS Android OS,Bada(Samsung Electronics),Black Berry OS,iPhone
OS/iOS,Symbian OS,Windows mobile OS,Harmony OS,Palm S,WebOS(Palm/HP)

THEORY:-

Operating systems are the backbone of modern computing devices, serving as the interface between
the hardware and the user. There are various types of operating systems in existence, each with
unique features and functionalities. In this article, we will compare and contrast some popular
operating systems, including cloud OS and mobile OS.

Cloud OS:
1. Netvibes: Netvibes is a web-based personal dashboard platform that allows users to organize their
favorite websites, news feeds, and social media accounts in one place. It offers a customizable
interface and real-time updates.
2. CloudMe: CloudMe is a cloud storage and file synchronization service that also offers a web-
based operating system with applications for productivity and entertainment. It provides seamless
access to files from any device with an internet connection.

Mobile OS:
1. Android OS: Developed by Google, Android is one of the most popular mobile operating systems
in the world. It is known for its open-source nature, wide range of apps available on the Google Play
Store, and customization options.
2. iOS: iOS is the operating system developed by Apple for its mobile devices, including the iPhone
and iPad. It is known for its user-friendly interface, security features, and seamless integration with
other Apple products and services.
3. Windows Mobile OS: Windows Mobile OS is developed by Microsoft for smartphones and
tablets. It offers integration with Microsoft services such as Office 365 and OneDrive, as well as a
familiar desktop-like interface.

Overall, cloud OS are ideal for users who prefer to access their data and applications online from any
device, while mobile OS are designed for smartphones and tablets and offer features specific to

39
mobile computing. Each operating system has its own strengths and weaknesses, so the choice of OS
will ultimately depend on the user's preferences and needs.

VIVA QUESTIONS:
1. How does Cloud OS such as netvibes and Cloud me differ from traditional operating systems like
Windows or MacOS?
2. What are the key features and advantages of Mobile OS such as Android OS, iOS, and Windows
Mobile OS?
3. How does Amoeba OS compare to other cloud-based operating systems like Eye OS and Ghost
OS?
4. What are the main differences between traditional desktop operating systems like Windows and
mobile operating systems like Android and iOS?
5. How does Palm OS and WebOS ((Palm/HP) compare to other mobile operating systems such as
Android and iOS in terms of functionality and user experience?

40
EXPERIMENT – 12
AIM-

Study various commands of linux operating system

THEORY:-

LINUX:
It is similar to UNIX, which is created by Linus Torualds. All UNIX commands worksin Linux.
Linux is a open source software. The main feature of Linux is coexisting with otherOS such as
windows and UNIX.
Commands-

a) date–used to check the date and time

Syntax:$date

b) cal–used to display the calendar


Syntax:$cal 2 2009

c)echo–used to print the message on the screen.


Syn:$echo “text”

d)ls–used to list the files. Your files are kept in a directory.


Syn:$lsls–s

e)lp–used to take printouts


Syn:$lp filename

g)who –it displays data about all users who have logged into the system currently. The next
command displays about current user only.

Syn:$who

41
FILE MANIPULATION COMMANDS

a)cat–this create, view and concatenate files.


Creation:

Syn:$cat>filename

Viewing:

Syn:$cat filename

Add text to an existing file:

Syn:$cat>>filename

Concatenate:

Syn:$catfile1file2>file3

$catfile1file2>>file3 (no over writing of file3)

b)grep–used to search a particular word or pattern related to thatword from the file.

Syn:$grep search word filename

Eg:$grep anu student

c)rm–deletes a file from the file system

Syn:$rm filename

d)touch–used to create a blank file.

Syn:$touch file names

e)cp–copies the files or directories

Syn:$cpsource file destination file

Eg:$cp student stud

f)mv–to rename the file or directory

42
syn:$mv old file new file

Eg:$mv–i student student list(-i prompt when overwrite)

g)cut–it cuts or pickup a given number of character or fields of the file.

Syn:$cut<option><filename>

Eg: $cut –c filename

$cut–c1-10emp

$cut–f 3,6emp

$ cut –f 3-6 emp

-c cutting columns

-f cutting fields

h)head–displays10 lines from the head(top)of a given file

Syn:$head filename

Eg:$head student

To display the top two lines:

Syn:$head-2student

i)tail–displays last 10 lines of the file

Syn:$tail filename

Eg:$tail student

To display the bottom two lines;

Syn:$ tail -2 student

j)chmod–used to change the permissions of a file or directory.Syn:$ch mod category operation


permission file

Where, Category–is the user type

Operation–is used to assign or remove permission

43
Permission–is the type of permission

File–are used to assign or remove permission all

Examples:

$chmodu-wx student

Removes write and execute permission for users

$ch modu+rw,g+rwstudent

Assigns read and write permission for users and groups

$chmodg=rwx student

Assigns absolute permission for groups of all read, write and execute permissions

k)wc–it counts the number of lines, words, character in a specified file(s).

VIVA QUESTIONS:
1. What is the purpose of the 'ls' command in Linux and how is it used?
2. How can the 'mkdir' command be used to create a new directory in Linux?
3. Explain the difference between the 'cp' and 'mv' commands in Linux.
4. What is the 'grep' command used for in Linux and how can it be used in conjunction with other
commands?
5. How can you use the 'chmod' command to change the permissions of a file in Linux?

44
.EXPERIMENT – 13

AIM-
Write a shell script to add two numbers.

THEORY-
A shell script is a type of program that is written in a scripting language for a Unix-based operating
system shell, such as bash, sh, zsh, or csh. Shell scripts are used for automating tasks and performing
various operations in a command-line interface. They are typically saved in a text file with a .sh
extension and can be executed by running the script file in a terminal window. Shell scripts can be
used to execute commands, manipulate files and directories, and perform system administration
tasks, among other things.

ALGORITHM
# Ask the user to input the first number
read -p "Enter the first number: " num1
# Ask the user to input the second number
read -p "Enter the second number: " num2
# Add the two numbers together
sum=$((num1 + num2))

# Display the result


echo "The sum of $num1 and $num2 is: $sum"

VIVA QUESTIONS:
1.What does the #!/bin/bash line at the beginning of the script signify?
2.How does the read command work in Bash scripting?
3.How is arithmetic operation performed in Bash scripting?
4.How is the sum of two numbers stored in a variable in this script?
5.How can you modify this script to add more than two numbers together?

45
EXPERIMENT – 14
AIM-
Write a shell script to check whether number enter by user is even or odd.
THEORY:
In this shell script, we will prompt the user to enter a number. We will then use the modulo operator
(%) to check if the number is divisible by 2. If the remainder is 0, the number is even. If the
remainder is not 0, the number is odd.

ALGORITHM:
1.Start
2.Prompt the user to enter a number
3.Read the number entered by the user
4.Check if the number is divisible by 2 (i.e., number % 2 is equal to 0)
a)If the number is divisible by 2, print that the number is even
b)If the number is not divisible by 2, print that the number is odd
End.year."

VIVA QUESTIONS:
1. What is a even number?
2. What is the condition to check even number?

46
EXPERIMENT – 15
AIM-
Write a shell script to read from a fie.

ALGORITHM:
#!/bin/bash
# Prompt user for file name
echo "Enter the name of the file to read from: "
read filename

# Check if the file exists


if [ ! -f "$filename" ]; then
echo "File does not exist"
exit 1
fi

# Read each line from the file and print it


while IFS= read -r line;
do
echo "$line"
done < "$filename"
exit 0
VIVA QUESTIONS:
1. Can you explain the concept of variables in shell scripting?
2. How do you use loops in shell scripting?
3. What are the different types of shell scripting constructs?
4. How do you handle errors in shell scripting?
5. Can you explain the use of functions in shell scripting?

47

You might also like