0% found this document useful (0 votes)
5 views

Operating System Master Copy

The document is a lab manual for the Operating Systems course (AL3452) offered by the Department of Artificial Intelligence and Data Science. It outlines course objectives, outcomes, and a correlation matrix between course outcomes and program outcomes, along with detailed lab exercises and procedures for installing operating systems and implementing various programming tasks. The manual is prepared by S.Abirami Kayathiri and approved by Mr.L.S.Vignesh, HOD of AI&DS.

Uploaded by

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

Operating System Master Copy

The document is a lab manual for the Operating Systems course (AL3452) offered by the Department of Artificial Intelligence and Data Science. It outlines course objectives, outcomes, and a correlation matrix between course outcomes and program outcomes, along with detailed lab exercises and procedures for installing operating systems and implementing various programming tasks. The manual is prepared by S.Abirami Kayathiri and approved by Mr.L.S.Vignesh, HOD of AI&DS.

Uploaded by

saisuganya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 151

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND

DATA SCIENCE

LAB MANUAL

MASTER COPY​
DEPARTMENT OF ARTIFICIAL INTELLIGENCE

AND DATASCIENCE

LAB MANUAL MASTER COPY


Subject Code : AL3452

Subject Name : Operating system

Year : III

Department : Artificial Intelligence and Data Science

Semester : VI

Regulation : 2021

Prepared by : S.Abirami Kayathiri Assistant Professor/AI&DS

Verified and Approved by : Mr.L.S.Vignesh HOD/AI&DS








DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


PROGRAM OUTCOMES (POs)

PO Graduate Attribute Program outcome

1. Engineering knowledge Apply the knowledge of mathematics, science, engineering fundamentals,


and an engi- neering specialization to the solution of complex engineering problems.

2. Problem analysis Identify, formulate, review research literature, and analyze complex
engineering prob- lems reaching substantiated conclusions using first principles of
Mathematics, natural sciences, and engineering sciences
3. Design/developmen t Design solutions for complex engineering problems and design system
ofsolutions components orprocesses that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal,
and environmental considerations

4. Conduct investigations of Use research-based knowledge and research methods including design of
complex problems experiments, analysis and interpretation of data, and synthesis of the information to
provide valid
conclusions

5. Modern tool usage Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
6. The engineer and society Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professionalengineering practice.
7. Environment and Understand the impact of the professional engineering solutions in societal
sustain- ability: and environ- mental contexts, and demonstrate the knowledge of, and need for
sustainable develop- ment.
8. Ethics Apply ethical principles and commit to professional ethics and responsibilities
andnorms of the engineering practice.

9. Individual and team work Function effectively as an individual, and as a member or leader in diverse teams,
and inmultidisciplinary settings.

10. Communication Communicate effectively on complex engineering activities with the engineering
com- munity and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give
and receive
clear instructions.

11. Project management Demonstrate knowledge and understanding of the engineering and management
andfinance princi- ples and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary
environments.

12. Life-long Learning Recognize the need for, and have the preparation and ability to engage in
independentand life-long learning in the broadest context of technological change.


DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


AL3452 - Operating Systems Laboratory

Course Objectives
OB1: To understand the basics and functions of operating systems.
OB2: To understand Processes and Threads.
OB3: To analyze Scheduling algorithms and process synchronization.
OB4: To understand the concept of Deadlocks.
OB5: To analyze various memory management schemes.
OB6: To be familiar with I/O management and File systems.
OB7: To be familiar with the basics of virtual machines and Mobile OS like iOS and Android.

Course outcome
At the end of the course, the student should be able to:

CO Outcomes Bloom’s Tax- onomy


s
CO1 Analyze various scheduling algorithms and process synchronization. L6

CO2 Explain deadlock, prevention and avoidance algorithms. L6


CO3 Compare and contrast various memory management schemes. L4

CO4 Explain the functionality of file systems I/O systems, and Virtualization L4

CO5 Compare iOS and Android Operating Systems. L6

CO-PO, PSO Correlation Matrix: (3- > Strong, 2- > Moderate, 1 – >| Low)

CO- P P P P P P P P P PO PO PO PS PS PS
P O O O O O O O O O 10 11 12 O1 O2 O3
O, 1 2 3 4 5 6 7 8 9
P
S
O
3 1 1 1 - - - - 1 1 1 2 2 1 2
CO1
2 3 1 3 1 - - - 3 2 2 3 3 3 1
CO2

2 2 3 3 2 - - - 3 3 1 2 1 1 1
CO3

2 2 1 1 3 - - - 1 1 2 1 1 1 2
CO4
2 3 3 1 3 - - - 3 2 2 1 3 1 2
CO5


CO–POMAPPINGWITHEXPERIMENTS
Course Program
S. Topic
Outcome Outcome
No.

Operating Systems Laboratory

1. Installation of Operating system : Windows/ Linux


CO1 1,2,3,4,5,9

Illustrate UNIX commands and Shell Programming


2.
CO2 1,2,3,4,5,9

Process Management using System Calls : Fork, Exec, Getpid, Exit, Wait,
3.
Close CO2 1,2,3,4,5,9

Write C programs to implement the various CPU Scheduling Algorithms


4. CO2 1,2,3,4,5,9
Illustrate the inter process communication strategy
5.
CO2 1,2,3,4,5,9

Implement mutual exclusion by Semaphores


6.
CO3 1,2,3,4,5,9

Write a C program to avoid Deadlock using Banker's Algorithm CO5 1,2,3,4,5,9,


7.
10
Write a C program to Implement Deadlock Detection Algorithm
8.
CO2 1,2,3,4,5,9
Write C program to implement Threading
9.
CO3 1,2,3,4,5,9
Implement the paging Technique using C program ​
10.
1. Write C programs to implement the following Memory Allocation ​
Methods a. First Fit b. Worst Fit c. Best Fit
2. Write C programs to implement the various Page Replacement
Algorithms CO5 1,2,3,4,5,9,
3. Write C programs to Implement the various File Organization 10
Techniques
4. Implement the following File Allocation Strategies using C programs a.
Sequential b. Indexed c. Linked 5. Write C programs for the
implementation of various disk scheduling algorithms
CONTENTS Page No

Ex.N Nameof theLabExercises


o.
Installation of windows operating system & Install any guest operating
1 4
system like Linux using VMware
2 Illustrate UNIX commands and Shell Programming 8

3 Process Management using System Calls : Fork, Exit, Getpid, Wait, Close 13
Write C programs to implement the various CPU Scheduling Algorithms
4 18

5 Illustrate the inter process communication strategy 29

6 Implement mutual exclusion by Semaphore 36

7 Write C programs to avoid Deadlock using Banker's Algorithm 40

8 Write a C program to Implement Deadlock Detection Algorithm 44

9 Write C program to implement Threading 48

10 Implement the paging Technique using C program 51


Write C programs to implement the following Memory Allocation
11 55
Methods
a.​First Fit
b.​Worst Fit
C. Best Fit
12 Implement the various Page Replacement Algorithms 62

13 File Organization Techniques 68


Implement the following File Allocation Strategies using C programs
14 78
a. Sequential b. Indexed c. Linked
Write C programs for the implementation of various disk scheduling
15 83
algorithms
L T P C
AL3452 OPERATING SYSTEMS (Lab)
3 0 2 4

Syllabus
1.​ Installation of Operating system : Windows/ Linux
2.​ Illustrate UNIX commands and Shell Programming
3.​ Process Management using System Calls : Fork, Exec, Getpid, Exit, Wait, Close
4.​ Write C programs to implement the various CPU Scheduling Algorithms
5.​ Illustrate the inter process communication strategy
6.​ Implement mutual exclusion by Semaphores
7.​ Write a C program to avoid Deadlock using Banker's Algorithm
8.​ Write a C program to Implement Deadlock Detection Algorithm
9.​ Write C program to implement Threading
10.​Implement the paging Technique using C program
11.​Write C programs to implement the following Memory Allocation Methods
a.​ First Fit
b.​ Worst Fit
c.​ Best Fit
12.​Write C programs to implement the various Page Replacement Algorithms
13.​Write C programs to Implement the various File Organization Techniques
14.​Implement the following File Allocation Strategies using C programs
a.​ Sequential
b.​ Indexed
c.​ Linked
15.​Write C programs for the implementation of various disk scheduling algorithms
COURSE OBJECTIVES:

●​ To understand the basics and functions of operating systems.


●​ To understand Processes and Threads
●​ To analyze Scheduling algorithms and process synchronization.
●​ To understand the concept of Deadlocks.
●​ To analyze various memory management schemes.
●​ To be familiar with I/O management and File systems.
●​ To be familiar with the basics of virtual machines and Mobile OS like iOS and Android

OUTCOMES:

Upon successful completion of this course, the students will be able to:
CO1: Apply the concepts of operating systems in various computing systems.
CO2 : Analyze various scheduling algorithms and process synchronization, deadlock,
prevention and avoidance algorithms.
CO3 : Apply various memory management schemes for memory allocation.
CO4 : Elucidate the functionality of file systems I/O systems, and Virtualization
CO5 : Compare iOS and Android Operating Systems
CO6 : Apply the various scheduling concepts for a real time problem.
CO-PO MAPPING

SNo Nameof theLabExercises COs


Installation of windows operating system & Install any guest operating
1 CO1
system like Linux using VMware
2 Illustrate UNIX commands and Shell Programming CO1
Process Management using System Calls : Fork, Exit, Getpid, Wait,
3 CO1
Close
Write C programs to implement the various CPU Scheduling CO2,
4
Algorithms
CO6
5 Illustrate the inter process communication strategy CO2
6 Implement mutual exclusion by Semaphore CO2
7 Write C programs to avoid Deadlock using Banker's Algorithm CO2
8 Write a C program to Implement Deadlock Detection Algorithm CO2
9 Write C program to implement Threading CO2
10 Implement the paging Technique using C program CO3
Write C programs to implement the following Memory Allocation
11 Methods CO3
a. First Fit b. Worst Fit c. Best Fit
Write C programs to implement the various Page Replacement
12 CO3
Algorithms
Write C programs to Implement the various File Organization
13 CO4
Techniques
Implement the following File Allocation Strategies using C programs
14 CO4
a. Sequential b. Indexed c. Linked
Write C programs for the implementation of various disk scheduling
15 CO4
algorithms
Ex.No:1
Installation of windows operating system & Install any
Date: guest operating system like Linux using VMware

Aim:
To install windows operating system any guest operating system like Linux using VMware.

a)​ Prcedure for installing windows operating system:

1.​ Step 1: Creating an Installation Disc or Drive


a.​ Connect a blank USB flash drive or insert a blank writable DVD. You can install
Windows 10 by creating a bootable USB flash drive or DVD that contains the Windows
10 installation files. You'll need a USB flash drive that's at least 8GB, or any blank DVD
to get started
2.​ Step 2: Download media creation tool from the official website: https://www.microsoft.com/en-
us/software-download/windows10%20.
3.​ Step 3: Double-click the downloaded file. Its name begins with "MediaCreationTool" and
ends with ".exe.". Click Yes when prompted to allow the installer to run.
4.​ Step 4: Select "Create installation media" and click OK. This option lets you create a Windows
installation disc or drive that will work on any compatible PC, not just the one you're using
now.
5.​ Step 5: Select your preferences and click Next. If you're installing Windows on the current PC,
you can keep the default options. If you need to install on a different PC, make sure you
choose the language and edition for which you have a license, and select the architecture
(64-bit or 32- bit) that matches the PC you're going to install on. If you're not sure about the
architecture, you can choose Both from the menu.
6.​ Step 6: Choose an installation type and click Next. An ISO file is a type of file that can be
burned to a DVD, so choose that option if you plan to create a DVD. Otherwise, choose the USB
flash drive option.
7.​ Step 7: Create your installation media. The steps are a little different depending on what
you're doing:
a.​ Flash drive: Select your flash drive from the list, click Next, and wait for the
installation files to install. When the process is complete, click Finish.
b.​ DVD/ISO: Click Save to save the ISO file to your computer—it may take a while
because the file is large and has to be downloaded. Once downloaded, you'll see a
progress screen that monitors the download. When the download is complete, click Open
DVD burner on the "Burn the ISO file to a DVD" screen, select your DVD burner, and
then click Burn to create your DVD.
8.​ Step 8: Connect your Windows 10 installation media. If you created a flash drive, connect it
to the PC on which you want to install Windows 10. If you made a DVD, insert it into the
drive now.
9.​ Step 9: Boot the PC into the BIOS. If your PC is not already set up to boot from your flash
or optical drive, rebooting from your installation media won't work. You'll need to make a
quick change in your BIOS to change the boot order. There are a few ways to get in:
a.​ Windows 8.1 or 10: From Windows, open Settings, select Update & Recovery or Update
& Security, and go to Recovery > Restart now > Troubleshoot > Advanced Options >
UEFI Firmware Settings > Restart.
b.​ Any PC: Reboot the PC and immediately start pressing (over and over again) the
keyboard key required by your PC to enter "Setup," or the BIOS. The key varies by
computer, but here are some of the most common keys:
i.​ Acer and Asus: F2 or Del
ii.​ Dell: F2 or F12
iii.​ HP: ESC or F10
iv.​ Lenovo: F1, F2, or Fn + F2
v.​ Lenovo ThinkPads: Enter + F1.
vi.​ MSI: DEL
vii.​ Microsoft Surface Tablets: Press and hold the volume-up button.
viii.​ Samsung and Toshiba: F2
ix.​ Sony: F1, F2, or F3
10.​Step 10: Go to the Boot tab. You'll use the arrow keys to select it. The Boot tab may instead say
Boot Options or Boot Order, depending on your computer's manufacturer.
11.​Step 11: Select a device from which to boot. You have a couple of options here:
a.​ For a USB flash drive, select the Removable Devices option.
b.​ For a disc installation, select the CD-ROM Drive or Optical Drive option.
12.​Step 12: Press the + key until your boot option is first. Once either Removable Devices or
CD- ROM Drive is at the top of the list, your computer will select your choice as its default
boot option.
a.​ On some computers, you'll instead press one of the function keys (e.g., F5 or the
arrow keys to navigate an option up to the top of the menu. The key will be listed on
the right side of the screen.
13.​Step 13: Save your settings. You should see a key prompt (e.g., F10 at the bottom of the screen
that correlates to "Save and Exit". Pressing it will save your settings and restart your computer.
14.​Step 14: Wait for your computer to restart. Once your computer finishes restarting, you'll see a
window here with your geographical data. You're now ready to begin setting up your Windows
10 installation.
15.​Step 15: Click Next when prompted. You can also change the options on this page (e.g., the setup
language) before continuing if need be.
16.​Step 16: Click Install Now. It's in the middle of the window.
17.​Step 17: Enter your Windows 10 key, then click Next. If you don't have a Windows 10 key,
instead click Skip in the bottom-right corner of the screen.
a.​ If you've already installed Windows 10 on this PC and were signed in with your
Microsoft account, your key should be linked to your account. When prompted, just sign
in with your Microsoft account and Windows will locate your key.[4]
b.​ If you've changed hardware in the PC, such as replacing the motherboard, you can
activateWindows after installing by going to Settings > Update & Security > Activation
> Troubleshoot > I changed hardware on this device recently. Sign in with your
Microsoft account when prompted, choose This is the device I'm using right now, and
then click Activate.
18.​Step 18: Follow the on-screen instructions to install Windows 10. You'll be asked to perform a
few tasks, such as connecting to Wi-Fi and choosing some preferences. Once the installation is
complete, you'll have a fresh new installation of Windows 10.
a.​ If you're upgrading from an earlier version of Windows, you'll be asked if you want to
upgrade the current operating system or do a custom install. If you choose Upgrade,
you'll preserve existing apps and files.
19.​Step 19: End the process

Output:
a)​Process of installing linux in VMware:
1.​ Click Create a New Virtual Machine
2.​ Select the default option, Installer disc image file (iso)
3.​ Click Browse to find the ISO file
4.​ With "guest" OS selected, click Next
5.​ Select Linux as the Guest operating system type
6.​ Under Version, scroll through the list and select the OS
7.​ Click Next to proceed and if necessary, input a Virtual machine name
8.​ Confirm the storage Location and change if needed
9.​ With the operating system selected and configured, it's time to build the virtual machine.
a.​ Under Specify Disk Capacity adjust Maximum disk size if required (the default should
be enough)
b.​ Select Split virtual disk into multiple files as this makes moving the VM to a new PC easy
c.​ Click Next then confirm the details on the next screen
d.​ If anything seems wrong click Back, otherwise click Finish
10.​End the process

Output:
Result:
ThustheWindows operating system has been installed standalone and linux operating system
has been installed in VMware successfully.

VivaQuestions
1.​ Define Operating System.
2.​ Where OS resides in sysem?
3.​ What do you meant by BIOS?
4.​ Difference between CLI and GUI.
5.​ List the purpose of Operating System.
6.​ State the purpose of VMware.
7.​ What is virtualization?
8.​ Differentiate type1 and tyep2 virtualization.
9.​ What do you meant by VMM?
7
Ex.No:2
Illustrate UNIX commands and Shell Programming
Date:

Aim:
To illustrate UNIX commands and Shell Programming.

Program:
who
The ‘$ who’ command displays all the users who have logged into the system currently. The thing tty2 is
terminal line the user is using and the next line gives the current date and time

$ who
Output:gomathynayagam tty2 2024-03-25 09:32 (:0)

pwd
The ‘$pwd’ command stands for ‘print working directory’ and as the name says,it displays the directory in
which we are currently (directory is same as folder for Windows OS users).

$ pwd
Output: /home/Documents

cal
The ‘$ cal’ means calendar and it simply display calendar on to your screen.

$ cal
Output : March 2024
Su Mo Tu We Th Fr Sa
1 2
3 4 5​ 6​ 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 16 27 28 29 30
31

grep
grep is an acronym for ‘globally search a regular expression and print it’.The ‘$ grep’ command searches
the specified input fully(globally) for a match with the supplied pattern and displays it.

$ grep picture newsfile

Man
The ‘$ man’ command stands for ‘manual’ and it can display the in-built manual for most of the
commands that we ever need. In the above example, we can read about the ‘$ pwd’ command.

$ man pwd

passwd
The ‘$ passwd’ command simply changes the password of the user.
$ passwd

clear
The ‘$ clear’ command is used to clean up the terminal
$ clear

8
ls
The ‘ls’ command simply displays the contents of a directory.

$ ls
Output: Desktop Documents Downloads Music Pictures Public Scratch Templates Videos

mkdir
The ‘$ mkdir’ stands for ‘make directory’ and it creates a new directory.

$ mkdirnewfolder

rmdir
The ‘$ rmdir’ command deletes any directory we want to delete.

$ rmdirnewfolder

cd
The ‘$ cd’ command stands for ‘change directory’ and it changes your current directory to some other
directory.

$ cd newfolder

cp
This ‘$ cp ‘ command stands for ‘copy’ and it simply copy/paste the file wherever you want.

$ cp /home/harssh/file.txt /home/harssh/new/

mv
The ‘$ mv’ command stands for ‘move’ and it simply move a file from a directory to another directory.

$ mv /home/harssh/file.txt /home/harssh/new

cat
Make a text file on Linux
$ cat > filename.txt

Write content into file


$ echo 'This is a test' > data.txt

Append line into file


$ echo 'yet another line' >> data.txt

chmod
The ‘$ chmod’ command stands for change mode command.As there are many modes in Unix that can be
used to manipulate files in the Unix environment.Basically there are 3 modes that we can use with the
‘chmod’ command
∙​ +w (stands for write and it changes file permissions to write)

∙​ +r (stands for read and it changes file permissions to read)

∙​ +x (generally it is used to make a file executable)

$ chmod +w file.txt
$ chmod +r file.txt
$ chmod +x file.txt

9
rm
The rm command removes the entries for a specified file, group of files, or certain select files from a list
within a directory

$ rm file.txt

fold

fold command wraps each line in an input file to fit a specified width and prints it to the standard
output. rit@rit-OptiPlex-3010:~$ vi
c.txtrit@rit-OptiPlex-3010:~$
cat c.txtGoodMorningto all
helloeveryone
rit@rit-OptiPlex-3010:~$
fold c.txtGoodMorningto all
helloeveryone
rit@rit-OptiPlex-3010:~$ fold -w 10
c.txtGoodMorni
ng to
allhello
everyon
e

Implementation of shell programming


1.​Factorial of a
number: Algorithm:
Step1.Get anumber
Step 2. Use for loop or while loop to compute the factorial by using the below
formula Step3. fact(n)=n * n-1* n-2 * .. 1
Step4. Displaythe result.
Program
echo "Enter a number"
read num
fact=1
while [ $num -gt 1 ]do
fact=$((fact * num)) #fact = fact *
num num=$((num-1)) #num =
num-1done echo $fact

Output
Enter a number 3
6

2.​Greatest of three
numbers Algorithm:
Step 1.Get three numbers. Say num1, num2, num3
Step2.If (num1 >num2)and(num1 > num3)
displaynum1
Step 3. elif(num2 > num1) and (num2 > num3)
displaynum2
Step4.Otherwise,
displaynum3
Program:
echo "EnterNum1"
10
read num1
echo "Enter Num2"
read num2
echo "Enter Num3"
read num3
echo "The greatest of three numbers:"
if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ] then
echo $num1
elif [ $num2 -gt $num1 ] && [ $num2 -gt $num3 ] then
echo $num2
else
echo $num3
fi

Output:
Enter Num1 3

Enter Num2 7

Enter Num3 5

Thegreatest of threenumbers:7

3.​Find if the number is odd or


even: Algorithm:
Step1.Get a number
Step 2. If the number is divisible by 2,Display even number
Step3. Otherwise,display odd number
Program:
echo "Enter a Number:"
read n
rem=$(($n%2))
if [ $rem -eq 0 ] then
echo "Number is
even"
else
echo"Number is odd"
fi

Output:
EnteraNumber: 5
Numberis odd

4.​Find the sum of Nnatural


numbers: Algorithm:
Step 1. Get N (Total Numbers of numbers).
Step2. Get N numbers usingloop.
Step 3. Calculate the sum.
Step4. Print the result.
Program:
echo "Enter Size(N)"
read N
i=1
sum=0
echo "Enter Numbers"
while[ $i-le $N]
do
read num​ #get number
sum=$((sum + num)) #sum+=num
i=$((i+1))
done
echo $sum

Output:
Enter Size(N) 5
Enter Numbers 1
2
3
4
5
15

5.​Arithmetic
Operations:
Algorithm:
Step1.Get two numbers.
Step2. Find the sum of two numbers and display the result.
Step 3. Find the difference between two numbers and display the result.
Step4. Find the product two numbers and displaythe result.
Step5: Divide the numbers and display the result.
Step6: Find the remainder using modulo operator and display the result.

Program:
echo "enter two numbers"
read a
read b
result=`expr $a + $b`
echo $result
result=`expr $a - $b`
echo $result
result=`expr $a \* $b`
echo $result
result=`expr $a / $b`
echo $result
result=`expr $a % $b`
echo $result

Output
enter two numbers 9 5
14S
4
45
1
4

Result Thus the program to execute basic UNIX


commands and shell programming has been
completed successfully.

VivaQuestions
1.​ DefineProcess.
2.​ Whatarethestates of aprocess?
3.​ Listthepurposeof OperatingSystem.
4.​ Statethe purposeofls command.
5.​ NamefewUnixCommands.

12
Ex.No:3
Process Management using System Calls : Fork, Exit,
Date: Getpid, Wait, Close

Aim:

To write C programs to demonstrate various system calls: Fork, Exit, Getpid, Wait, Close

Algorithm:

SYSTEM CALLS USED:


1.​fork()
Used to create new processes. The new process consists of a copy of the address space of the
original process. The value of process id for the child process is zero, whereas the value of process id
for theparentis an integer valuegreater than zero.
2.​getpid( )
Each process is identified by its id value.This function is used to get the id value of a
particular process.
3.​exit( )
The function exit() terminates the calling process "immediately".
4.​wait()
The wait() system call suspends execution of the current process
5.​close()
close() closes a file descriptor, so that it no longer refers to any file and may be reused

Programusing fork, wait, exit system calls

1.​Step1: Create a child process using fork() system call.


2.​Step 2: The parent process waits, until the child process completes the execution or terminates
using wait() system call.
3.​Step 3: If child process created successfully, terminate the child process, using exit() system
call.
4.​Step4: Print theparentprocess id and the child process id using getpid().

ProgramCode for fork() and getpid() system call:


#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
int main(int argc, char **argv)
{
pid_t pid;
pid = fork();
if(pid==0)
{
printf("It is the child process and pid is
%d\n",getpid()); exit(0);
}
else if(pid> 0)
{
printf("It is the parent process and pid is %d\n",getpid());
}
else
{
printf("Error while forking\n");
13
exit(EXIT_FAILURE);
}
return 0;
}

Output:
rit@rit-OptiPlex-3010:~/Documents$ sudo vim
fork.c rit@rit-OptiPlex-3010:~/Documents$make
fork rit@rit-OptiPlex-3010:~/Documents$/.fork

It is the parent process and pid is 18097


It is the parent process and pid is 18098

Program using wait system call


#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>

int main()
{
Int cpid;
if(fork() ==0)
exit(0);​ /* terminate child
*/ else
cpid=wait(NULL); /*reapingparent*/

printf("Parent pid = %d\n", getpid());


printf("Childpid= %d\n",cpid);

return0;
}
/*
Output:
rit@rit-OptiPlex-3010:~/Documents
$ gccwaittest.crit@rit-OptiPlex-
3010:~/Documents$./a.out
Parent pid =
5508Childpid=5509
*/

Programs using exec system calls


#include<unistd.h>

14
intmain()
{
char *binaryPath =
"/bin/ls"; char*arg1 ="-lh";
char*arg2= "/home";
execl(binaryPath,binaryPath,arg1,arg2,NULL);

return0;
}

Output:
rit@rit-OptiPlex-3010:~/Documents$
gccexecltest.crit@rit-OptiPlex-3010:~/Documents
$
./a.out
total28K
drwxr-xr-x2endsemendsem4.0KApr252019endse
m drwxr-xr-x2login login4.0K Apr25 2019login
drwx------2rootroot​ ​​
16KJul92018lost+found drwxr-xr-x22 rit​ rit​
4.0K Jan3 11:56rit

#include <unistd.h>

int main()

{
char *programName = "ls";
char *arg1 = "-l";//-lh
char *arg2= "/home";

execlp(programName,programName,arg1, arg2,NULL);

return0;
}

Output

rit@rit-OptiPlex-3010:~/Documents$
gccexeclptest.crit@rit-OptiPlex-3010:~/Documents
$
./a.out
total28
drwxr-xr-x2endsemendsem4096Apr252019endse
m drwxr-xr-x2loginlogin4096 Apr252019login
drwx------2rootroot16384Jul 92018lost+found
drwxr-xr-x22 rit​ rit​ 4096 Jan3 11:56 rit

Program using open dir,read dir,close dir system calls

#include <stdio.h>
#include<dirent.h
> int main(void)
{
structdirent *de;// Pointer fordirectoryentry
// opendir() returns a pointer of DIR type.DIR*dr =opendir(".");

if(dr==NULL)// opendir returns NULLif couldn't open directory

{
printf("Could not open current directory" );
return0;
}

//Referhttp://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
//forreaddir()
while ((de = readdir(dr)) !=
NULL)
printf("%s\n",de->d_name);

closedir(dr);
return0;
}

Output:
rit@rit-OptiPlex-3010:~/Documents
$ gccdirectorytest.crit@rit-OptiPlex-
3010:~/Documents$./a.out
a.outdirectory
test.c
.
..
forktest.ce
x
ittest.cexec
l
ptest.cexec
l test.c

Program using stat system call

#include <stdio.h>
#include
<sys/stat.h>
#include<stdlib.h>
int main()
{
char *fd = "forktest.c";
structstat *buf;

buf = malloc(sizeof(struct stat));

stat(fd,buf);

//Accessing data members of stat


structprintf("\nFilest_uid%d\n",buf->st_uid);printf("\nFilest_blksize %ld
\n",buf->st_blksize); printf("\nFilest_gid%d\n",buf->st_gid);
printf("\nFilest_blocks %ld
\n",buf->st_blocks);
printf("\nFilest_size%ld\n",buf->st_size);
printf("\nFilest_nlink %u \n",(unsigned int)buf->st_nlink);printf("\nFilePermissions
User\n"); printf((buf->st_mode&S_IRUSR)?"r":"-");
printf((buf->st_mode&S_IWUSR)?"w":"-");
printf((buf->st_mode& S_IXUSR)? "x":"-");printf("\n");
printf("\nFilePermissionsGroup\n");
printf((buf->st_mode&S_IRGRP)?"r":"-");
printf((buf->st_mode&S_IWGRP)?"w":"-");
printf((buf->st_mode& S_IXGRP)? "x":"-");
printf("\n");
printf("\nFile Permissions
Other\n");printf((buf->st_mode&S_IROTH)?"r":"-");
printf((buf->st_mode&S_IWOTH)?"w":"-");
printf((buf->st_mode& S_IXOTH)? "x":"-");
printf("\n");
free(buf);
return0;
}

Output
Program using open and close system call

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<errno.h>
extern int errno;
int main()
{
//if filedoes nothavein directory
//thenfilefoo.txtiscreated.
int fd = open("foo.txt", O_RDONLY | O_CREAT);printf("fd=%d\n", fd);

if(fd==-1)
{
// print which type of error have in a code
printf("Error Number%d\n", errno);

int i =
close(fd);
return0;
}

Result:

The C programs implementing system calls have been implemented successfully.

VivaQuestions:

1.​ Definefork.
2.​ Whataresystemcalls?
3.​ Namesomefilemanagementsystemcalls.
4.​ Statevarious typesof system calls.
5.​ Howdoesa userprogramcommunicate withOS?
Ex.No:4
Write C programs to implement the various CPU Scheduling
Date: Algorithms

Aim:
To write C programs to implement various CPU Scheduling algorithms.

Algorithm:
FCFS
1.​Initialize arrays to store the process‘s parameters like process id, arrival time, burst time,
completion time, turnaround time and waiting time
2.​Get the number of processes from the user, n.
3.​For each process i, get the process id, pidi, arrival time, ati and burst time, bti.
4.​ Calculate completion time, cti, turnaround time, tati and waiting time, wti for all the
processes, i. Completion Time:
ct0 = at0 + bt0 ;
when i>=1,
cti = cti-1 + bti ;
Turnaround Time:
tati = cti - ati ;
totaltat+= tati ;
Waiting Time:
wti = tati - bti ;
totalwt+= wti ;
5.​ Display the average turnaround time, avgtat and average waiting time,avgwt of the
processes using FCFS scheduling algorithm.
Average Turnaround Time:
avgtat = totaltat / n ;
Average Waiting Time:
avgwt = totalwt / n ;

SJF (Non-pre-emptive)
1.​Initialize arrays to store the process‘s parameters like process id, arrival time, burst time,
completion time, turnaround time and waiting time
2.​Get the number of processes from the user, n.
3.​For each process i, get the process id, pidi, arrival time, ati and burst time, bti.
4.​ Select and sort the processes based on the minimum arrival time and minimum Burst
time for execution.
5.​ Calculate completion time, cti, turnaround time, tati and waiting time, wti for all the
processes, i. Completion Time:
ct0 = at0 + bt0 ;
when i>=1,
cti = cti-1 + bti ;
Turnaround Time:
tati = cti - ati ;
totaltat+= tati ;
Waiting Time:
wti = tati - bti ;
totalwt+= wti ;
6.​ Display the average turnaround time, avgtat and average waiting time, avgwt of the
processes using SJF non-pre-emptive scheduling algorithm.
Average Turnaround Time:
avgtat = totaltat / n ;
Average Waiting Time:
avgwt = totalwt / n ;
SJF (Pre-emptive)
1.​Initialize arrays to store the process‘s parameters like process id, arrival time, burst time,
completion time, turnaround time and waiting time
2.​Get the number of processes from the user, n.
3.​For each process i, get the process id, pidi, arrival time, ati and burst time, bti.
4.​Until all processes get completely executed,
Initialize current_time = 0 and store the remaining time of processes.
At every single process‘s arrival (time) ati, find process with minimum remaining time among the
processes that arrives till the current_time and reduce its remaining time by 1.
Check if the process‘s remaining time becomes 0.
Increment the counter of process completion, cti.
Completion time of current process, cti = current_time + 1
5.​ Calculate turnaround time, tati and waiting time, wti for all the
processes, i. Turnaround Time:
tati = cti - ati ;
totaltat+= tati ;
Waiting Time:
wti = tati - bti ;
totalwt+= wti ;
6.​ Display the average turnaround time, avgtat and average waiting time, avgwt of the processes
using SJF pre-emptive scheduling algorithm.
Average Turnaround Time:
avgtat = totaltat / n ;
Average Waiting Time:
avgwt = totalwt / n ;

Priority Scheduling (Non-pre-emptive)


1.​Initialize arrays to store the process‘s parameters like process id, arrival time, burst time, priority,
completion time, turnaround time and waiting time
2.​Get the number of processes from the user, n.
3.​For each process i, get the process id, pidi, arrival time, ati, burst time, bti, priority prii.
4.​ Sort the processes, according to process priority, prii if two processes priority are same then
break tie based on the first arrived process.
5.​ Calculate completion time, cti, turnaround time, tati and waiting time, wti for all the
processes, i. Completion Time:
ct0 = at0 + bt0 ;
when i>=1,
cti = cti-1 + bti ;
Turnaround Time:
tati = cti - ati ;
totaltat+= tati ;
Waiting Time:
wti = tati - bti ;
totalwt+= wti ;
6.​ Display the average turnaround time, avgtat and average waiting time, avgwt of the processes
using priority scheduling algorithm.
Average Turnaround Time:
avgtat = totaltat / n ;
Average Waiting Time:
avgwt = totalwt / n ;

Round Robin Algorithm


1.​ Initialize arrays to store the process’s parameters like process id, arrival time, burst
time, completion time, turnaround time and waiting time for each process.
2.​Get the number of processes from the user, n.
3.​Get the time quantum from the user, tq.
3.​For each process i, get the process id, pidi, arrival time, ati and burst time, bti.
4.​ Initialize current time, t = 0 and store the remaining time of processes in rti. Initilize
process’s remaining time rti to the process’s burst time bti.
5.​ Keep traversing the all processes while all processes until all the processes get
completed. Do following for ith process if it is not completed yet.
a.​If rti > quantum
(i)​ t = t + quantum
(ii)​rti -= quantum;
b.​Else // Last cycle for this process
(i)​ t = t + rti;
(ii)​rti = 0; // This process is over
(iii)​cti = t;
(iv)​Turnaround
Time tati = cti -
ati ; totaltat+=
tati ;
(v)​ Waiting
Time: wti = tati - bti ;
totalwt+= wti ;
6.​ Display the average turnaround time, avgtat and average waiting time, avgwt of the
processes. Average Turnaround Time:
avgtat = totaltat / n ;
Average Waiting Time:
avgwt = totalwt / n ;

Program Code:
FCFS
#include<stdio.h>
int main()
{
int bt[10],at[10];
double ct[10],wt[10],tat[10];
int n,sum=0;
float totaltat=0,totalwt=0;
printf("Enter number of processes");
scanf("%d",&n);
printf("Enter arrival time & burst time for each process\n\n");
for(int i=0;i<n;i++)
{
printf("Arrival time of the process %d",i+1);
scanf("%d",&at[i]);
printf("Burst time of process %d",i+1);
scanf("%d",&bt[i]);
printf("\n");
}
for(int j=0;j<n;j++)
{
sum+=bt[j];
ct[j]+=sum;
}
for(int k=0;k<n;k++)
{
tat[k]=ct[k]-at[k];
totaltat=totaltat+tat[k];
}
double avgtat=totaltat/n;
for(int k=0;k<n;k++)
{
wt[k]=tat[k]-bt[k];
totalwt=totalwt+wt[k];
}
double avgwt=totalwt/n;
printf("\t\t SOLUTIONS:\n\n");
printf("P#\tAT\tBT\tCT\t\tTAT\t\tWT\t\n\n");
for(int i=0;i<n;i++)
{
printf("p%d\t%d\t%d\t%f\t%f\t%f\n",i+1,at[i],bt[i],ct[i],tat[i],wt[i]);
}
printf("\nAverage TurnaroundTime=%f\n",avgtat);
printf("Average wt=%f\n",avgwt);
return 0;
}

Enter number of processes 3


Enter arrival time & burst time for each process

Arrival time of the process 1 0


Burst time of process 1 24

Arrival time of the process 2 0


Burst time of process 2 3

Arrival time of the process 3 0


Burst time of process 3 3

SOLUTIONS:

P# AT BT CT TAT WT

p1 0 24 24.000000 24.000000 0.000000


p2 0 3 27.000000 27.000000 24.000000
p3 0 3 30.000000 30.000000 27.000000

Average TurnaroundTime=27.000000
Average wt=17.000000

SJF Preemptive
#include<stdio.h>
int main()
{
int bt[10],at[10],temp[10];
double ct[10],wt[10],tat[10];
int n,sum=0,curntime,complete=0,small;
float totaltat=0,totalwt=0;
printf("Enter number of processes");
scanf("%d",&n);
printf("Enter arrival time & burst time for each process\n\n");
for(int i=0;i<n;i++)
{
printf("Arrival time of the process %d:",i+1);
scanf("%d",&at[i]);
printf("Burst time of process
%d:",i+1); scanf("%d",&bt[i]);
printf("\n");
temp[i]=bt[i];
}

bt[9]=9999;
for(curntime=0;complete!=n;curntime++)
{
small=9;
for(int i=0;i<n;i++)
{
if(at[i]<=curntime && bt[i]<bt[small] && bt[i]>0)
{
small=i;
}
}
bt[small]--;
if(bt[small]==0)
{
complete++;
ct[small]=curntime+1;
tat[small]=ct[small]-at[small];
totaltat+=tat[small];
wt[small]=tat[small]-temp[small]
;
totalwt+=wt[small];
}

}double avgwt=totalwt/n;
double avgtat=totaltat/n;

for(int i=0;i<n;i++)
{
printf("p%d\t%d\t%d\t%f\t%f\t%f\n",i+1,at[i],bt[i],ct[i],tat[i],wt[i]);
}
printf("\nAverage TurnaroundTime=%f\n",avgtat);
printf("Average wt=%f\n",avgwt);
}

Enter number of processes 4


Enter arrival time & burst time for each process

Arrival time of the process 1:0


Burst time of process 1:8

Arrival time of the process 2:1


Burst time of process 2:4

Arrival time of the process 3:2


Burst time of process 3:9

Arrival time of the process 4:3


Burst time of process 4:5

p1 0 0 17.000000 17.000000 9.000000


p2 1 0 5.000000 4.000000 0.000000
p3 2 0 26.000000 24.000000 15.000000
p4 3 0 10.000000 7.000000 2.000000

Average TurnaroundTime=13.000000
Average wt=6.500000

SJF Non-preemptive
#include<stdio.h>
int main()
{
int BT[10]={0},AT[10]={0},TAT[10]={0},WT[10]={0},CT[10]={0};
int i,j,n,sum=0;
float tatsum=0,wtsum=0;
float avgtat=0,avgwt=0;
printf("Enter number of
process:"); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter arrival and burst time of %d",i+1);
scanf("%d%d",&AT[i],&BT[i]);
}
CT[0]=AT[0]+BT[0];
for(i=1;i<n;i++)
{
CT[i]=CT[i-1]+BT[i];
}
for(i=0;i<n;i++)
{
TAT[i]=CT[i]-AT[i];
WT[i]=TAT[i]-BT[i];
tatsum+=TAT[i];
wtsum+=WT[i];
}
printf("\n\nSOLUTION:\n");
printf("p\tAT\tBT\tCT\tTAT\tWT\n");
for(i=0;i<n;i++)
{
printf("%d\t%d\t%d\t%d\t%d\t%d\n",i+1,AT[i],BT[i],CT[i],TAT[i],WT[i]);
}
printf("Average Turnaround Time: %f",tatsum/n);
printf("\n");
printf("Average Waiting Time:
%f",wtsum/n); return 0;
}

Enter number of process:5


Enter arrival and burst time of 1
07
Enter arrival and burst time of 2
05
Enter arrival and burst time of 3
01
Enter arrival and burst time of 4
02
Enter arrival and burst time of 5
08

SOLUTION:
p​ AT​ BT​ CT​ TAT​ WT
1 0 7 7 7 0
2 0 5 12 12 7
3 0 1 13 13 12
4 0 2 15 15 13
5 0 8 23 23 15
Average Turnaround Time:
14.000000 Average Waiting Time:
9.400000

Priority
#include<stdio.h>
void sort(int b[],int a[],int n[],int p[], int m)
{
int i,j,s,tmp;
for(i=0;i<m;i++)
{
for(j=i+1;j<m;j++)
{
if(p[i]>p[j])
{
tmp=p[i];p[i]=p[j];p[j]=tmp;
tmp=b[i];b[i]=b[j];b[j]=tmp;
tmp=a[i];a[i]=a[j];a[j]=tmp;
tmp=n[i];n[i]=n[j];n[j]=tmp;
}
}
}
}
int main()
{
int AT[10]={0},BT[10]={0},PID[10]={0};
int WT[10]={0},TAT[10]={0},PR[10]={0},CT[10]={0};
int i,j,n,sum=0;
float tatsum=0,wtsum=0;
float avgtat=0,avgwt=0;
printf("Enter number of
process:"); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter arrival and burst time and priority of %d",i+1);
scanf("%d%d%d",&AT[i],&BT[i],&PR[i]);
}
sort(BT,AT,PID,PR,n);
CT[0]=AT[0]+BT[0];
for(i=1;i<n;i++)
{
CT[i]=CT[i-1]+BT[i];
}
for(i=0;i<n;i++)
{
TAT[i]=CT[i]-AT[i];
WT[i]=TAT[i]-BT[i];
tatsum+=TAT[i];
wtsum+=WT[i];
}
printf("\n\nSOLUTION:\n");
printf("p\tAT\tBT\tPR\tCT\tTAT\tWT\n");
for(i=0;i<n;i++)
{
printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\n",i+1,AT[i],BT[i],PR[i],CT[i],TAT[i],WT[i]);
}
printf("Average Turnaround Time: %f",tatsum/n);
printf("\n");
printf("Average Waiting Time: %f",wtsum/n);
return 0;
}

Enter number of process:5


Enter arrival and burst time and priority of 1 0 10 3
Enter arrival and burst time and priority of 2 0 1 1
Enter arrival and burst time and priority of 3 0 2 4
Enter arrival and burst time and priority of 4 0 1 4
Enter arrival and burst time and priority of 5 0 5 2

SOLUTION:
p AT BT PR CT TAT WT
1 0 1 1 1 1 0
2 0 5 2 6 6 1
3 0 10 3 16 16 6
4 0 1 4 17 17 16
5 0 2 4 19 19 17
Average Turnaround Time:
11.800000 Average Waiting Time:
8.000000

Round Robin
#include<stdio.h>
int main()
{

int count,j,n,time,remain,flag=0,time_quantum;
int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10];
printf("Enter Total Process:\t ");
scanf("%d",&n);
remain=n;
for(count=0;count<n;count++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d :",count+1);
scanf("%d",&at[count]);
scanf("%d",&bt[count]);
rt[count]=bt[count];
}
printf("Enter Time Quantum:\t");
scanf("%d",&time_quantum);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,count=0;remain!=0;)
{
if(rt[count]<=time_quantum && rt[count]>0)
{
time+=rt[count];
rt[count]=0;
flag=1;
}
else if(rt[count]>0)
{
rt[count]-=time_quantum;
time+=time_quantum;
}
if(rt[count]==0 && flag==1)
{
remain--;
printf("P[%d]\t|\t%d\t|\t%d\n",count+1,time-at[count],time-at[count]-bt[count
]); wait_time+=time-at[count]-bt[count];
turnaround_time+=time-at[count]
; flag=0;
}
if(count==n-1)
count=0;
else if(at[count+1]<=time)
count++;
else
count=0;
}
printf("\nAverage Waiting Time= %f\n",wait_time*1.0/n);
printf("Avg Turnaround Time = %f",turnaround_time*1.0/n);

return 0;
}
Enter Total Process: 3
Enter Arrival Time and Burst Time for Process Process Number 1
:0 5
Enter Arrival Time and Burst Time for Process Process Number 2
:1 7
Enter Arrival Time and Burst Time for Process Process Number 3
:3 4
Enter Time Quantum:​ 2

Process​ |Turnaround Time|Waiting Time

P[3] | 9 | 5
P[1] | 13 | 8
P[2] | 15 | 8

Average Waiting Time= 7.000000


Avg Turnaround Time = 12.333333

Result:

Thus the CPU scheduling algorithms have been implemented and tested successfully.

Viva Questions:
1.​ What do you mean by CPU Scheduling?
2.​ What is preemptive and nonpreemptive scheduling?
3.​ What is turnaround time?
4.​ What is dispatch latency?
5.​ Define race condition.
28
Ex.No:5
Illustrate the inter process communication strategy
Date:

Aim
To implement interprocess communication using pipe and shared memory
i)​ Interprocess Communication using pipe
System calls used:
fork() - To create child
process.fork() returns :
<0 fail to create child (new) process
=0 for child process
>0 i.e process ID of the child process to the parent process. When >0 parent process will execute.
pipe()
pipe() is used for passing information from one process to another. pipe() is unidirectional
therefore, for two-way communication between processes, two pipes can be set up, one for each
direction.

Algorithm pass a string between parent and child process through pipe
Inside Child Process :
1.​ Child process closes the reading end of the pipe (fd[0])
2.​ Child process writes a string and passes the string to parent process via pipe‘s writing end
(fd[1])
3.​ Child process exits.

Inside Parent Process :


1.​ Parent process waits for child process.
2.​ Parent process close the writing end of second pipe(fd[1])
3.​ It reads the string through reading end of pipe (fd[0]).
4.​ The received string is displayed on standard output.

Algorithm to generate numbers in parent process and and determine if it is odd or even in child
process through pipe

Inside Child Process :


1.​ Child process closes the reading end of the pipe (fd[0])
2.​ Child process generates a set of numbers and sends the numbers to parent process via
pipe‘s writing end (fd[1])
3.​ Child process exits.

Inside Parent Process :


1.​ Parent process waits for child process.
2.​ Parent process close the writing end of second pipe(fd[1])
3.​ It reads the numbers through reading end of pipe (fd[0]).
4.​ It determines if the numbers are odd or even number using modulo operator and
displays the result.
29
ii)​ Interprocess Communication using shared memory
System calls used
1.​ shmget :To allocate a shared memory segment.
Prototype
int shmget(key_t key, size_t size, int shmflg);
Where
key​ Specifies either IPC_PRIVATE or a system-wide unique key
size​ Size of new shared memory segment
IPC_CREAT
Create the segment if it doesn't already exist in the kernel.
Shmflg: IPC_EXCL
When used with IPC_CREAT, to ensure failure if
segment already exists
Return Value : Shared memory segment identifier on success -1 On Failure(error)

Header file:
#include<sys/ipc.h>
#include<sys/shm.h>

2.​ shmat()
To attach the shared memory segment identified by shmid to the address space of the
calling process.

Header file
#include <sys/shm.h>

Prototype
void *shmat(int shmid, const void *shmaddr, int shmflg)
shmat() attaches the shared memory segment identified by shmid to the address space of the
calling process. The attaching address is specified by shmaddr with one of the following criteria:
If shmaddr is NULL, the system chooses a suitable (unused) address atwhich to attach the
segment.
If shmaddr is not NULL and SHM_RND is specified in shmflg, the attachment occurs at the
address equal to shmaddr rounded down to the nearest multiple of SHMLBA.

Field Description
Is a unique positive integer created by a shmget system call and
shmid
associated with a segment of shared memory.
shmaddr Points to the desired address of the shared memory segment
Specifies a set of flags that indicate the specific shared memory
shmflg
conditions and options to implement

30
return address at which segment was attached to the process, or
value -1 on error

3.​ shmdt
The shmdt() function detaches from the calling process's data segment the shared memory
segmentlocated at the address specified by shmaddr.
Header File
include <sys/shm.h>
Prototype
int shmdt(const void *shmaddr)
Field Description

shmaddr Is the data segment start address of a shared memory segment

If successful, shmdt() decrements the shm_nattach associated with the


return shared memory segment and returns zero.
value
On failure, it returns -1

4.​ shmctl
Perform shared memory control operations
Header File
#include <sys/shm.h>
Prototype
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
Field Description
Is a unique positive integer created by a shmget system call and
shmid
associated with a segment of shared memory.

cmd Specifies one of IPC_STAT, IPC_SET, or IPC_RMID

Points to the data structure used for sending or receiving data during
buf
execution of shared memory control operations
return
If successful, shmctl() returns zero. On failure, it returns -1
value

Algorithm: 1.​ Create shared memory using shmget() system call.


2.​ Use fork() system call to create child process.
3.​ Both the parent process and child
process uses shmat() to attach to the
shared memory segment.
4.​ Parent process writes a message in the shared
memory and waits.
5.​ Child process reads from the shared memory and
displays the message.
6.​ Child process uses shmdt() function to detach
from the shared memory.
31
Program Code:
#include <stdio.h>
#include <unistd.h>
#include
<sys/types.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
int​ fd[2],
nbytes; pid_t
childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1) {
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);

/* Send
"string"
through the
} output side
else of pipe */
{ write(fd[1],
string,
(strlen(strin
g)+1));
exit(0);

}
/* Parent
process
closes up
output side
of pipe */ readbuffer,
close(fd[1] sizeof(read
); buffer));
printf("Rec
/* Read in a string from the pipe */ eived
nbytes = string: %s",
read(fd[0], readbuffer)
;
return(0);
}
Output:
Received string: Hello!
Program for odd or even:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
int i, fd[2], nbytes;
pid_t childpid;
int a[10],b[10];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
for(i=0;i<10;i++)
{
a[i]=i+1;
}
}
else
{
w
r
i
t
e
(
f
d
[
1
]
,
a
,
1
0
*
s
i
z
e
o
f
(
i
n U
t L
) L
) )
; ;
e c
x l
i o
t s
( e
0 (
) f
; d
w [
a 1
i ]
t )
( ;
N nbytes = read(fd[0], b, 10*sizeof(int));
for(i=0;i<10;i++)
{
if(b[i]%2==0)
{
printf("%d is even number\n",b[i]);
}
else
{
printf("%d is odd number\n",b[i]);
}
}
}

return(0);
}
Output:
1 is odd number
2 is even
number3 is odd
number 4
is even number
5 is odd number
6 is even
number7 is odd
number 8 is even
number9 is odd
number
10 is even number

Inter Process communication using shared memory:


#include<stdio.h>
#include<sys/types.h
> #include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/shm.h>
#include<sys/ipc.h>
int main()
{
int pid, shmid, i;
char *shmptr;
pid=fork();
if(pid == -1)
{
printf("Fork failed");
return 0;
}
else if(pid > 0)
{
shmid = shmget(2041, 32, IPC_CREAT|0666);
shmptr = shmat(shmid,0,0);
printf("Parent is writing\n");

for(i=0;i<10;i++)
{
s
h
} m
p
} t
else r
{ [
i
]
=
'
a
'
+
i
;
p
u
t m
c p
h t
a r
r [
( i
s ]
h )
;
printf("\n\n%s",shmptr);wait(NULL);
shmid = shmget(2041,32,0666);
shmptr = shmat(shmid,0,0); printf("Child is reading\n");
for(i=0;i<10;i++)
{
putchar(shmptr[i]);
}

shmdt(shmptr);shmctl(shmid, IPC_RMID, NULL);


}
return 0;
}

Output
Parent is writing
abcdefghij

Child is reading
abcdefghij

Result:

The programs were implemented and tested successfully.

Viva Questions:

1.​ What is a long term scheduler & short term schedulers?


2.​ What is Dispatcher?
3.​ Which of the following is not a fundamental process state which is not the state of the process?
4.​ What is PCB?
5.​ List some scheduling algorithms.

35
Ex.No:6
Implement mutual exclusion by Semaphore
Date:

Aim:
To write C program to implement Producer Consumer problem using semaphores.

System Calls Used for semaphores:


1.​ semget
To create a new semaphore set, or access an existing set, the semget() system call is used.
Prototype
int semget ( key_t key, int nsems, int semflg );
Field Description
key Specifies either IPC_PRIVATE or a system-wide unique key
nsems Is the number of semaphores in the set associated with the semaphore ID.
Is a flag indicating specific semaphore conditions and options to implement.
IPC_CREAT
semflg Create the semaphore set if it doesn't already exist in the kernel.
IPC_EXCL
When used with IPC_CREAT, fail if semaphore set already exists.
returns the semaphore set identifier associated with
return value the argument key.

2.​ semctl
Used to perform control operations on a semaphore set.
Prototype
int semctl ( int semid, int semnum, int cmd, union semun arg )
Field Description
semid Is the semaphore identifier.
semnum Is a semaphore number greater than zero and less than sem_nsems.

​ The following commands are executed with respect to the


semaphore specified by semid and semnum: GETVAL, SETVAL,
cmd GETPID, GETNCNT, and GETZCNT.
​ The following commands return and set, respectively, every semval
in the set of semaphores: GETALL and SETALL.
​ The following commands are also available: IPC_STAT,
IPC_SET, and IPC_RMID.
Is an optional argument, and depends upon the operation cmd requested.
If used, it is of type union semun, which the application program must
Arg explicitly declare:
union semun {
int val;
36
struct semid_ds *buf;
unsigned short *array;
} arg;

return positive integer on success


value -1 on error

3.​ semop()
Perform array of operations on semaphore set
Header files
#include <sys/sem.h>
Prototype
int semop(int semid, struct sembuf *sops, size_t nsops)

Field Description

semid Is a unique positive integer created by a semget() call.

sops
Points to the array of semaphore-operation structures.

nsops Is the number of semaphore-operation structures in sops.


If successful, semop() returns a value of 0.
return value On failure, semop() returns a value of -1

ALGORITHM:
Step 1: The Semaphore mutex, full & empty are initialized.
Step 2: Use fork system call to create two processes namely Producer process and Consumer process
Step 3: In the case of producer process,
i)​Produce an item into temporary variable.
ii)​If there is empty space in the buffer, check the mutex value to enter into the critical section.
iii)​If the mutex value is 0, allow the producer to add value in the temporary variable to the buffer.
(iv) Signal the mutex value and increase the full value by 1.
Step 4: In the case of consumer process,
i)​It should wait if the buffer is empty
ii)​ If there is any item in the buffer, check for mutex value, if the mutex==0, remove item
from buffer
iii)​Signal the mutex value and reduce the empty value by 1.
iv)​Consume the
item.
Step 5: Print the
result
Program Code:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<sys/sem.h>
void semAcquired(int);
void semReleased(int);
void main() {
char c[10];
int mutex, empty, full, pid, shmid; int in = -1, out = -1;
char *buffer;
mutex = semget(IPC_PRIVATE,1,0666);
if(mutex == -1) {
perror("Failed to create semaphre...\n");
exit(0);
}
if(semctl(mutex, 0, SETVAL, 1) == -1) {
perror("Failed to set mutex value...\n");
exit(0);
}
empty = semget(IPC_PRIVATE, 1, 0666 | IPC_CREAT);
if(empty == -1) {
perror("Error while creating Empty...\n");
exit(0);
}
if(semctl(empty, 0, SETVAL, 50) == -1) {
perror("Failed to set Empty value...\n");
exit(0);
}
full = semget(IPC_PRIVATE, 1, 0666 | IPC_CREAT);
if(full == -1) {
perror("Failed to create full...\n");
exit(0);
}
if(semctl(full, 0, SETVAL, 0) == -1) {
perror("Failed to set full value...\n");
exit(0);
}
shmid = shmget(IPC_PRIVATE, 50*sizeof(char), 0666 | IPC_CREAT);
buffer = shmat(shmid, 0, 0);
pid = fork();
do {
if(pid == -1) {
perror("Error creating consumer...\n");
exit(0);
}
elseif(pid == 0) {
printf("Enter Item produced : ");
scanf("%s", c);
semAcquired(empty);
semAcquired(mutex);
in = (in + 1) % 50;
buffer[in] = c[0];
semReleased(full);
semReleased(mutex);
}
else { s
l
e
e
p
(
3
)
;
} s
}while(1); e
} m
A
c
q
u
i
r
e
d
(
f
u
l
l
)
;
s
e
m
A
c
q
u
i
r
e
d
(
m
u
t
e
x
)
;
o
u
t
=
(
o
u
t
+
1
)
%
5
0
;
c su
[ me
0 d
] no
= w...
b \n",
u c[0]
f );
f sem
e Rel
r eas
[ ed(
o mut
u ex);
t sem
] Rel
; eas
prin ed(
tf(" em
%c pty)
con ;
void semAcquired(int semid) {
struct sembuf sb;
sb.sem_num = 0;
sb.sem_op = -1;
sb.sem_flg = 0;
if(semop(semid, &sb, 1) == -1) {
perror("Failed to acquire semaphores...\n");
exit(0);
}
}
void semReleased(int semid) {
struct sembuf sb;
sb.sem_num = 0;
sb.sem_op = 1;
sb.sem_flg = 0;
if(semop(semid, &sb, 1) == -1) {
perror("Failed to release semaphores...\n");
exit(0);
}
}
OUTPUT:
Enter Item produced : a
a consumed now...
Enter Item produced : r
r consumed now...

Result:
Thus the program to implement semaphores has been executed successfully.

Viva Questions:
1.​ Define busy waiting and spinlock
2.​ Name some synchronization problem.
3.​ Define Semaphore.
4.​ State the advantages of Semaphores.
5.​ What is a monitor?
39
Ex.No:7
Write C programs to avoid Deadlock using Banker's Algorithm
Date:
Aim:
To write a C program to implement Banker‘s Algorithm for Deadlock Avoidance.

Data Structures Needed:


Available: A vector of length m. It shows number of available resources of each type. If
Available[i] = k, then k instances of resource Ri are available.
Max: An n×m matrix that contain maximum demand of each process. If Max[i,j] = k, then process
Pi can request maximum k instances of resource type Rj.
Allocation: An n×m matrix that contain number of resources of each type currently allocated to
each process. If Allocation[i,j] = k, then Pi is currently allocated k instances of resource type Rj.
Need: An n×m matrix that shows the remaining resource need of each process. If Need[i,j] = k,
then process Pi may need k more instances of resource type Rj to complete the task.
Algorithm:
1)​ Let Work and Finish be vectors of length ‘m’ and ‘n’
respectively. Initialize: Work = Available
Finish[i] = false; for i=1, 2, 3, 4….n
2)​Find an i such that both
a)​Finish[i] = false
b)​Needi <= Work
if no such i exists goto step (4)
3)​Work = Work + Allocation[i]
Finish[i] = true
goto step (2)
4)​ if Finish [i] = true for
all i then the system is in a safe
state

Program Code:
#include <stdio.h>
#include
<stdlib.h> int
main() {
int Max[10][10], need[10][10], alloc[10][10], avail[10], completed[10],
safeSequence[10]; int p, r, i, j, flag, count;
count = 0;

printf("Enter the no of processes : ");


scanf("%d", &p);

for(i = 0; i< p; i++)


completed[i] = 0;

printf("\n\nEnter the no. of resources : ");


scanf("%d", &r);

printf("\n\nEnter the Max-value for each process : ");


for(i = 0; i < p; i++) {
40
printf("\nFor process %d : ", i + 1);
for(j = 0; j < r; j++)
scanf("%d", &Max[i][j]);
}

printf("\n\nEnter the allocation for each process : ");


for(i = 0; i < p; i++) {
printf("\nFor process %d : ",i + 1);
for(j = 0; j < r; j++)
scanf("%d", &alloc[i][j]);
}

printf("\n\nEnter the Available Resources : ");


for(i = 0; i < r; i++)
scanf("%d", &avail[i]);

// Calculating need.
for(i = 0; i < p; i++)
for(j = 0; j < r; j++)
need[i][j] = Max[i][j] - alloc[i][j];

do {

flag = -1;
for(i = 0; i < p; i++) {
// If not completed
if(completed[i] == 0) {
flag = i ;
for(j = 0; j < r; j++) {
if(avail[j] < need[i][j]) {
flag = -1;
break;
}
}
}
if(flag != -1)
break;
}

if(flag != -1) {
safeSequence[count] = flag + 1;
count++;
for(j = 0; j < r; j++) {
avail[j] += alloc[flag][j];
alloc[flag][j] = 0;
Max[flag][j] = 0;
completed[flag] = 1;
}
}
}while(count != p && flag != -1);

if(count == p) {
printf("\nThe system is in a safe state...\n");
printf("Safe Sequence : < ");
41
for( i = 0; i < p; i++)
printf("%d ", safeSequence[i]);
printf(">\n");
}
else
printf("\nThe system is in an unsafe state...");
}

42
OUTPUT:

Enter the no of processes : 3


Enter the no. of resources : 3

Enter the Max-value for each process :


For process 1 : 5
5
6
For process 2 : 9
8
7
For process 3 : 6
5
4

Enter the allocation for each process :


For process 1 : 1
2
3
For process 2 : 1
2
3
For process 3 : 1
2
3

Enter the Available Resources : 3


3
3

The system is in an unsafe state...


Result:
Thus, program to implement deadlock avoidance has been executed successfully.

Viva Questions:
1.​ Define request edge and assignment edge.
2.​ What are the methods for handling deadlocks?
3.​ Define deadlock prevention.
4.​ Define deadlock avoidance.
5.​ Define request edge and assignment edge.
6.​ What are conditions under which a deadlock situation may arise?
43
Ex.No:8
Write a C program to Implement Deadlock Detection Algorithm
Date:
Aim:
To write C program to implement Deadloack detection algorithm.

DataStructuresNeeded:
●​ Available
o​ Vector of length m
o​ Indicates number of available resources of each type.
●​ Allocation
o​ Matrix of size n*m
o​ A[i,j] indicates the number of jth resource type allocated to ith process.
●​ Request
o​ Matrix of size n*m
o​ Indicates requet of each process.
o​ Request[i,j] tells number of instance Pi process is request of jth resource type.
Algorithm
Step1
1.​ Let Work(vector) length = m
2.​ Finish(vector) length = n
3.​ InitializeWork = Available.
1.​ For i=0, 1, …., n-1, if Allocationi = 0, then Finish[i] = true; otherwise,
Finish[i]=false.
Step2
1.​ Findanindexisuch thatboth
1.​ Finish[i]==false
2.​ Requesti<=
WorkIf no such i exists go to
step 4.Step 3
1.​ Work=Work+Allocationi
2.​Finish[i]=
trueGo to
Step
2.​Step 4
If Finish[i]== false for some i, 0<=i<n, then the system is in a deadlocked state.
Moreover,ifFinish[i]==false the process Pi is deadlocked.

Program Code
#include<stdio.h>
static int finish[20];
inti,j,np,nr;
int main()
{
int alloc[10][10],request[10][10],avail[10],r[10],w[10];
printf("\nEnter the no of process: ");
scanf("%d",&np);
printf("\nEnter the no of resources: ");
scanf("%d",&nr);
for(i=0;i<nr;i++)
44
{
printf("\nTotal Amount of the Resource R%d: ",i+1);
scanf("%d",&r[i]);
}
printf("\nEnter the request matrix:");for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&request[i][j]);

printf("\nEnter the allocation matrix:");


for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&alloc[i][j]);
/*Available Resource calculation*/
for(j=0;j<nr;j++)
{
avail[j]=r[j];
for(i=0;i<np;i++)
{
avail[j]-=alloc[i][j];
}
}
//marking processes with zero allocation

for(i=0;i<np;i++)

{
int
count=0;for(j=0;
j<nr;j++)
{
if(alloc[i][j]==0)
count++;
else
break;
}
if(count==nr)
finish[i]=1;
}
//initializeW with avail
for(j=0;j<nr;j++)
w[j]=avail[j];

//mark processes with request less than or equal to W


for(i=0;i<np;i++)
{
int canbeprocessed=0;
if(finish[i]!=1)
{
for(j=0;j<nr;j++)
{
45
if(request[i][j]<=w[j])
canbeprocessed=1;
else
{ c
a
n
} b
} e
p
r
o
c
e
s
s
e
d
=
0
;
b
r
e
a
k
;
if(canbeprocessed)
{
finish[i]=1;
for(j=0;j<nr;j++)
w[j]+=alloc[i][j];
}
}
}

//checking for unmarked processes


int deadlock=0;
for(i=0;i<np;i++)
if(finish[i]!=1)
deadlock=1;
if(deadlock)
printf("\n Deadlock detected");
else printf("\nNoDeadlockpossible");

OUTPUT:

Enter the no of process:


4Enterthenoofresources:
5

Total Amount of the Resource R1:


2Total Amount of the Resource R2:
1Total Amount of the Resource R3:
1Total Amount of the Resource R4:
2TotalAmountoftheResourceR5:1

Enter the request


matrix:0 1 0 0 1
00101
00001
10101

46
Entertheallocation matrix:
10110
11000
00010
00000

Deadlock detected
Result:

The program to detect deadlock in a system has been excecuted.

VivaQuestions
1.​ Define deadlock detection.
2.​ State Deadlock recovery
3.​ What are the methods for handling deadlocks?
4.​ Define deadlock avoidance.
5.​ List out the scheduling algorithms
47
Ex.No:9
Write C program to implement Threading
Date:
Aim:
To write programs to implement threading.

Description
1.​ Thread synchronization is defined as a mechanism which ensures that two or more
concurrentprocesses or threads do not simultaneously execute some particular program segment
known ascriticalsection.
2.​ Processes‘access to critical section is controlled by using synchronization techniques.
3.​ When one thread starts executing the critical section (serialized segment of the program)
the other thread should wait until the first thread finishes.
4.​ If proper synchronization techniques are not applied, it may cause a race condition where
the values ofvariables may be unpredictable
5.​ A Mutex is a lock that we set before using a shared resource and release after using it.
6.​ When the lock is set, no other thread can access the locked region of code. So this ensures
asynchronized access of shared resources in the code.

Algorithm
1.​Create two threads
2.​Let the threads share a common resource, say counter
3.​ Even if thread2 si scheduled to start while thread was not done, access to shared
resource is not done as it is locked by mutex
4.​Once thread1 completes,thread2 starts execution
5.​Stop

Program Code:
#include<stdio.h>
#include<pthread.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
int counter = 0;
pthread _ttid[2];
pthread _mutex_tlock;

void *test(void *args)


{
pthread _mutex_lock(&lock);
long i = 0;
counter+=1;
printf("Job %d started \n", counter);
for(i=0; i<10000; i++);
printf("Job %d finished\n", counter);

pthread _mutex_unlock(&lock);

void main()
{
int i = 0;
48
int error;

if(pthread _mutex_init(&lock, NULL) != 0)


{
printf("Mutexinitfailed...\n");exit(1);
}

while(i< 2)
{
error= pthread_create(&tid[i],NULL,&test,NULL);

if(error!=0)
{
printf("Threadcan't becreated:%s\n",strerror(error));
}

i++

pthread _join(&tid[0], ULL);


pthread_join(tid[1],NULL);
pthread_mutex_destroy(&lock);

OUTPUT:

Job1 started
Job 1 finished
Job2 started
Job 2 finished

//MutexLock-SineandCosine

#include<stdio.h>
#include<pthread.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

int counter = 0;
pthread_ttid[2];
pthread_mutex_t lock;

void *test(void *args) {


pthread_mutex_lock(&lock);
long i = 0;
int x;
counter += 1;
printf("Job %d started \n", counter);
printf("Enter a number :
"); scanf("%d", &x);
if(counter == 1) {
printf("Sin of %d is : %lf\n", x, sin(x * (3.141592653589793238 / 180)));
}
else { printf("Cos of %d is : %lf\n", x, cos(x *
(3.141592653589793238 / 180)));
}

printf("Job %d finished\n", counter);


pthread_mutex_unlock(&lock);
}

void main()
{ int i = 0;
int error;
if(pthread_mutex_init(&lock, NULL) != 0) {
printf("Mutex init failed...\n");
exit(1);
}
while(i< 2) {
error = pthread_create(&tid[i], NULL, &test, NULL);
if(error != 0) {
printf("Thread can't be created : %s\n", strerror(error));
}
i++;
}

pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_mutex_destroy(&lock)
;
}
OUTPUT
Job1 started
Enter a number :
90Sinof90is:1.00000
0 Job 1 finished
Job2 started
Enteranumber: 90
Cosof 90 is : 0.000000
Job 2 finished

Result:

The programs have been executed and tested successfully.


VivaQuestions:
1.​ What is a thread?
2.​ What is a deadlock?
3.​ Distinguish between process and thread.
4.​ Statesynchronization problems.
5.​ Define mutex locks.
Ex.No:10 Implement the paging Technique using C program
Date:

Aim:

●​ To write C program to implement paging technique of memory management


●​ Simulate Virtual memory using Virtual memory Simulator–Virtual Lab exercise

Algorithm:
1.​Get the process size from the user.
2.​Get the page size.
3.​Calculate the no.of pages needed.
4.​Enter page table details
5.​Get the page number and offset value and find the corresponding frame number.
6.​Display the physical memory address
Program Code:
#include<stdio.h>
#include<math.h>
void main()
{
double npages;
int n,ps,pn,off,fnumber,m,i;
int pagetable[100];
printf("enter process size");
scanf("%d",&ps);
printf("\nenter page size");
scanf("%d",&m);
npages=ceil(ps/m);
n=npages;
printf("\nenter page table details");
for(i=0;i<n;i++)
{
scanf("%d",&pagetable[i]);
}
printf("\nenter page number");
scanf("%d",&pn);
printf("\nenter offset");
scanf("%d",&off);
printf("\npagetable");
printf("\npage number frame number");
for(i=0;i<n;i++)
{
printf("\n");
printf("%d\t%d",i,pagetable[i]);
}
fnumber=pagetable[pn];
printf("\nframe number offset
value:");
printf("%d%d",fnumber,off);
printf("\nThe corresponding physical address is %d",(fnumber*m)+off);
}

VirtualmemorySimulator

Explanation
$Page fault occurs but our physical pages are empty. So we don't need to find any victim page from
physical memory.

$page fault occurs but our physical pages are empty. So we don't need to find any victim page from
physical memory.

$page fault occurs but our physical pages are empty. So we don't need to find any victim page from
physical memory.

$hey! It's a page hit our virtual page(6) maps to physical page(2).

$hey!It's a page hit our virtual page(4) maps to physical page(1).


$page fault occurs but our physical pages are empty. So we don't need to find any victim page from
physical memory.
$ page fault occurs but our physical memory is full now.so we have to find an victim page from
physical memory to replace it with our current virtual page(1). now to find victim page we apply our
page replacement policy this time it is fifo. By this policy victim page found is 0 which is not dirty.
Sowe don't require to copy it back on disk. Now it's over, we just have to replace this victim page
withourvirtual page.
$hey! It's a page hit our virtual page(6) maps to physical page(2).
$ page fault occurs but our physical memory is full now.so we have to find an victim page from
physical memory to replace it with our current virtual page(5).now to find victim page we apply our
page replacement policy this time it is fifo. By this policy victim page found is 1 which is not dirty.
Sowe don't require to copy it back on disk. Now it's over, we just have to replace this victim page with
our virtual page.

$ page fault occurs but our physical memory is full now. so we have to find an victim page from
physical memory to replace it with our current virtual page(4). now to find victim page we apply
ourpage replacement policy this time it is fifo. By this policy victim page found is 3 which is not dirty.
Sowe don't require to copy it back on disk. Now it's over, we just have to replace this victim page with
our virtual page.

$hey! It's a page hit our virtual page(1) maps to physical page(0).

$ page fault occurs but our physical memory is full now.so we have to find an victim page
fromphysical memory to replace it with our current virtual page(0). now to find victim page we apply
ourpage replacement policy this time it is fifo. By this policy victim page found is 2 which is not dirty.
Sowe don't require to copy it back on disk. Now it's over, we just have to replace this victim page with
our virtual page.

$ page fault occurs but our physical memory is full now.so we have to find an victim page
fromphysical memory to replace it with our current virtual page(3). now to find victim page we apply
ourpage replacement policy this time it is fifo. By this policy victim page found is 1 which is not dirty.
Sowe don't require to copy it back on disk. Now it's over, we just have to replace this victim page with
our virtual page.

$ page fault occurs but our physical memory is full now. so we have to find an victim page from
physical memory to replace it with our current virtual page(5). now to find victim page we apply our
page replacement policy this time it is fifo. By this policy victim page found is 3 which is not dirty.
Sowe don't require to copy it back on disk. Now it's over, we just have to replace this victim page with
our virtual page.

$ hey! It's a page hit our virtual page(1) maps to physical page (0).Hey! It's a page hit our virtual page(5)
maps to physical page(3).

$hey!It's a page hit our virtual page(0) maps to physical page(2).

$ page fault occurs but our physical memory is full now.so we have to find an victim page from
physical memory to replace it with our current virtual page(2). now to find victim page we apply
ourpage replacement policy this time it is fifo. By this policy victim page found is 1 which is not dirty.
Sowe don't require to copy it back on disk. Now it's over, we just have to replace this victim page with
our virtual page.

53
Result:

Thus the program has been executed and Virtual memoryhas been simulated.

VivaQuestions:
1.​ What is Paging?
2.​ Define Page Table.
3.​ What is Fragmentation?
4.​ State Segmentation.
Ex.No:11 Write C programs to implement the following Memory Allocation
Date: Methods
a.​ First Fit
b.​ Worst Fit
C.​ Best Fit

Aim
To allocate memory requirements for processes using the first-fit, best-fit, or worst-fit strategy
isusedto select a freeholefrom theset ofavailableholes.
Firstfit
●​ Allocate the first hole that is big enough.
●​ Searching starts from the beginning of set of holes.
Algorithm
1.​Get number of holes/partitions, say m.
2.​Get the size of each hole/partition.
3.​Get number of processes, say n.
4.​Get the memory requirements for each process.
5.​Allocate processes to holes,by examining each holeas follows:
a.​If holesize>process size then
i.​Mark process as allocated to that hole.
ii.​Decrement hole size by processs size.
b.​Otherwise check the next from these tof holes
6.​Print the list of process and their allocated holes or unallocated status.
7.​Print the list of holes,their actual and current availability.
8.​Stop
Bestfit
●​ Allocate the smallest hole that is big enough.
●​ The list of free holes is kept sorted according to size in ascending order.
Algorithm
1.​Get number of holes, say m.
2.​Getthe size of each hole
3.​Get number of processes, say n.
4.​Get the memory requirements for each process.
5.​Allocate processes to holes,by examining each hole as follows:
a.​Sortthe holes according to their sizes in ascending order
b.​If holesize>process size then
i.​Mark process as allocated to that hole.
ii.​Decrement hole size by processsize.
c.​Otherwise check the next from the set of sortedholes
6.​Print the list of process and their allocated holes or unallocated status.
7.​Print the list of holes,their actual and current availability.
8.​Stop
Worst fit
●​ Allocate the largest hole.
●​ The list of free holes is kept sorted according to size in descending order.
Algorithm
1.​Get number of holes, say m.
2.​Get the sizeof each hole
3.​Get number ofprocesses, sayn.
4.​Get the memory requirements for each process.
5.​Allocate processes to holes,by examining each hole as follows:
a.​Sort the holes according to their sizes in descending order
b.​If hole size>process size then
i.​Mark process as allocated to that hole.
ii.​Decrement hole sizebyprocesssize.
c.​Otherwise check the next from theset of sorted holes
6.​Print the list of process and their allocated holes or unallocated status.
7.​Print the list of holes,their actual and current availability.
8.​Stop

Program Code
#include<stdio.h>
void main()
{
int memory[50], process[50], i, j, p, m, assign[50], r[50];
printf("Enter number of memory partitions and processes : ");
scanf("%d%d",&m,&p);
printf("Size of all memory spaces : \n");
for(i=0; i<m; i++)
{
printf("Partition%d:",(i+1));
scanf("%d", &memory[i]);
r[i] =memory[i];
}

printf("Size of all processes : \n");

for(i=0; i<p; i++) {


printf("Process%d: ",(i +1));
scanf("%d", &process[i]);
assign[i] = -1;
}

for(i=0; i<p; i++)


{
for(j=0; j <m; j++)
{
if(memory[j] >= process[i]) {
assign[i] = (j + 1);
memory[j] -= process[i];
break;
}
}

}
printf("Proc\tSize\tAssignment\n");
for(i=0; i<p; i++)

{
printf("%d\t%d\t%d\n",(i+1),process[i],assign[i]);
}

printf("Hole\tSize\tRemain\n");
for(j=0; j <m; j++)

{
printf("%d\t%d\t%d\n",(j+1),r[j],memory[j]);
}
}

OUTPUT:

Enter number of memory partitions and processes :


53
Size of all memory spaces
:Partition1 : 100
Partition2 :200
Partition3 :300
Partition4 :500
Partition5 :600
Size of all processes :
Process1 :
50
Process2:20
0
Process3:55
0
Proc Size Assignment
1 50 1
2 200 2
3 550 5

Hole Size Remain


1 100 50
2 200 0
3 300 300
4 500 500
5 600 50

//BestFit
#include<stdio.h>
void main()
{
int i,j,n,m,a[10],b[10],c[10],min;
printf("enter the no of processes");
scanf("%d",&n);
printf("enter the no.of holes");
scanf("%d",&m);
printf("Enter the processes");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the holes");
for(j=0;j<m;j++)
{
scanf("%d",&b[j]);
}
i=0,j=0;
printf("processes\tprocessessize\tholes" );
for(i=0;i<n;i++)
{
min=0;
for(j=0;j<m;j++)
{
if(b[j]<b[min]&&a[i]<=b[min])
{
min=j;
}
}
b[min]=b[min]-a[i];

printf("\n%d\t%d\t%d\t",i,a[i],min+1);
}
printf("Remaining holesize\n");
for(j=0;j<m;j++)
{
printf("\n%d",b[j]);
}
}

OUTPUT:
enter the no of processes2
enter the no.of holes3
Entertheprocesses

100
200
Enter the holes
300
400
500
processes processessize holes
0 100 1
1 200 1
Remaining
holesize0
400
500

// Worst Fit

#include<stdio.h>
void main()
{
int i,j,n,m,a[10],b[10],c[10],max;
printf("enter the no of processes");
scanf("%d",&n);
printf("enter the no.of holes");
scanf("%d",&m);
printf("Enter the processes");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the holes");
for(j=0;j<m;j++)
{
scanf("%d",&b[j]);
}
i=0,j=0;
printf("processes\tprocessessize\tholes" );
for(i=0;i<n;i++)
{
max=0;
for(j=0;j<m;j++)
{
if(b[j]>b[max]&&a[i]<=b[max])
{
max=j;
}
}
b[max]=b[max]-a[i];

printf("\n%d\t%d\t%d\t",i,a[i],max+1);
}
printf("Remaining holesize\n");
for(j=0;j<m;j++)
{
printf("\n%d",b[j]);
}
}
OUTPUT:

enter the no of processes


2
enter the no.of holes
3
Enter the processes
100
200
Enter the holes
300
400
600

processes processes
size holes
0 100 3
1 200 3
Remaining hole size

300
400
300
Result:
The programs have been implemented and executed successfully.

VivaQuestions:
1.​ Define logical address and physical address.
2.​ What is logical address space and physical address space?
3.​ What is the main function of the memory-management unit?
4.​ What are the common strategies to select a free hole from a set of available holes?
5.​ What do you mean by best fit?
6.​ What do you mean by first fit?
61
Ex.No:12 Implement the various Page Replacement Algorithms
Date:

Aim:
To write a C program to implement FIFO page replacement algorithm.

ALGORITHM:
1.​ Read the size of the frame, no. of elements and elements one by one.
2.​ Initialize the frames with value-1.
3.​ Insert each element in to frame, if it ‘s already not present.
4.​ If the frame is full and the new element is not already present, then replace the
oldest element by the new element.
5.​ Increment no.of page faults by one while inserting each element into the frames.
6.​ Display the contents of frames during processing and the total no. of page faults.

PROGRAM:
#include <stdio.h>
#include <conio.h>
int
refstr[50],cq[10];
int f=0,r=0,pf=0,nof,len;
int check(int);
void addq(int);
int main()
{
int temp,i,count,p,f1;
printf("\n\n\tFIFO PAGE REPLACEMENT ALGORITHM\n\n");
printf("Enter the no of frames\n");
scanf("%d",&nof);
printf("\nEnter the number of
elements\n"); scanf("%d",&len);
for(count=0;count<nof;count++)
cq[count]=-1;
printf("\nEnter the elements\n");
for(i=0;i<len;i++)
scanf("%d",&refstr[i]);
count=0;
printf("\n\t CONTENTS OFFR A MES DURING PROCESSING\n\n");
for(i=0;i<nof;i++)
printf("F[%d]\t",i);
printf("Page
fault\n"); do
{
p=refstr[count];
f1=check(p);
if(f1==0)
62
{
addq(p);
pf+=1;
}
count+=1;
for(i=0;i<nof;i++)
printf("%d\t",cq[i]);
if(f1==0)
printf("*\n");
else
printf("-\n");
}while(count<len);
printf("\nNoofpagefaults:%d\n",pf);
}
int check(intx)
{
int i;
for(i=0;i<r;i++)
if(cq[i]==x)
return(1);
return(0);
}
void addq(int x)
{
if(r==nof)
{​
cq[f]=
x; f++;
}
else
{
cq[r]=x
; r++;
}
}

Least Recently Used(LRU)


Algorithm:
1.​ Read the size of the frame, no. of elements and elements one by one.
2.​ Initialize the frames with value -1.
3.​ Insert each element into frame, if it‘s already not present.
4.​ If the frame is full and new element is not already present then replace the leas trecently
used element by the new element.
5.​ Increment no.of page faults by one while inserting each element into the frames.
6.​ Display the contents of frames during processing and the total no. of page faults.
Program:
void pg(intf[],intsz);
void npg(int f[],int sz);
int sort(int ind[],int sz);
#include<stdio.h>
main()
{
int d,ft=0,g,i,j,n,sz,a[30],f[10],t,r,x,temp,s,pos,ind[10];
printf("\n\n\tLRU PAGE REPLACEMENT ALGORITHM\n\nEnter the size of frame:");
scanf("%d",&sz);
printf("\nEnter the no. of elements:");
scanf("%d",&n);
printf("\nEnter the elements:\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=sz;i++)
f[i]=-1;
printf("\n\tContents of frames during processing\n\n");
for(i=1;i<=sz;i++)
printf("F[%d]\t",i);
printf("PF\n");
for(i=1;i<=sz;i++)
printf("%d\t",f[i]);
printf("\n");
f[1]=a[1];
pg(f,sz);
ft++;
for(i=2;i<=n;i++)
{
g=0
;
for(j=1;j<=sz;j++)
{
if(f[j]==a[i])
{
npg(f,sz);
g++;
break;
}
}
if(g==0)
{
t=0;
for(r=1;r<=sz;r++)
{
if(f[r]==-1)
{
f[r]=a[i];
pg(f,sz);
ft++;
t++;
break;
}
}
if(t==0)
{
for(x=1;x<=sz;x++)
{
temp=f[x];
for(s=1;s<=i-1;s++
)
{
if(temp==a[s])
{
pos=s;
}
}
ind[x]=pos;
}
d=sort(ind,sz);
f[d]=a[i];
pg(f,sz);
ft++;
}
}
}
printf("\n\nNo.ofpage faults=%d\n\n",ft);
}
void npg(int f[],int sz)
{
int i;
for(i=1;i<=sz;i++)
printf("%d\t",f[i]);
printf("-\n");
}
void pg(int f[],int sz)
{
int i;
for(i=1;i<=sz;i++)
printf("%d\t",f[i]);
printf("*\n");
}
int sort(int ind[],int sz)
{
int c,d,max=999;
for(c=1;c<=sz;c++)
{
if(ind[c]<max)
{
max=ind[c];
d=c;
}
}
return(d);
}

LFU Page Replacement Algorithm


#include<stdio.h>
#include<conio.h>
main()
{
intrs[50],i,j,k,m,f,
cntr[20],a[20],min,pf=0;clrscr(); printf("\nEnter
number of page references --");
scanf("%d",&m);
printf("\nEnterthereferences tring--");
for(i=0;i<m;i++)
scanf("%d",&rs[i]);
printf("\nEntertheavailableno.offrames--")
; scanf("%d",&f);
for(i=0;i<f;i++)
{
cntr[i]=0
; a[i]=-1;
}
Printf(“\nThe Page Replacement Process is–\n“);
for(i=0;i<m;i++)
{
for(j=0;j<f;j++)
if(rs[i]==a[j])
{
cntr[j]++;
break;
}
if(j==f)
{
min =0;
for(k=1;k<f;k++)
if(cntr[k]<cntr[min])
min=k;
a[min]=rs[i];
cntr[min]=1;
pf++;
}
printf("\n");
for(j=0;j<f;j++)
printf("\t%d",a[j]);
if(j==f)
printf(“\tPFNo.%d”,pf);
}
printf("\n\nTotal number of page faults--%d",pf);
}
Ente rnumber of page references--10
Enter the reference
string--123452525143 Enter the available
no.of frames--3

OUTPUT
1-1 -1 PFNo. 1
12 -1 PFNo. 2
12 3 PFNo. 3
4 23 PFNo. 4
5 23 PFNo. 5
523
523
52 1 PFNo. 6
52 4 PFNo. 7
52 3 PFNo. 8
Total number of page faults- -8

Result:

Thus the page replacement algorithms have been executed successfully.

Viva Questions:
1.​ What is virtual memory?
2.​ Define effective access time.
3.​ What is the basic approach of page replacement?
4.​ What are the various spage replacement algorithms used for page replacement?
5.​ What are the major problems to implement demand paging?
Ex.No:13 File Organization Techniques
Date:

Aim:

To implement various file organization techniques

Description:
The directory structure is the organization of files into a hierarchy of folders.In a single-level directory
system, all the files are placed in one directory. There is a root directory which has all files.It has a
simple architecture and there are no sub directories. Advantage of single level directory system is that
it is easy to find a file in the directory. In the two-level directory system, each user has own user file
directory (UFD). The system maintains a master block that has one entry for each user.This master
block contains the addresses of the directory of the users.When a user job starts or a user logs in,the
system's master file directory(MFD)is searched.When a user refers to a particular file,only his own
UFD is searched.This effectively solves the name collision problem and isolates users from one
another. Hierarchical directory structure allows users to create their own sub directories and to
organize their files accordingly. A tree is the most common directory structure. The tree has a root
directory,and every file in the system has a unique path name. A directory (or subdirectory) contains a
set of files or subdirectories.

13.1​ SingleLevelDirectory

AIM:
To write a c program to implement the single level directory file organization.

PROGRAM:
#include <stdio.h>
#include<string.h>

int main()
{
char d[20];
charf[20][20];
int
i,j,nfiles,flag;
chartemp[20];
printf("enter names of the master directory:");
scanf("%s",d);
printf("enter size of directory:");
scanf("%d",&nfiles);
printf("enter the file names :");
scanf("%s",f[0]);
for(i=1;i<nfiles;)
{
scanf("%s",temp);
j=0; flag=0;
while(j<i)
{
if((strcmp(f[j],temp))==0)
{
printf("Overwritingexistingfile!");
flag=1
; break;
}j+
+;
}
if(flag==0)
{
strcpy(f[i],temp);
i++;
}
}
printf("\n");
printf(" directory\tsize\n");
printf("************************\n");
printf("%s\t\t%2d\n",d,nfiles);
printf("Files in the directory\n");
printf("************************\n");
for(i=0;i<nfiles;i++)
{
printf("%s\n",f[i]);
}
}
Output:
enter names of the master directory:
root enter size of directory:4
enter the file names
:iij
j jj
Over writing existing
file!kk
ll

directory​ size
***********************
* root​ 4
Files in the directory
************************
ii
jj
k
kl
l
13.2.​ Two Level Directory

AIM:
To write a c program to implement the two level directory file organization.
PROGRAM:
#include<stdio.h>
struct st
{
char dname[10];
char
fname[10][10]; int
ds;
}dir[10];

void main()
{
int i,j,k,n;
printf("enter number of directories:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter directory %d names:",i+1);
scanf("%s",dir[i].dname);
printf("enter size of directories:");
scanf("%d",&dir[i].ds);
printf("enter file names:");
for(j=0;j<dir[i].ds;j++)
{
scanf("%s",dir[i].fname[j]);
}
}
printf("\ndirname\t\tsize\t\tfiles");
printf("\n******************************************************\n");
for(i=0;i<n;i++)
{
printf("%s\t\t%d\t\t",dir[i].dname,dir[i].ds)
; for(j=0;j<dir[i].ds;j++)
{
printf("%s\t",dir[i].fname[j]);
printf("\n\t\t\t\t");
}
printf("\n");

}
}
Output
enter number of directories:2
enter directory 1 names:user2
enter size of directories:2
enter file names:cat
test
enter directory 2 names:user3
enter size of directories:1
enter file names:at

dirname​ size​ files


*****************************************************
* user2​ 2​ cat
test

user3​ 1​ at

Description:
Hierarchical directory structure allows users to create their own sub directories and to organize their
files accordingly. A tree is the most common directory structure. The tree has a root directory, and
every file in the system has a unique pathname. A directory (or subdirectory) contains a set of files or
sub directories.

13.3​ HierarchicalLevelDirectory

AIM:
To write a c program to implement the hierarchical level directory file organization.

ALGORIHTM:
Step1.Start
Step2. Define structure and declare structure variables
Step3.Start main and declare variable
Step4.Create a directory tree structure
Step5.Display the directory tree in graphical mode
Step6. Get the names of the root directory and files are organized with this
directoryStep7.Stop the program

PROGRAM:
#include<stdio.h>
#include<graphics.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct
tree_element*link[5];
};
type def struct tree_elementnode;
void main()
{
int gd=DETECT,gm;
node *root;
root=NULL;
clrscr();
create(&root,0,"root",0,639,320);
clrscr();
init graph(&gd,&gm,"c:\tc\BGI");
display(root);
getch();
closegraph();
}

create(node **root,int lev,char *dname,int lx,int rx,int x)


{
int i,gap;
if(*root==NULL)
{
(*root)=(node*)malloc(sizeof(node));
printf("Enter name of dir/file(under %s) : ",dname);
fflush(stdin);
gets((*root)->name);
printf("enter 1 for Dir/2 for file
:"); scanf("%d",&(*root)->ftype);
(*root)->level=lev;
(*root)->y=50+lev*50
; (*root)->x=x;
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++
)
(*root)->link[i]=NULL
; if((*root)->ftype==1)
{
printf("No of sub directories/files(for
%s):",(*root)->name); scanf("%d",&(*root)->nc);
if((*root)->nc==0)
gap=rx-lx;
else
gap=(rx-lx)
/
(*root)->nc
;
for(i=0;i<(*root)->nc;i++)
create(&((*root)->link[i]), lev+1, (*root)>name, lx+gap*i, lx+gap*i+gap, lx+gap*i+gap/2);
}
else
(*root)->nc=0;
}
}
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root!=NULL)
{
for(i=0;i<root->nc;i++)
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1)
bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}
}
}
Output:

13.4.​ Directed Acyclic

GraphAIM:
To writea c program to implement the directed acyclic graph of file organization.

ALGORIHTM:
Step1.Start
Step2. Define structure and declare structure variables
Step3.Start main and declare variable
Step4.Create a directory tree structure
Step5. Display the directory tree in graphical mode
Step6. Get the names of the root directory and files are organized with this graph structure.
Step7.Stop the program.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<string.h>
structtree_element
charname[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element*link[5];
};
typedef struct tree_elementnode;
typedef struct
{
char
from[20];
char to[20];
}link;
Link
L[10]; int
nofl; node *
root; void
main()
{
int gd=DETECT,gm;
root=NULL;clrscr();
create(&root,0,"root",0,639,320)
; read_links();
clrscr();
initgraph(&gd,&gm,"c:\tc\BGI")
; draw_link_lines();
display(root);
getch();
closegraph();
}
read_links()
{
int i;
printf("how many links");
scanf("%d",&nofl);
for(i=0;i<nofl;i++)
printf("File/dir:");
fflush(stdin);
gets(L[i].from);
printf("user
name:");
fflush(stdin);
gets(L[i].to);
}
}
draw_link_lines()
{
int i,x1,y1,x2,y2;
for(i=0;i<nofl;i++)
{
search(root,L[i].from,&x1,&y1);
search(root,L[i].to,&x2,&y2);
setcolor(LIGHTGREEN);
setlinestyle(3,0,1);
line(x1,y1,x2,y2);
setcolor(YELLOW);
setlinestyle(0,0,1);
}
}
search(node*root,char*s,int*x,int*y)
{
int i;
if(root!=NULL)
{
if(strcmpi(root->name,s)==0)
{
*x=root->x;
*y=root->y;
return;
}
else
{
for(i=0;i<root->nc;i++)
search(root->link[i],s,x,y)
;
}
}
}
create(node**root,intlev,char*dname,intlx,intrx,intx)
{
int i,gap;
if(*root==NULL)
(*root)=(node*)malloc(sizeof(node));
printf("enter name of dir/file(under
%s):",dname); fflush(stdin);
gets((*root)->name);
printf("enter 1 for dir/ 2 for
file:");
scanf("%d",&(*root)->ftype);
(*root)->level=lev;
(*root)->y=50+lev*50
; (*root)->x=x;
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++
)
(*root)->link[i]=NULL
; if((*root)->ftype==1)
{
printf("no of sub directories /files (for
%s):",(*root)->name);
scanf("%d",&(*root)->nc);if((*root)->nc==0)
gap=rx-lx;
else
gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++
)
create( &((*root)->link[i] ),lev+1, (*root)->name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
Else
(*root)->nc=0;
}
}
/* displays the constructed tree in graphics mode
*/display(node*root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root!=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1)
bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}
}
}

OUTPUT

Result:
Thus,the programs have been executed successfully.

VivaQuestions:

1.​ What is a file?


2.​ List the various file organization techniques.
3.​ State File Structure
4.​ What is a logical file system?
5.​ State file mounting and unmounting.
Ex.No:14
Implement the following File Allocation Strategies
Date: using C programs
a. Sequential b. Indexed c. Linked
AIM:
To write a C Program to implement Sequential,Indexed and Linked File Allocation methods.

DESCRIPTION:
Sequential allocation
●​ Each file in the disk occupies a contiguous address space on the disk.
●​ In this scheme, the address is assigned in the linear fashion.
●​ This is very easy to implement the contiguous allocation method.
●​ In the contiguous allocation technique, external fragmentation is a major issue.

Indexed allocation

●​ In this scheme, a special block known as the index block contains the pointer to all the
blocks occupied by a file.
●​ Each file contains its index which is in the form of an array of disk block addresses.
●​ The ith entry of index block point to the ith block of the file.
●​ The address of the index block is maintained by the directory.
●​ When we create a file all pointer is set to nil.
●​ A block is obtained from the free space manager when the first ith block is written.
●​ When the index block is very small it is difficult to hold all the pointers for the large file to
deal with this issue a mechanism is available.

Linked allocation
●​ In this scheme, disk blocks are arranged in the linked list form which is not contiguous.
●​ In this scheme, the directory entry contains the pointer of the first block and pointer of the
ending block.
●​ Each pointer contains the address of the next block.
●​ When we create a new file we simply create a new entry with the linked allocation.
●​ Each directory contains the pointer to the first disk block of the file.
●​ When the pointer is null then it defines the emptyfile.

PROGRAM:

#include<stdio.h>
void main()
{
int
n=0,i,j,b[20],sb,len,flag=0,t[20],x,c[20][20],y;
intdiskspace[50];//50 blocks
do
{
printf("Enter the starting block of file%d:",i+1);
scanf("%d",&sb);
printf("Enter no. of blocks(length) occupied by file%d:",i+1);
scanf("%d",&len);
for(j=sb;j<(sb+len);j++)
{
if(diskspace[j]==1)
{
printf("Space can't be allocated");
flag=1;
break;
}
}
if(flag==0)
{
t[n]=sb;
b[n]=len
; n++;
for(j=sb;j<(sb+len);j++)
{
diskspace[j]=1;
}
}
printf("\n Do you want to enter more files?(y-1/n-0)");
scanf("%d",&y);
flag=0;
}while(y==1);

printf("Filename\tStart\tLength\n");
for(i=0;i<n;i++)
printf("%d\t%d
\t%d\n",i+1,t[i],b[i]);
printf("Enterfilename:");
scanf("%d",&x);
printf("File name is:%d\n",x);
printf("length is:%d\n",b[x-1]);
printf("blocks occupied:");
for(i=t[x-1];i<(t[x-1]+b[x-1]);i++
)
printf("%4d",i);

Output:

Enter the starting block of file1:0


Enter no.of blocks(length) occupied by file1:2

Do you want to enter more files?(y-1/n-0)1


Enterthestartingblock of file1:1
Enter no. of blocks(length) occupied by file1:3
Space can't be allocated
Do you want to enter more files?(y-1/n-0)1
Enter the starting block of file1:14
Enter no.of blocks(length) occupied by file1:3

Do you want to enter more files?(y-1/n-0)1


Enter the starting block of file1:19
Enter no.of blocks(length) occupied by file1:6

Do you want to enter more


files?(y-1/n-0)0 Filename​ Start​ Length
1​ 0​ 2
2​ 14​ 3
3​ 19​ 6
Enter file name:2
File name is:2
Length is:3
Blocks occupied:14 15 16
Indexed File Allocation
#include<stdio.h>
void main()
{
int
n,m[20],i,j,sb[20],s[20],b[20][20],x;
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
b[i][j]=-1;
}
printf("Enter no. of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{​ printf("Enter index block and size of index block%d:",i+1);
scanf("%d%d",&sb[i],&s[i]);
printf("Enter no. of blocks occupied by file%d:",i+1);
scanf("%d",&m[i]);
printf("enter blocks of file%d:",i+1);
for(j=0;j<m[i];j++)
scanf("%d",&b[i][j]);
}
printf("\nFile\t index\tlength\n");
for(i=0;i<n;i++)
{
printf("%d\t%d\t%d\n",i+1,sb[i],m[i]);
}
printf("\nEnter file name:");
scanf("%d",&x);
printf("file name is:%d\n",x);
i=x-1;
printf("Index is:%d\n",sb[i]);
printf("Block occupied are:");
for(j=0;j<s[i];j++)
printf("%3d",b[i][j]);

}
Output:
Enter no.of files:1
Enter index block and size of index block1:198
Enter no. of blocks occupied by file1:5
Enter blocks of file1:9
16
1
10
25
File​ index length
1​ 19​ 5
Enter file name:1
file name is:1
Index is:19
Block occupied are:9161 1025-1 -1-1

Linked File Allocation

#include<stdio.h>
struct file
{
Char fname[10];
int start,size,block[10];
}f[10];
void main()
{
int i,j,n;
printf("Enter no. of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter file name:");
scanf("%s",f[i].fname);
printf("Enter starting block:");
scanf("%d",&f[i].start);
f[i].block[0]=f[i].start;
printf("Enter no.of blocks:");
scanf("%d",&f[i].size);
printf("Enter block numbers:");
for(j=1;j<=f[i].size;j++)
{
scanf("%d",&f[i].block[j]);
}
}
printf("File\tstart\tsize\tblock\n");
for(i=0;i<n;i++)
{
printf("%s\t%d\t%d\t",f[i].fname,f[i].start,f[i].size)
; for(j=1;j<=f[i].size-1;j++)
printf("%d--->",f[i].block[j]);
printf("%d",f[i].block[j]);
printf("\n");
}
}
Output:
Enter no. of files:1
Enter file name:jeep
Enter starting block:9
Enter no.of blocks:5
Enter block numbers:116
9
10
25
File start size block
Jeep 951--->16--->9--->10--->25

Result:

Thus the programs for File Allocation Strategies have been executed successfully.

Viva Questions

1.​ What is a file?


2.​ List the various file attributes.
3.​ What are the various file operations?
4.​ What are the various file allocation strategies?
5.​ State the advantages and dis advantages of linked allocation.
Ex.No:15 Write C programs for the implementation of various disk scheduling
algorithms
Date:

Aim:
To write C programs for the implementation of various disk scheduling algorithms.

Description:
Disk scheduling is done by operating systems to schedule I/O requests arriving for the disk. Disk
scheduling is also known as I/O scheduling.
Disk scheduling is important because:
●​ Multiple I/O requests may arrive by different processes and only one I/O request can be served at
a time by the disk controller. Thus other I/O requests need to wait in the waiting queue and need
to be scheduled.
●​ Two or more request may be far from each other so can result in greater disk arm movement.
●​ Hard drives are one of the slowest parts of the computer system and thus need to be accessed in
an efficient manner.
Disk Scheduling Algorithms:
1.​ First Come First Serve (FCFS)
FCFS is the simplest of all the Disk Scheduling Algorithms. In FCFS, the requests are addressed in
the order they arrive in the disk queue
ALGORITHM:
1.​ Request array represents an array storing indexes of tracks that have been requested in
ascending order of their time of arrival. ‘head’ is the position of disk head.
2.​ Take the tracks one by one in default order and calculate the absolute distance of the track from
the head.
3.​ Increment the total seek count with this distance.
4.​ Currently serviced track position now becomes the new head position.
5.​ Go to step 2 until all tracks in request array have not been serviced.

PROGRAM:
#include
<stdio.h>
#include
<math.h> int size
= 8;
void FCFS(int arr[],int head)
{
int seek_count = 0;
int cur_track, distance;
for(int i=0;i<size;i++)
{
cur_track = arr[i];
// calculate absolute distance
distance = fabs(head - cur_track);
// increase the total count
seek_count += distance;
// accessed track is now new head
head = cur_track;
}
printf("Total number of seek operations: %d\n",seek_count);
// Seek sequence would be the same
// as request array sequence
printf("Seek Sequence is\n");
for (int i = 0; i< size; i++) {
printf("%d\n",arr[i]);
}
}
//Driver code
int main()
{
// request array
int arr[8] = { 176, 79, 34, 60, 92, 11, 41, 114 };
int head = 50;
FCFS(arr,head);
return 0;
}

Output:
Total number of seek operations = 510
Seek Sequence is
176
79
34
60
92
11
41
114

2.​ Shortest Seek Time First (SSTF)


FCFS is the simplest of all the Disk Scheduling Algorithms. In FCFS, the requests are addressed in the
order they arrive in the disk queue.
ALGORITHM:
1.​ Request array represents an array storing indexes of tracks that have been requested. ‘head’ is
the position of disk head.
2.​ Find the positive distance of all tracks in the request array from head.
3.​ Find a track from requested array which has not been accessed/serviced yet and has
minimum distance from head.
4.​ Increment the total seek count with this distance.
5.​ Currently serviced track position now becomes the new head position.
6.​ Go to step 2 until all tracks in request array have not been serviced.

PROGRAM:
#include<stdio.h>
#include<stdlib.h
> int main()
{
int RQ[100],i,n,TotalHeadMoment=0,initial,count=0;
printf("Enter the number of Requests\n");
scanf("%d",&n);
printf("Enter the Requests sequence\n");
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
printf("Enter initial head position\n");
scanf("%d",&initial);
// logic for sstf disk scheduling
/* loop will execute until all process is completed*/
while(count!=n)
{
int
min=1000,d,index;
for(i=0;i<n;i++)
{
d=abs(RQ[i]-initial);
if(min>d)
{
min=d;
index=i
;
}
}
TotalHeadMoment=TotalHeadMoment+min;
initial=RQ[index];
// 1000 is for max
// you can use any
number RQ[index]=1000;
count++;
}
printf("Total head movement is %d",TotalHeadMoment);
return 0;
}
Output:
Enter the number of Request
8
Enter Request Sequence
95 180 34 119 11 123 62 64
Enter initial head Position
50
Total head movement is 236
3.​ SCAN (Elevator) algorithm:
In SCAN disk scheduling algorithm, head starts from one end of the disk and moves towards the
other end, servicing requests in between one by one and reach the other end. Then the direction of the
head is reversed and the process continues as head continuously scan back and forth to access the
disk.
ALGORITHM:
1.​ Request array represents an array storing indexes of tracks that have been requested in
ascending order of their time of arrival. ‘head’ is the position of disk head.
2.​ Direction represents whether the head is moving towards left or right.
3.​ In the direction in which head is moving service all tracks one by one.
4.​ Calculate the absolute distance of the track from the head.
5.​ Increment the total seek count with this distance.
6.​ Currently serviced track position now becomes the new head position.
7.​ Go to step 3 until we reach at one of the ends of the disk.
8.​ If we reach at the end of the disk reverse the direction and go to step 2 until all tracks in
request array have not been serviced.
PROGRAM:
#include
<stdio.h>
#include
<math.h> int
main()
{
int queue[20], n, head, i, j, k, seek = 0, max, diff, temp, queue1[20],
queue2[20], temp1 = 0, temp2 = 0;
float avg;
printf("Enter the max range of disk\n");
scanf("%d", &max);
printf("Enter the initial head position\n");
scanf("%d", &head);
printf("Enter the size of queue request\n");
scanf("%d", &n);
printf("Enter the queue of disk positions to be
read\n"); for (i = 1; i<= n; i++)
{
scanf("%d", &temp);
if (temp >=
head)
{
queue1[temp1] = temp;
temp1++;
}
else
{
queue2[temp2] = temp;
temp2++;
}
}
for (i = 0; i< temp1 - 1; i++)
{
for (j = i + 1; j < temp1; j++)
{
if (queue1[i] > queue1[j])
{
temp = queue1[i];
queue1[i] = queue1[j];
queue1[j] = temp;
}
}
}
for (i = 0; i< temp2 - 1; i++)
{
for (j = i + 1; j < temp2; j++)
{
if (queue2[i] < queue2[j])
{
temp = queue2[i];
queue2[i] = queue2[j];
queue2[j] = temp;
}
}
}
for (i = 1, j = 0; j < temp1; i++, j++)
queue[i] = queue1[j];
queue[i] = max;
for (i = temp1 + 2, j = 0; j < temp2; i++, j++)
queue[i] = queue2[j];
queue[i] = 0;
queue[0] = head;
for (j = 0; j <= n + 1; j++)
{
diff = abs(queue[j + 1] - queue[j]);
seek += diff;
printf("Disk head moves from %d to %d with seek %d\n", queue[j],
queue[j + 1], diff);
}
printf("Total seek time is %d\n", seek);
avg = seek / (float)n;
printf("Average seek time is %f\n", avg);
return 0;
}

Output:
Enter the max range of disk
200
Enter the initial head position
50
Enter the size of queue request
8
Enter the queue of disk positions to be read
95 180 34 119 11 123 62 64
Disk head moves from 50 to 62 with seek 12
Disk head moves from 62 to 64 with seek 2
Disk head moves from 64 to 95 with seek 31
Disk head moves from 95 to 119 with seek 24
Disk head moves from 119 to 123 with seek 4
Disk head moves from 123 to 180 with seek 57
Disk head moves from 180 to 200 with seek 20
Disk head moves from 200 to 34 with seek 166
Disk head moves from 34 to 11 with seek 23
Disk head moves from 11 to 0 with seek 11
Total seek time is 350
Average seek time is 43.750000

4.​ LOOK Disk Scheduling Algorithm:


LOOK is the advanced version of SCAN (elevator) disk scheduling algorithm which gives slightly
better seek time than any other algorithm in the hierarchy (FCFS->SRTF->SCAN->C-SCAN-
>LOOK). The LOOK algorithm services request similarly as SCAN algorithm meanwhile it also
“looks” ahead as if there are more tracks that are needed to be serviced in the same direction. If there
are no pending requests in the moving direction the head reverses the direction and start servicing
requests in the opposite direction.

ALGORITHM:
1.​ Request array represents an array storing indexes of tracks that have been requested in
2.​ Ascending order of their time of arrival. ‘head’ is the position of disk head.
3.​ The intial direction in which head is moving is given and it services in the same direction.
4.​ The head services all the requests one by one in the direction head is moving.
5.​ The head continues to move in the same direction untill all the request in this direction are
6.​ not finished.
7.​ While moving in this direction calculate the absolute distance of the track from the head.
8.​ Increment the total seek count with this distance.
9.​ Currently serviced track position now becomes the new head position.
10.​Go to step 5 until we reach at last request in this direction.
11.​If we reach where no requests are needed to be serviced in this direction reverse the
12.​Direction and go to step 3 until all tracks in request array have not been serviced.

PROGRAM:
#include<stdio.h>
#include<stdlib.h
> int main()
{
int
RQ[100],i,j,n,TotalHeadMoment=0,initial,size,move;
printf("Enter the number of Requests\n");
scanf("%d",&n);
printf("Enter the Requests sequence\n");
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
printf("Enter initial head position\n");
scanf("%d",&initial);
printf("Enter total disk size\n");
scanf("%d",&size);
printf("Enter the head movement direction for high 1 and for low 0\n");
scanf("%d",&move);

// logic for look disk scheduling

/*logic for sort the request array */


for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(RQ[j]>RQ[j+1])
{
int temp;
temp=RQ[j];
RQ[j]=RQ[j+1];
RQ[j+1]=temp;
}

}
}

int index;
for(i=0;i<n;i++)
{
if(initial<RQ[i])
{
index=i
; break;
}
}
// if movement is towards high value
if(move==1)
{
for(i=index;i<n;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial)
; initial=RQ[i];
}

for(i=index-1;i>=0;i--)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial)
; initial=RQ[i];

}
}
// if movement is towards low value
else
{
for(i=index-1;i>=0;i--)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial)
; initial=RQ[i];
}

for(i=index;i<n;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial)
; initial=RQ[i];

}
}

printf("Total head movement is %d",TotalHeadMoment);


return 0;
}

Output:
Enter the number of Request
8
Enter the Requests Sequence
95 180 34 119 11 123 62 64
Enter initial head position
50
Enter the head movement direction for high 1 and for low 0
1
Total head movement is 299

You might also like