Os Lab Manual New
Os Lab Manual New
SCHOOL OF COMPUTING
Department of Computing Technologies
REGULATION 2021
Laboratory Manual
(Semester III)
Prepared by,
1
Vision of the Department
Program Educational Objectives (PEO) for the Computing Technologies program describes
accomplishments that graduates are expected to attain within a few years of graduation.
PREFACE
The 21CSC202J – OPERATING SYSTEMS Lab is designed to provide students with practical
experience in implementing fundamental operating system using various programming techniques. This lab
focuses on helping students understand and apply theoretical concepts in operating system, enabling them
to write efficient code for real-world problems.
As a critical component of computer science and engineering, understanding operating systems is essential
for any aspiring software developer or systems engineer. In this lab, you will explore core concepts such as
process management, memory management, file systems, and concurrency. Through hands-on experiments
and projects, you will gain practical experience that reinforces theoretical knowledge and prepares you for
real-world challenges.
Each lab is structured to foster not only technical skills but also problem-solving and critical thinking
abilities. Students will have the opportunity to work with various operating systems, utilizing tools and
environments that reflect industry standards. Additionally, the lab encourages collaboration and discussion,
allowing students to learn from peers and share insights.
By the end of the lab, students will have gained valuable experience in applying operating system in
a range of contexts, preparing them for more advanced studies and professional challenges in computer
science and software development.
2
LABORATORY ORIENTATION
I. OVERALL PURPOSE
The primary purpose of the Operating Systems Lab is to bridge the gap between theoretical knowledge and
practical application in the field of operating systems. Here are the key objectives to provide students with
practical experience in interacting with and managing operating systems, reinforcing classroom learning
through experimentation. To deepen comprehension of fundamental operating system principles such as
process management, memory management, file systems, and concurrency.
To develop critical technical skills, including programming, scripting, debugging, and system configuration,
which are essential for any IT professional. To enhance problem-solving abilities by engaging students in
real-world scenarios that require analytical thinking and troubleshooting skills. To foster teamwork and
communication skills through group projects and discussions, preparing students for collaborative work
environments.
To encourage exploration of current trends and innovations in operating systems, promoting creativity and
critical thinking. To equip students with the knowledge and skills necessary for careers in software
development, systems administration, and related fields, ensuring they are well-prepared for industry
demands. Overall, the lab aims to create a rich learning environment where students can apply their
knowledge, develop practical skills, and prepare for future challenges in the field of operating systems.
Every week before lab, each student should read over the laboratory experiment and work out the various
suitable logics, etc. that are outlined. The student should refer to the text as prescribed in the course
description for the fundamental theory.
Your grade will reflect how well you have prepared for the lab. It is a standard engineering practice that
each student maintains a laboratory notebook. The notebook should be a permanent document that is
maintained and witnessed properly, and that contains accurate records of all lab sessions.
The lab report grade will reflect the students' ability to communicate what he or she has accomplished.
Laboratory and equipment maintenance is the responsibility of not only the laboratory staff, but also the
students. A concerted effort to keep the equipment in excellent condition and the working environment well-
organized will result in a productive and safe laboratory. Above all, keep in mind that safety is first!
Each student should maintain a laboratory notebook according to the following guidelines:
1. Obtain a notebook whose pages are consecutively numbered. About 228 pages may be adequate.
2. Dedicate the notebook solely to this lab.
3. Write name, register number, course code and name and section on the cover.
4. Record the analysis and output by pen, not pencil.
5. Do not leave intervening blank page or space. Cross out empty space.
6. Demonstrate to the lab staff of your understanding and achievement of the lab objectives.
7. Have the lab staff sign and date all data groups before completing each laboratory session. It is the
responsibility of both the staff and the student to make sure that the data is within expectation before the
student leaves each lab session.
3
IV. PRE-LAB WORK
For each experiment in the Operating system lab, there is a pre-lab discussion that must be completed in
your logbook before entering the laboratory. To ensure that you are well-prepared for your Operating
System Lab sessions, please complete the following pre-lab work familiarize yourself with the fundamental
concepts of operating systems, including: Process management, Memory management, File systems,
Concurrency.
Thoroughly read the lab manual for the upcoming session to understand the objectives, required materials,
and expected outcomes of the experiments. Ensure you have the necessary software installed on your
machine, such as: A virtual machine software (e.g., VirtualBox, VMware), The operating systems you will
be working with (e.g., Linux distributions), Familiarize yourself with the command line interface (CLI) of
the OS you will be using.
To ensure that you can complete the experimental tasks within the allocated lab session, it is recommended
to review and write pseudocode, understand the algorithms, and outline the operating system you will be
implementing before the lab. This preparation will allow you to focus more on coding, debugging, and
testing during the lab session, thereby maximizing your learning and practice time.
Here are five key safety precautions and laboratory rules for a computer lab:
4
VI. INTERNAL EVALUATION METHODS
The objective of this lab is to teach students various operating system and to explain them the importance
of operating system in context of writing algorithms for performing various concepts on operating system.
Students will gain practical knowledge by writing and executing programs in deepen comprehension of
fundamental operating system principles such as process management, memory management, file systems,
and concurrency.
5
Experiment List: 21CSC202J – OPERATING SYSTEMS Lab
Course Outcome
No. Lab Experiments Sessions
(CO)
a. Operating system Installation 1 CO - 1
1
b. Booting Process of Linux
a. Basic Linux Commands 2 CO - 1
2
b. Filters and Admin Commands
3 Shell Programs 3 CO - 1
4 Process Creation 4 CO - 2
5 Multithreading 5 CO - 2
6 Mutual Exclusion-Semaphore and Reader Writer 6 CO - 2
Solution
7 Dining Philosopher problem 7 CO - 2
8 CPU Scheduling Algorithms - FCFS and SJF 8 CO - 3
9 CPU Scheduling Algorithms – Priority and Round 9 CO - 3
Robin
10 Bankers Algorithm - Deadlock Avoidance 10 CO - 3
11 Memory Allocation Techniques First-Best-Worst Fit 11 CO - 4
12 Page Replacement Algo - FIFO-LRU-LFU 12 CO - 4
13 Disk Scheduling Algorithms-FCFS-SCAN-C-SCAN 13 CO - 5
14 File Allocation-Sequential-Indexed 14 CO - 5
3 Exemplify different types PO1-Engineering Lab 8: CPU Scheduling Algorithms - FCFS and
of scheduling algorithms Knowledge SJF
and deadlock mechanism PO2-Problem Lab 9: CPU Scheduling Algorithms – Priority and
Analysis Round Robin
PO3-Design and Lab 10: Bankers Algorithm - Deadlock Avoidance
development of
solutions
PO4- Conduct
investigations
of complex
problems
7
IX. RUBRICS FOR EVALUATION OF LABORATORY REPORT
CRITERIA EXCELLENT (10) GOOD (7) SATISFACTORY (5) NEEDS IMPROVEMENT (3)
The solution The solution is correct The solution is correct but The solution is partially correct or
demonstrates a deepand efficient but may have uses a less optimal approach,inefficient, using the operating
Basic Solution understanding ofslightly less optimal time with some improvementssystem concept.
the operating system,or space complexity in needed in efficiency. It lacks handling of edge cases,
using optimalsome parts. It handles basic cases well has poor or unclear
approaches with clear,It addresses most edge but misses some edge cases explanations, and may contain
efficient code. cases and is generally or has incomplete errors or redundancies.
It covers all edge cases, well-explained, but lacks explanations.
and includes thorough some detail or could be
explanations. cleaner.
The implementation is The code is mostly The code has someThe implementation lacks
Modularity highly modular, with modular, with separate modularity, but severalmodularity, with a monolithic
well-defined, reusable functions and classes for functions or classes perform structure where functions or classes
functions and classes distinct tasks, but could multiple tasks, making them are not well-defined or reusable.
that follow the single benefit from further harder to reuse or extend. Modifications or extensions are
responsibility principle. decomposition. Changes or extensions are challenging due to tightly coupled
It allows for easy It allows for reasonable possible but may require components, leading to difficulty in
modifications, ease in making changes or significant refactoring, maintenance and testing.
extensions, and testing adding new features, but indicating moderate
of individual some parts are slightly coupling between
components without interdependent. components.
affecting the overall
system.
Readability The code is clear, well-The code is generally The code is readable but hasThe code is difficult to read due to
organized, and easy to readable, with appropriate several areas that are difficultpoor naming conventions, lack of
understand, withvariable names and some to understand due to comments, and inconsistent
meaningful variablecomments, but could ambiguous variable names,formatting, making comprehension
names, concisebenefit from more detailed insufficient comments, orchallenging.
comments, and well-explanations in complex dense logic. It does not adhere to standard
structured formatting. sections. There is some adherence to coding practices, and the
There is consistent use It follows most coding coding conventions, but structure is cluttered, which
of coding standards standards, but there may inconsistencies in formatting significantly affects readability
and conventions, be occasional or structure make it harder to and maintainability.
making the code inconsistencies or follow.
approachable for both formatting issues that
new and experienced slightly hinder readability.
developers.
Validation The implementationThe implementation The implementation has basicThe implementation lacks proper
includes includes validation for validation for some inputs, butvalidation, allowing invalid or
comprehensive most common inputs and it does not cover all edgeunexpected inputs to cause failures
validation checks for allscenarios but may miss cases, making it prone to or incorrect results.
input types, edge cases, handling some less potential errors or unexpected Error messages are unclear or
and potential errors,frequent edge cases or behavior. nonexistent, with little to no
ensuring robustness and special conditions. Error handling is minimal, exception handling, making the
reliability. Error messages and and error messages may not code unreliable and difficult to
It uses clear error handling are mostly clear, be informative, making debug.
messages and proper but there could be room debugging more challenging.
exception handling, for improvement in some
making it easy to areas to enhance
debug and understand robustness.
any issues that arise
during execution.
8
Scalability The implementation isThe implementation is The implementation handlesThe implementation is not scalable,
highly scalable, andreasonably scalable, with small to medium-sizedwith poor performance on multiple
optimized for both time good performance on datasets adequately butinput due to inefficient algorithms,
and space complexity,moderately large datasets, struggles with all inputs. leading to high time or space
handling all inputbut may require There is limited support for complexity.
efficiently. optimization for very large scaling, with parts of the codeThe code design is rigid, making
The code design inputs. needing significant changesit difficult to scale without major
allows for easy The design is somewhat or optimizations to handlemodifications, and lacks support
scaling, with minimal modular, allowing for increased load. for parallelism or distributed
modifications needed scaling with some processing.
to accommodate all changes, but certain
inputs or distributed parts of the code may
processing. need refactoring for
significant growth.
Outstanding The student demonstrates exceptional knowledge, answers all questions with clarity and confidence,
(5) covers edge cases and optimizations thoroughly, and showcases critical thinking by providing
insights beyond the standard curriculum.
Very good The student shows strong understanding, gives clear and concise answers, covers most edge cases,
(4) and can discuss optimizations and alternative approaches.
Good (3) The student demonstrates good comprehension, answers questions with confidence, and provides
logical explanations for their choices in implementation, but misses out on some finer points.
Average The student shows a reasonable understanding of core concepts and answers most basic questions
Viva (2.5) correctly but struggles with deeper, more complex questions or implementation details.
Fair (2) The student demonstrates a basic grasp of fundamental concepts but has difficulty answering
questions beyond the most basic level or relating theory to practice.
Poor (1) The student has minimal understanding, is unable to explain most of the concepts correctly, and
provides incorrect answers with little clarity.
Very Poor The student shows no understanding of basic concepts, struggles to answer even simple questions,
(0) and is unable to explain their own implementation.
9
Exp. No: 1a OPERATING SYSTEM INSTALLATION
Aim:
To perform the Linux operating system can be installed as either dual OS in your system or you can install
through a virtual machine (VM).
Pre-Lab Discussion:
In the pre-lab discussion for the experiment "Operating System installation," we will understand the
importance of OS installation in configuring a system. Familiarize yourself with the prerequisites for
installing various operating systems. Discuss the minimum hardware specifications needed for different
operating systems (CPU, RAM, storage). Importance of backing up data before installation and
understanding recovery options. Walk through the general steps involved in OS installation. Discuss
potential issues that may arise during installation, such as hardware compatibility, partition errors, and boot
failures.
Steps
1. Download VMware Player or Workstation recent version.
2. Download Ubuntu LTS recent version.
3. Install VM ware Player in your host machine.
4. Open VMware Workstation and click on "New Virtual Machine".
5. Select "Typical (recommended)" and click "Next".
6. Select "Installer disc image (ISO)", click "Browse" to select the Ubuntu ISO file, click "Open" then
"Next".
7. You have to type in "Full name", "User name" that must only consist of lowercase and numbers then
you must enter a password. After you finished, click "Next".
8. You can type in a different name in "Virtual machine name" or leave as is and select an appropriate
location to store the virtual machine by clicking on "Browse" that is next to "Location" -- you should place
it in a drive/partition that has at least 5GB of free space. After you selected the location click "OK" then
"Next".
9. In "Maximum disk size" per Ubuntu recommendations you should allocate at least 5GB
-- double is recommended to avoid running out of free space.
10. Select "Store virtual disk as a single file" for optimum performance and click "Next".
11. Click on "Customize" and go to "Memory" to allocate more RAM -- 1GB should suffice, but more
is always better if you can spare from the installedRAM.
12. Go to "Processors" and select the "Number of processors" that for a normal computer is 1 and
"Number of cores per processor" that is 1 for single core, 2 for dual core, 4 for quad core and so on -- this
is to insure optimum performance of thevirtual machine.
13. Click "Close" then "Finish" to start the Ubuntu install process.
14. On the completion of installation, login to the system
10
Ex. No. 1b BOOTING PROCESS OF LINUX
Press the power button on your system, and after few moments you see the Linux login prompt. From the
time you press the power button until the Linux login prompt appears, the following sequence occurs. The
following are the 6 high level stages of a typical Linux bootprocess.
Step 1.BIOS
Step 4. Kernel
When the Linux system is booting up, you might see various services getting started.For example, it
might say “starting sendmail …. OK”. Those are the runlevel programs, executed from the run level
directory as defined by your run level. Depending on your default init level setting, the system will
execute the programs fromone of the following directories.
12
o Run level 0 – /etc/rc.d/rc0.d/
o Run level 1 – /etc/rc.d/rc1.d/
o Run level 2 – /etc/rc.d/rc2.d/
o Run level 3 – /etc/rc.d/rc3.d/
o Run level 4 – /etc/rc.d/rc4.d/
o Run level 5 – /etc/rc.d/rc5.d/
o Run level 6 – /etc/rc.d/rc6.d/
Login Process
Post-Lab Questions:
1. What were the key steps you followed during the OS installation process?
2. Did you encounter any unexpected challenges? If so, how did you resolve them?
3. What type of installation did you perform (fresh, dual boot, virtual)? Why did you choose this
method?
4. What user configurations did you set up during the installation (e.g., user accounts, passwords)?
5. How does the installation process of this OS compare to others you’ve experienced (e.g., Windows,
macOS, or different Linux distributions)?
Result:
The installation of Ubuntu was successful, with the system performing well post-installation. The
experience provided valuable insights into OS installation and configuration.
13
Exp No: 2 BASIC LINUX COMMANDS
Aim:
To perform the implementation of basic linux commands.
Pre-Lab Discussion:
The purpose of this pre-lab discussion is to introduce students to basic Linux commands, providing them
with foundational knowledge necessary to complete lab tasks. This includes file navigation, file
management, and understanding the Linux file system structure. By the end of this session, students should
feel comfortable using the Linux command-line interface (CLI).
a) Basics
6. mv f1 f2 ➔ rename file f1 as f2
14
c) Working with Directories
3. ls [gpy]et ➔ list files whose first letter is any one of the character g, p
or y and followed by the word et
4. ls [a-d,l-m]ring ➔ list files whose first letter is any one of the character
from a to d and l to m and followed by the word ring.
e) I/O Redirection
1. Input redirection
wc –l < ex1 ➔ To find the number of lines of the file ‘ex1’
2. Output redirection
who > f2 ➔ the output of ‘who’ will be redirected to file f2
f) Piping
Syntax : Command1 | command2
head –6 f1 |tail –2 ➔ prints the 5th & 6th lines of the file f1.
g) Environment variables
1. echo $HOME ➔ display the path of the home directory
3. echo $PS2 ➔ display the second prompt string ( > symbol by default )
Method-1
Method-2
Each digit is specified as the sum of following 4 – read permission, 2 – write permission, 1 –
execute permission ex. chmod 754 f1
read, write & execute permissions for the user ie; 4+2+1 = 7
read, & execute permissions for the group members ie; 4+0+1 = 5
16
Ex. No. 2b FILTERS and ADMIN COMMANDS
FILTERS
1. cut
■ Used to cut characters or fileds from a file/input
Syntax : cut -cchars filename
-ffieldnos filename
■ By default, tab is the filed separator(delimiter). If the fileds of the files are separated byany
other character, we need to specify explicitly by –d option
2. grep
■ Used to search one or more files for a particular pattern.
Syntax : grep pattern filename(s)
3. sort
■ Used to sort the file in order
Syntax : sort filename
4. Uniq
■ Displays unique lines of a sorted file
Syntax : uniq filename
-d option displays only the duplicate lines
-c displays unique lines with no. of occurrences.
17
5. diff
■ Used to differentiate two files
Syntax : diff f1 f2
compare two files f1 & f2 and prints all the lines that are differed between f1& f2.
Q2. Write a command to display user-id of all the users in your system.
$
Q3. Write a command to check whether the user judith is available in your system or
not.(use grep)
$
Q4. Write a command to display the lines of the file f1 starts with SRM.
$
Q6. Write a command to display the unique lines of the sorted file f21. Also display the number
of occurrences of each line.
$
Q7. Write a command to display the lines that are common to the files f1 and f2.
$
18
Q8. Update the package repositories
MANAGING USERS
To add a user:
sudo adduser username
To disable a user:
sudo passwd -l username
To enable a user:
sudo passwd -u username
To delete a user:
sudo userdel –r
username To create a group:
sudo addgroup groupname
To delete a group:
sudo delgroup groupname
If you do not want to run the commands in terminal to manage users and groups, then youcan
install a GUI add-on .
sudo apt install gnome-system-tools
Once done, type
users-admin
19
Q11. Create a user ‘elias’. Login to the newly created user and exit.
Q12. Disable the user ‘elias’, try to login and enable again.
Post-Lab Questions:
1. How do you display the current directory you are working in? What is the significance of this
command in Linux?
2. Describe the purpose of the ls command and explain two commonly used options.
3. Explain the difference between cp and mv commands. Provide an example of each.
4. What command would you use to display the first 10 lines of a file? How would you display only
the last 10 lines of the file?
5. How does the grep command work? Provide an example of how to search for a specific word in a
file.
Result:
The implementation of essential Linux commands and filtering techniques, laying the
foundation for efficient navigation and manipulation of files within a Linux environment explored
successfully.
20
Exp No: 3 SHELL PROGRAMS
Aim:
To perform the learn to use various shell commands and integrate them into scripts to perform complex
operations.
Pre-Lab Discussion
The purpose of this pre-lab discussion is to introduce students to shell programming in an operating system
environment. Shell scripts enable users to automate repetitive tasks, manage system processes, and interact
with the OS through a command-line interface (CLI). This discussion will cover basic shell concepts,
structure, and essential commands needed for writing and executing shell programs. A shell is a program
that interprets and executes commands entered by a user. It acts as an interface between the user and the
operating system. Shell programming (or scripting) involves writing sequences of shell commands in a
script file to automate tasks. Instead of typing commands manually, a script allows you to execute a series
of commands automatically, improving efficiency and reducing errors
pat2) ...
*) ...
esac
21
Syntax for for-loop
for var in list-of-values
do
----
----
done
echo num
echo $num
echo $x
echo ‘$x’
echo “$x”
echo $y
echo $(date)
echo $a
echo \$num
echo \$$num
22
Q1. Find the output of the following shell scripts
$ vi ex31
echo Enter value for nread
n sum=0 i=1
while [ $i –le $n ]do
sum=$((sum+i))i=$((i+2))
done
echo Sum is $sum
Output :
Q2. Write a program to check whether the file has execute permission or not. If not, add
the permission.
$ vi ex32
Q3. Write a shell script to list only the name of sub directories in the present working
directory
$ vi ex33
Q4. Write a program to check all the files in the present working directory for a pattern
(passed through command line) and display the name of the file followed by a message stating
that the pattern is available or not available.
$ vi ex34
Post-Lab Questions:
1. How do you make a shell script executable, and why is this necessary?
2. What command would you use to display the contents of a variable within a script?
3. How does piping (|) work in shell scripts? Provide an example that lists files and filters the output using
grep.
4. Write a shell function that takes two arguments and prints their sum
5. What is the difference between > and >> in shell scripting?
Result:
The practical skills gained during the lab, ensuring that the concepts and applications of shell scripting in
an operating system environment, outputs are validated.
23
Exp No: 4 PROCESS CREATION using fork() and Usage of getpid(), getppid(), wait() functions
Aim:
To implement the PROCESS CREATION using fork() and Usage of getpid(), getppid(), wait() functions.
Pre-Lab Discussion:
To provide an overview of process creation in an Operating System (OS), focusing on how processes are
created, managed, and terminated. Understanding these concepts is crucial for grasping how multitasking
and resource management work in modern OS environments. This discussion will cover the fundamental
concepts of processes, system calls used for process creation, and related mechanisms such as process
states, parent-child relationships, and inter-process communication (IPC).
Compilation of C Program
Step 1 : Open the terminal and edit your program and save with extension “.c”Ex.
nano test.c
Virtual fork
vfork() is similar to fork but both processes shares the same address space.
#include <stdio.h>
#include<unistd.h>int main()
{
int a=5,b=10,pid;
printf("Before fork a=%d b=%d \n",a,b);pid=fork();
if(pid==0)
{
a=a+1; b=b+1;
24
printf("In child a=%d b=%d \n",a,b);
}
else
{
sleep(1);
a=a-1; b=b-1;
printf("In Parent a=%d b=%d \n",a,b);
}
return 0;}
Q2. Rewrite the program in Q1 using vfork() and write the output
#include <stdio.h>
#include<unistd.h>int main()
{
int a=5,b=10,pid;
printf("Before fork a=%d b=%d \n",a,b);pid=vfork();
if(pid==0)
{
a=a+1; b=b+1;
printf("In child a=%d b=%d \n",a,b);
}
else
{
sleep(1);
a=a-1; b=b-1;
printf("In Parent a=%d b=%d \n",a,b);
}
return 0;
}
#include <stdio.h>
#include<unistd.h>
int main()
{
fork();
fork();
fork();
printf(“SRMIST\n”);
return 0;
25
Q4. Complete the following program as described below :
The child process calculates the sum of odd numbers and the parent process calculate thesum of even
numbers up to the number ‘n’. Ensure the Parent process waits for the child process to finish.
#include <stdio.h>
#include<unistd.h>
int main()
{
int pid,n,oddsum=0,evensum=0;
return 0;
}
Sample Output :
Enter the value of n 10
Sum of odd numbers 25
Sum of even numbers : 30
Q5. How many child processes are created for the following code?
Hint : Check with small values of ‘n’.
Output :
Q6. Write a program to print the Child process ID and Parent process ID in both Childand
Parent processes
#include <stdio.h>
#include<unistd.h>int
main()
{
return 0;
}
Sample Output:
26
In Child Process
Parent Process ID : 18
Child Process ID : 20
In Parent Process
Parent Process ID : 18
Child Process ID : 20
Q7. How many child processes are created for the following code?
#include <stdio.h>
#include<unistd.h>
int main()
{
}
Output
Post-Lab Questions:
1. Explain how the fork() system call works. What does it return to the parent and child
processes?
2. What is the purpose of the exec() system call? How does it differ from fork()?
3. What is the difference between a program and a process?
4. After a successful fork(), both the parent and child processes execute the same code. How can
the parent and child processes distinguish between each other?
5. What is the purpose of the exec() system call? How does it differ from fork()?
Result:
Thus, the program for implementing understanding of process creation, system calls, and process
management in operating systems, executed successfully.
27
Exp No: 5 MULTI-THREADING
Aim
This experiment aims to understand the concept of multithreading in programming, explore how
multiple threads can run concurrently within a single process, and implement multithreading.
Pre-Lab Discussion:
The goal of this pre-lab discussion is to introduce the concept of multithreading in operating systems
and programming, and to prepare students for hands-on experimentation with creating and managing
threads. Multithreading enables concurrent execution of tasks within a single process, which can lead
to more efficient and responsive applications. This discussion will cover the fundamentals of threads,
thread management, synchronization, and common challenges in multithreaded programming.
Multithreading is a technique where multiple threads are executed concurrently within a single
process. A thread is the smallest unit of execution within a process and shares the process's resources,
such as memory and file descriptors, with other threads in the same process.
Unlike Java, multithreading is not supported by the language standard. POSIX Threads (or
Pthreads)is a POSIX standard for threads. Implementation of pthread is available with gcc
compiler.
We must include the pthread.h header file at the beginning of the script to use all the
functions of the pthreads library.
28
thread, const pthread_attr_t * attr, void *
(*start_routine)(void *), void *arg);
Parameters:
• thread: pointer to an unsigned integer value that returns the thread id of the thread
created.
• attr: pointer to a structure that is used to define thread attributes like detachedstate, scheduling
policy, stack address, etc. Set to NULL for default thread attributes.
• start_routine: pointer to a subroutine that is executed by the thread. The return type and
parameter type of the subroutine must be of type void *. Thefunction has a single attribute
but if multiple values need to be passed to thefunction, a struct must be used.
• arg: pointer to void that contains the arguments to the function defined in the earlier
argument
e. pthread_equal: compares whether two threads are the same or not. If the two threadsare
equal, the function returns a non-zero value otherwise zero.
Syntax:
int pthread_equal(pthread_t t1, pthread_t t2);
Parameters: This method accepts following parameters:
• t1: the thread id of the first thread
• t2: the thread id of the second thread
Applications
Threading is used widely in almost every field.
Most widely it is seen over the internet now days where we are using transaction processing of everytype
like recharges, online transfer, banking etc.
Threading is a segment which divide the code into small parts that are of very light weight and has less
burden on CPU memory so that it can be easily worked out and can achieve goal in desired field.
The concept of threading is designed due to the problem of fast and regular changes in technology andless
29
the work in different areas due to less application.
Create 3 threads, first one to find the sum of odd numbers; second one to find the sum of
evennumbers; third one to find the sum of natural numbers;
This program also displays the list of odd/even numbers.
Complete the code snippet wherever applicable in the below program highlighted in red colourfont.
int
je,jo,evensum=0,sumn=0,oddsum=0,evenarr[50],oddarr[50];
for(i=0;i<=n;i++)
{
if(logic to allow only odd numbers)
{Calculate sum of odd numbers only}
}
}
void *SumN( )
{
int i,n;
n=(int)threadid;
for(i=1;i<=n;i++)
{ Calculate sum of natural numbers only}
}
30
int main()
{
pthread_t threads[NUM_THREADS]; int i,t;
printf("Enter a number\n");
scanf("%d",&t);
for(i=0;i<NUM_THREADS;i++)
{
pthread_join(threads[i],NULL);
}
printf("The sum of first N natural numbers is %d\n", display the sum of natural
numbers);printf("The sum of first N even numbers is %d\n",display the sum of even numbers);
printf("The sum of first N odd numbers is %d\n",oddsum);
printf("The first N Even numbers are\n");
Print all the Even numbers
printf("The first N Odd numbers are \n");
Print all the ODD numbers
} pthread_exit(NULL);
Post-Lab Questions:
1. Describe the key differences between threads and processes. Why might you choose to use threads
instead of processes?
2. What is a race condition, and how can it be prevented in a multithreaded application?
3. Discuss how multithreading can impact the performance of an application. What factors
should be considered to optimize thread performance?
4. What are the primary functions of thread libraries or APIs in different programming languages ?
5. Provide an example of a real-world application or system that benefits from multithreading.
How does multithreading contribute to its functionality?
Result:
Thus, the program has been executed successfully by creating three threads.
31
Exp No: 6 Mutual Exclusion-Semaphore and Reader Writer Solution
Aim:
Pre-Lab Discussion:
Semaphore
Semaphore is used to implement process synchronization. This is to protect critical region shared
among multiples processes.
key ➔ semaphore id
nsems ➔ no. of semaphores in the semaphore array
semflg ➔ IPC_CREATE|0664: to create a new semaphore IPC_EXCL|IPC_CREAT|0664
: to create new semaphore and the
call fails if the semaphore already existsTo
perform operations on the semaphore sets viz., allocating resources, waiting for the resources or freeing
the resources,
int semop(int semid, struct sembuf *semops, size_t nsemops)
If sem_op is –ve, allocate or obtain resources. Blocks the calling process until enough resources
have been freed by other processes, so that this process can allocate.
If sem_op is zero, the calling process waits or sleeps until semaphore value reaches 0.If sem_op is
+ve, release resources.
32
Q1. Execute and write the output of the following program for mutual exclusion using
system V semaphore
#include<sys/ipc.h>
#include<sys/sem.h>int main()
{
int pid,semid,val;struct sembuf sop;
semid=semget((key_t)6,1,IPC_CREAT|0666);pid=fork(); sop.sem_num=0;
sop.sem_op=0; sop.sem_flg=0;
if (pid!=0)
{
sleep(1);
printf("The Parent waits for WAIT signal\n");semop(semid,&sop,1);
printf("The Parent WAKED UP & doing her job\n");sleep(10); printf("Parent
Over\n");
}
else
{
printf("The Child sets WAIT signal & doing her job\n");semctl(semid,0,SETVAL,1); sleep(10);
printf("The Child sets WAKE signal & finished her job\n");semctl(semid,0,SETVAL,0);
printf("Child Over\n");
}
return 0;
}
Output :
POSIX SEMAPHORE
The POSIX system in Linux presents its own built-in semaphore library. To use it, we have to
include semaphore.h and compile the code by linking with
-lpthread - lrt
To initialize a semaphore
sem_init(sem_t *sem, int pshared, unsigned intvalue);
Where,
sem: Specifies the semaphore to be initialized.
pshared : This argument specifies whether or not the newly initialized semaphore is shared
between processes/threads. A non-zero value means the semaphore is shared between processes
33
and a value of zero means it is shared between threads.
value: Specifies the value to assign to the newly initialized semaphore.
To destroy a semaphore
sem_destroy(sem_t *mutex);
Q2. Program creates two threads: one to increment the value of a shared variable and
second to decrement the value of the shared variable. Both the threads make use of
semaphore variable so that only one of the threads is executing in its critical section.
Execute and write the output.
#include<pthread.h>
#include<stdio.h>
#include<semaphore.h>
#include<unistd.h> void
*fun1();
void *fun2();
int shared=1; //shared variablesem_t s;
//semaphore variable int main()
{
sem_init(&s,0,1); //initialize semaphore variable - 1st argument is
//address of variable, 2nd is number of processes sharing semaphore,
//3rd argument is the initial value of semaphore variablepthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);sleep(1);
pthread_create(&thread2, NULL, fun2, NULL); pthread_join(thread1,
NULL);
pthread_join(thread2,NULL);
printf("Final value of shared is %d\n",shared); //prints the last
//updated value of shared variable
}
void *fun1()
{
int x;
sem_wait(&s); //executes wait operation on s x=shared;//thread1 reads value
of shared variableprintf("Thread1 reads the value as %d\n",x); x++; //thread1
increments its value printf("Local updation by Thread1: %d\n",x); sleep(1);
//thread1 is preempted by thread 2
shared=x; //thread one updates the value of shared variableprintf("Value of shared variable
updated by Thread1 is:
%d\n",shared);
sem_post(&s);
}
void *fun2()
{
int y; sem_wait(&s);
y=shared;//thread2 reads value of shared variableprintf("Thread2 reads the
value as %d\n",y);
y--; //thread2 increments its value printf("Local updation by Thread2:
%d\n",y);sleep(1); //thread2 is preempted by thread 1
34
shared=y; //thread2 updates the value of shared variableprintf("Value of shared
variable updated by Thread2 is:
%d\n",shared);
sem_post(&s);
}
The final value of the variable shared will be 1. When any one of the threads executes the wait
operation the value of “s” becomes zero. Hence the other thread (even if it preempts the running
thread) is not able to successfully execute the wait operation on “s“. Thus, not able to read the
inconsistent value of the shared variable. This ensures that only one of the threads is running in
its critical section at any given time.
Output:
Reader Writer Solution
In a reader-writer problem, multiple readers can read data from a shared resource, while onlyone
writer can write data to the resource. The challenge is to ensure that the readers do not read data while
the writer is writing, and the writer does not write data while the readers are reading.
For example, consider a scenario where a database is being accessed by multiple users. Theusers can
read data from the database, but only one user can write data to the database at a time. The challenge
is to ensure that the users do not read data while the database is being written to, and the writer does
not write data while the users are reading.
Q3.
/*
This program provides a possible solution for first readers writersproblem using mutex and
semaphore.
I have used 10 readers and 5 producers to demonstrate the solution.You can always play with
these values.
*/
}
void *reader(void *rno)
{
35
// Reader acquire the lock before modifying numreader pthread_mutex_lock(&mutex);
numreader++; if(numreader
== 1) {
sem_wait(&wrt); // If this id the first reader, then it willblock the writer
}
pthread_mutex_unlock(&mutex);
// Reading Section
printf("Reader %d: read cnt as %d\n",*((int *)rno),cnt);
int main()
{
pthread_t read[10],write[5];
pthread_mutex_init(&mutex, NULL);
sem_init(&wrt,0,1);
pthread_mutex_destroy(&mutex);sem_destroy(&wrt);
return 0;
Output:
36
Post-Lab Questions:
Result:
Thus, the program for implementing Mutual Exclusion-Semaphore and Reader WriterSolution was
written and executed successfully.
37
Exp No: 7 Dining Philosopher problem
Aim
Pre-Lab Discussion:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
38
sem_t room;
sem_t chopstick[5];
void * philosopher(void * num)
{
//Write coding for Main Philosopher thread
int main()
{
int i,a[5]; pthread_t tid[5];
sem_init(&room,0,4);for(i=0;i<5;i++) sem_init(&chopstick[i],0,1);
for(i=0;i<5;i++)
{ a[i]=i;
pthread_create(&tid[i],NULL,philosopher,(void *)&a[i]);
}
for(i=0;i<5;i++)
pthread_join(tid[i],NULL);
}
Post-Lab Questions:
1. Describe the Dining Philosophers Problem. What are the main challenges associated with solving this
problem?
2. What are the common approaches to solving the Dining Philosophers Problem? Briefly describe at
least two approaches.
3. How can starvation be avoided in the Dining Philosophers Problem? What methods ensure that all
philosophers get a chance to eat?
4. Reflect on any challenges or issues you encountered while implementing the Dining Philosophers
Problem. How did you address these issues?
5. What strategies can be employed to avoid deadlock in the Dining Philosophers Problem?
Result:
Thus, the program for implementing Dining Philosophers Problem was written and executed
successfully.
39
Exp No: 8 SCHEDULING ALGORITHMS FCFS-SJF
Aim:
Pre-Lab Discussion:
Given n processes with their burst times, the task is to find average waiting time and averageturn around
time using FCFS scheduling algorithm. First in, first out (FIFO), also known as first come, first served
(FCFS), is the simplest scheduling algorithm. FIFO simply queues processes in the order that they
arrive in the ready queue.
In this, the process that comes first will be executed first and next process starts only after the previous
gets fully executed. Here we are considering that arrival time for all processesis 0.
Turn Around Time: Time Difference between completion time and arrival time.
Turn Around Time = Completion Time – Arrival Time
Waiting Time(W.T): Time Difference between turn around time and burst time.
Waiting Time = Turn Around Time – Burst Time
Algorithm:
Step 1. Input the processes along with their burst time (bt).
Step 2. Find waiting time (wt) for all processes.
Step 3. As first process that comes need not to wait so
waiting time for process 1 will be 0 i.e. wt[0] = 0.
Step 4. Find waiting time for all other processes i.e. for process i ->
wt[i] = bt[i-1] + wt[i-1]
Step 5. Find turnaround time = waiting_time + burst_time
for all processes.
Step 6. Find average waiting time = total_waiting_time / no_of_processes
Step 7. Similarly, find average turnaround time =
total_turn_around_time / no_of_processes.
Output :
40
Q1. Write a program to implement FCFS Scheduling algorithm
#include <stdio.h>
//Write the program here
To calculate the average waiting time in the shortest job first algorithm the sorting of the process
based on their burst time in ascending order then calculate the waiting timeof each process as
the sum of the bursting times of all the process previous or before tothat process.
ALGORITHM:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU bursttime
Step 4: Start the Ready Q according the shortest Burst time by sorting according tolowest to
highest burst time.
Step 5: Set the waiting time of the first process as ‗0‘ and its turnaround time as itsburst time.
Step 6: Sort the processes names based on their Burt time Step 7: For each process in the ready
queue, calculate
a) Waiting time(n)= waiting time (n-1) + Burst time (n-1)
b) Turnaround time (n)= waiting time(n)+Burst time(n) Step 8: Calculate
c) Average waiting time = Total waiting Time / Number of process
d) Average Turnaround time = Total Turnaround Time / Number of process Step
9:Stop the process
#include <stdio.h>
//Write the program here
Post-Lab Questions:
1. What are the advantages and disadvantages of using the FCFS scheduling algorithm?
2. What is burst time?
3. Describe the Shortest Job First (SJF) scheduling algorithm. How does it differ from FCFS, and what
criteria does it use to schedule processes?
4. Compare the performance of FCFS and SJF scheduling algorithms in terms of average waiting time
and turnaround time. Which algorithm generally performs better and why?
5. How can you determine TAT?
Result:
Thus, the program for implementing FCFS and SJF was written and executed successfully.
41
Exp No: 9 SCHEDULING ALGORITHMS Priority and Round Robin
Aim:
Pre-Lab Discussion:
In operating systems, scheduling algorithms play a crucial role in managing the execution of processes.
Two commonly studied scheduling algorithms are Priority Scheduling and Round Robin Scheduling.
Each algorithm has distinct characteristics, advantages, and trade-offs, making them suitable for
different types of applications and system requirements. Priority Scheduling is a CPU scheduling
algorithm where each process is assigned a priority. The process with the highest priority (or lowest
priority number, in some implementations) is selected for execution first. If multiple processes have the
same priority, they are typically scheduled according to their arrival time (in the case of non-pre-emptive
priority scheduling). Round Robin (RR) is a CPU scheduling algorithm that allocates a fixed time
quantum (or time slice) to each process in the ready queue. Each process is given a chance to execute
for a duration of the time quantum before being pre-empted and moved to the end of the queue. When a
process's time quantum expires, it is moved to the end of the ready queue, and the CPU is allocated to
the next process in the queue.
Algorithm
42
Q1. Write a program to implement Priority Scheduling algorithm
#include <stdio.h>
//Write the program here
ROUND ROBIN
ALGORITHM:
#include <stdio.h>
//Write the program here
Post-Lab Questions:
2. Explain the potential issue of starvation in Priority Scheduling. How can this issue be mitigated?
Result:
Thus, the program for implementing priority and round robin scheduling, was written and executed
successfully.
43
Exp No: 10 BANKERS ALGORITHM-DEAD LOCK AVOIDANCE
Aim:
Data structures
n-Number of process,
m-number of resource types.
Available: Available[j]=k, k – instance of resource type Rj is available.
Max: If max[i, j]=k, Pi may request at most k instances resource Rj.
Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource
RjNeed: If
Need[I, j]=k, Pi may need k more instances of resource type Rj, Need[I, j]=Max[I, j]-
Allocation[I, j];
Safety Algorithm
Let Request i be request vector for the process Pi, If request i=[j]=k, then process Pi wants
k instances of resource type Rj.
44
I;Need i=Need i- Request I;
If the resulting resource allocation state is safe, the transaction is completed and process Pi is
allocated its resources. However if the state is unsafe, the Pi must wait for Request iand the
old resource-allocation state is restored.
ALGORITHM:
#include <stdio.h>
//Write the program here
Post-Lab Questions
1. Describe the primary objective of the Banker's Algorithm in the context of deadlock avoidance.
How does it ensure that the system remains in a safe state?
2. Explain the concept of a "safe state" in the Banker's Algorithm. How does the algorithm determine
if a state is safe?
3. Illustrate how the Banker's Algorithm handles a new resource request from a process. What steps
does the algorithm take to determine if the request can be granted?
4. In what scenarios might the Banker's Algorithm not be the most suitable choice for deadlock
avoidance?
5. How you will calculate Need matrix?
.
Result:
Thus, the program for implementing Banker's Algorithm was written and executed successfully.
45
Exp No.11 MEMORY ALLOCATION TECHNIQUES- FIRST-BEST-WORST FIT
Aim:
Pre-Lab Discussion:
One of the simplest methods for memory allocation is to divide memory into several fixed- sized
partitions. Each partition may contain exactly one process. In this multiple-partition method, when
a partition is free, a process is selected from the input queue and is loaded into the free partition.
When the process terminates, the partition becomes available for another process. The operating
system keeps a table indicating which parts of memory are available and which are occupied.
Finally, when a process arrives and needs memory, a memory section large enough for this process
is provided. When it is time to load or swap a process into main memory, and if there is more than
one free block of memory of sufficient size, then the operating system must decide which free block
to allocate. Best-fit strategy chooses the block that is closest in size to the request. First-fit chooses
the first available block that is large enough. Worst-fit chooses the largest available block.
Q1. Write a program to simulate First, Best and Worst fit memory allocation techniques
algorithm
#include <stdio.h>
//Write the program here
Post-Lab Questions:
1. Describe the First Fit memory allocation algorithm. How does it determine where to allocate a new
block of memory?
2. What are the potential drawbacks of using the First Fit algorithm? How can fragmentation issues
arise?
3. Explain the Best Fit memory allocation algorithm. How does it differ from First Fit, and what
criteria does it use for allocation?
4. Describe the Worst Fit memory allocation algorithm. How does it allocate memory, and how does it
differ from Best Fit?
5. What are the strengths and weaknesses of the Worst Fit algorithm compared to First Fit and Best
Fit?
Result:
Thus, the program for implementing First, Best and Worst fit memory allocation techniques algorithm
was written and executed successfully.
46
Exp No: 12 PAGE REPLACEMENT ALGORITHMS FIFO- LRU - LFU
Aim:
Pre-lab Discussion:
Page replacement algorithms are an important part of virtual memory management and it helps the OS
to decide which memory page can be moved out making space for the currently needed page.
However, the ultimate objective of all page replacement algorithms is to reduce the number of page
faults.
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 thequeue. When a page
needs to be replaced page in the front of the queue is selected for removal.
LRU-The LRU stands for the Least Recently Used. It keeps track of page usage in the memory over a
short period of time. It works on the concept that pages that have been highly used in the past are
likely to be significantly used again in the future. It removes the page that has not been utilized in the
memory for the longest time. LRU is the most widely used algorithm because it provides fewer page
faults than the other methods.
The LFU page replacement algorithm stands for the Least Frequently Used. In the LFU page
replacement algorithm, the page with the least visits in a given period of time is removed. It replaces
the least frequently used pages. If the frequency of pages remains constant, the page that comes first is
replaced first.
Q1. Write a program to simulate FIFO, LRU and LFU page replacement techniques algorithm
#include <stdio.h>
//Write the program here
Post-Lab Questions:
1. Describe the FIFO page replacement algorithm. How does it determine which page to replace when
a page fault occurs?
2. What are the advantages and disadvantages of the FIFO page replacement algorithm? How does it
compare to other algorithms in terms of performance?
3. Explain the LRU page replacement algorithm. How does it determine which page to replace?
4. Describe the LFU page replacement algorithm. How does it determine which page to replace?
5. What are the strengths and weaknesses of the LFU algorithm compared to FIFO and LRU?
Result:
Thus, the program for implementing FIFO, LRU and LFU page replacement techniques algorithm was
written and executed successfully.
47
Exp No:13 DISK SCHEDULING ALGORITHMS FCFS-SCAN-C-SCAN
Aim:
Pre-Lab Discussion:
One of the responsibilities of the operating system is to use the hardware efficiently. For the disk drives,
meeting this responsibility entails having fast access time and large disk bandwidth. Both the access time
and the bandwidth can be improved by managing the order in which disk I/O requests are serviced which
is called as disk scheduling. The simplest form of disk scheduling is, of course, the first-come, first-
served (FCFS) algorithm. This algorithm is intrinsically fair, but it generally does not provide the fastest
service. In the SCAN algorithm, the disk arm starts at one end, and moves towards the other end,
servicing requests as it reaches each cylinder, until it gets to the other end of the disk. At the other end,
the direction of head movement is reversed, and servicing continues. The head continuously scans back
and forth across the disk. C-SCAN is a variant of SCAN designed to provide a more uniform wait time.
Like SCAN, C-SCAN moves the head from one end of the disk to the other, servicing requests along
the way. When the head reaches the other end, however, it immediately returns to the beginning of the
disk without servicing any requests on the return trip
Q1. Write a program to simulate disk scheduling algorithms FCFS-SCAN and C-SCAN
#include <stdio.h>
//Write the program here
Post-Lab Questions
1. Describe the FCFS disk scheduling algorithm. How does it determine the order in which disk I/O
requests are serviced?
2. What are the advantages and disadvantages of the FCFS disk scheduling algorithm? How does it
compare to other algorithms in terms of performance?
3. Explain the SCAN disk scheduling algorithm. How does it differ from FCFS in managing disk I/O
requests?
4. Discuss the advantages and limitations of the SCAN algorithm compared to FCFS. How does
SCAN improve disk scheduling performance?
5. How do FCFS, SCAN, and C-SCAN compare in terms of seek time, fairness, and overall
performance?
Result:
Thus, the program for implementing disk scheduling algorithms FCFS-SCAN-C-SCAN was written
and executed successfully.
48
Exp No:14 FILE ALLOCATION STRATEGIES SEQUENTIAL and INDEXED
Aim:
Pre-Lab Discussion
The most common form of file structure is the sequential file in this type of file, a fixed format is used
for records. All records (of the system) have the same length, consisting of the same number of fixed
length fields in a particular order because the length and position of each field are known, only the values
of fields need to be stored, the field name and length for each field are attributes of the file structure.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations to each in sequential order a). Randomly select
a location from available location s1= random(100);
Check whether the required locations are free from the selectedlocation.
if(b[s1].flag==0){ for
(j=s1;j<s1+p[i];j++)
{
if((b[j].flag)==0)count++;
}
if(count==p[i]) break;
}
a) Allocate and set flag=1 to the allocated locations. for(s=s1;s<(s1+p[i]);s++)
{
k[i][j]=s; j=j+1;
b[s].bno=s;b[s].flag=1;
}
Step 5: Print the results file no, length, Blocks allocated.
Step6: Stop the program
49
B) INDEXED:
AIM:
DESCRIPTION:
In the chained method file allocation table contains a field which points to starting block of memory. From
it for each bloc a pointer is kept to next successive block. Hence, there is no external fragmentation.
ALGORITHM:
#include <stdio.h>
//Write the program here
Post-Lab Questions
1. Describe the sequential file allocation strategy. How does it manage file storage and access?
2. How does sequential allocation handle file growth? What are some strategies to manage files that
grow beyond their allocated space?
3. Compare sequential and indexed file allocation strategies in terms of performance and suitability for
different types of file access patterns. Provide examples of scenarios where each strategy might be
preferred.
4. In a file system where both sequential and indexed allocation strategies are used, how might a system
decide which strategy to apply for a given file?
5. How does indexed allocation handle file deletion and fragmentation? What are some strategies for
maintaining index efficiency?
Result:
Thus, the program for implementing file allocation strategies sequential and indexed was written and
executed successfully.
50