0% found this document useful (0 votes)
16 views105 pages

Os Lab Record Final

The document is a practical record for B. Tech (IT) students at J. P. College of Engineering, detailing exercises in the Operating Systems Laboratory. It includes instructions for installing various operating systems like Ubuntu and Windows 10, as well as basic UNIX commands for file and directory management. The record also contains a bonafide certificate and an index for practical exercises conducted during the academic year 2024-25.

Uploaded by

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

Os Lab Record Final

The document is a practical record for B. Tech (IT) students at J. P. College of Engineering, detailing exercises in the Operating Systems Laboratory. It includes instructions for installing various operating systems like Ubuntu and Windows 10, as well as basic UNIX commands for file and directory management. The record also contains a bonafide certificate and an index for practical exercises conducted during the academic year 2024-25.

Uploaded by

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

J. P.

COLLEGE OF ENGINEERING
Ayikudy, Tenkasi-627852.

Department of Information Technology


PRACTICAL RECORD

Name:

Register Number:

Degree: B. Tech (IT)

Year/ Sem: II/IV

Subject Code: CS3461

Subject Name: OPERATING SYSTEMS LABORATORY


J. P. COLLEGE OF ENGINEERING
Ayikudy, Tenkasi-627852.

Department of Information Technology


PRACTICAL RECORD
BONAFIDE CERTIFICATE
Certified that this is the Bonafide record of Practical exercises done by
Register Number of II Year IV Semester
B. Tech IT in the CS3461 OPERATING SYSTEMS LABORATORY during the Academic Year 2024-25
(EVEN SEM).

Staff-in-charge Head of the Department

Certified that this record has been submitted for the practical examination held on
at J. P. COLLEGE OF ENGINEERING, Ayikudy conducted by Anna University, Chennai.

INTERNAL EXAMINER EXTERNAL EXAMINER


INDEX

Ex.No Date Experiment Name Page No Marks Staff


Signature
INDEX

Ex.No Date Experiment Name Page No Marks Staff


Signature
EX.NO :1 Case study on Installation of Windows Operating Systems
DATE :

AIM :
To perform a case study by installing and exploring various types of operating

systems on a physical or logical (virtual) machine. Such as Linux Installation and

windows installation.

I. Instructions to Install Ubuntu Linux 12.04 (LTS) along with windows:


Back Up Your Existing Data!
This is highly recommended that you should take backup of your entire data before start
with the installation process.
Obtaining System Installation Media
Download latest Desktop version of Ubuntu from this link:
http://www.ubuntu.com/download/desktop
1.Booting the Installation System
There are several ways to boot the installation system. Some of the very popular ways are ,
Booting from a CD ROM, Booting from a USB memory stick, and Booting from TFTP.
Here we will learn how to boot installation system using a CD ROM.
Before booting the installation system, one need to change the boot order and set CD-ROM
as first boot device.
Changing the Boot Order of a Computers
As your computer starts, press the DEL, ESC, F1, F2, F8 or F10 during the initial startup screen.
Depending on the BIOS manufacturer, a menu may appear. However, consult the hardware
documentation for the exact key strokes. In my machine, its DEL key as shown in following screen-
shot.

1
2. Find the Boot option in the setup utility. Its location depends on your BIOS.
Select the Boot option from the menu, you can now see the options Hard Drive, CD-ROM
Drive, Removable Devices Disk etc.

3. Change the boot sequence setting so that the CD-ROM is first. See the list of “Item Specific
Help” in right side of the window and find keys which is used to toggle to change the boot
sequence.

4. Insert the Ubuntu Disk in CD/DVD drive.


5. Save your changes. Instructions on the screen tell you how to save the changes on your
computer. The computer will restart with the changed settings.
Machine should boot from CD ROM, Wait for the CD to load...

In a few minutes installation wizard will be started. Select your language and click the
"Install Ubuntu" button to continue...

2
Optionally, you can choose to download updates while installing and/or install third party
software, such as MP3 support. Be aware, though, that if you select those options, the entire
installation process will be longer!

Since we are going to create partitions manually, select Something else, then click
Continue. Keep in mind that even if you do not want to create partitions manually, it is better to
select the same option as indicated here. This would insure that the installer will not overwrite your
Windows , which will destroy your data. The assumption here is that sdb will be used just for
Ubuntu 12.04, and that there are no valuable data on it.

3
Where are you? Select your location and Click the "Continue" button.

Keyboard layout
Select your keyboard layout and UK (English) and Click on “Continue” button.

Who are you?


Fill in the fields with your real name, the name of the computer (automatically generated,
but can be overwritten), username, and the password.
Also at this step, there's an option called "Log in automatically." If you check it, you will
automatically be logged in to the Ubuntu desktop without giving the password.
Option "Encrypt my home folder," will encrypt your home folder. Click on the "Continue"
button to continue...

4
Now Ubuntu 12.04 LTS (Precise Pangolin) operating system will be installed.

It will take approximately 10-12 minutes (depending on computer's speed), a pop-up


window will appear, notifying you that the installation is complete, and you'll need to restart the
computer in order to use the newly installed Ubuntu operating system. Click the "Restart Now"
button.

5
Please remove the CD and press the "Enter" key to reboot. The computer will be restarted.
In a few seconds, you should see Windows 7′s boot menu with two entires listed – Windows 7 and
Ubuntu 12.04 (LTS).
Then you may choose to boot into Windows 7 or Ubuntu 12.04 using the UP/Down arrow key.

Please select Ubuntu 12.04 (LTS) and press Enter to boot the machine in Ubuntu 12.04
Linux.

6
Here you can see the users on the machine, Click on the user name and enter the password and
press Enter key to login.

We have successfully install and login to Ubuntu 12.04 LTS.

7
ii. Procedure for Windows 10 installation :

Follow the steps below to proceed with the Windows 10 installation.


1. Select the following Language, Time, and Keyboard Layout and select“Next”.

2. Select “Install now” option.

8
3. Enter the product key to activate Windows and press “Next”, or press“Skip” to enter a valid
product key later.

4. Check the box next to “I accept the license terms” and select “Next”.

5. Choose the type of installation to perform.


- To upgrade to Windows 10 from an earlier version of Windows, select the “Upgrade”
option below.
- To perform a clean OS installation, select “Custom: Install Windows only (advanced)”option
below. For instructional purposes, this option was selected below.

9
6. Select the “Load driver” option to load the appropriate driver for the storagedevice.

7. Make sure to load the appropriate storage device driver onto a CD, DVD,or USB flash
drive before completing the next step.
- For storages devices attached to the Intel storage controller, load the Intel Rapid
Storage Technology enterprise (RSTe) driver.

o Select “Browse”, and browse to the CD, DVD, or USB flash drive to where
thestorage device driver is located and select “OK”.

10
[Type here]
- For storages devices attached to the Broadcom controller, load the Broadcom
storagedriver.

o Select “Browse”, browse to the CD, DVD, or USB flash drive to where
thestorage device driver is located and select “OK”.

8. Select the driver to install.

11

[Type here]
9. Select the drive to install Windows and select “Next” at the bottom.

10. Installing Windows screen.

11. After the installation completes, the system will automatically reboot. If noproduct key

was entered above, then it’ll prompt to enter a product key again. Either enter the
product key here and select “Next” or select “Do this later” at the bottom left.

12
12. Select “Use Express Settings” at the bottom right to use the default settings
or select “Customize settings” at the bottom left. For instructional
purposes, “Use Express settings” was selected.

13. Create an account by typing a “User name”. Optionally, type a password to


make it secure.

14. Windows 10 desktop screen.

13
15. At this point, download and install the appropriate device drivers,
i.e. Intel Chipset, Intel AMT, Ethernet, Graphics, etc.
16. Restart the system after installation.

RESULT :
The installation of the Windows Operating System was completed successfully.

14
EX.NO: 2 BASICS OF UNIX COMMANDS

DATE :

AIM :

To study and execute the commands in UNIX.

COMMANDS:
1. DIRECTORY RELATED COMMANDS :

a. MKDIR Command :

To create or make a new directory in a current directory .

Syntax : $mkdir <directory name>

b. Present Working Directory Command :

To print the complete path of the current working directory.

Syntax : $pwd

c.CD Command :

To change or move the directory to the mentioned directory .

Syntax : $cd <directory name>.

d.RMDIR Command :

To remove the current directory.

Syntax : $rmdir <directory name>

2. FILE RELATED COMMANDS :

a. CREATE A FILE :

To create a new file in the current directory we use CAT command.

Syntax :

$cat > <filename>.

The > symbol is redirect.

b.DISPLAY A FILE :

To display the content of file mentioned we use CAT command without „>‟ operator.
Syntax :
15
$cat <filename>.

Options –s = to neglect the warning /error message.

c.COPYING CONTENTS :

To copy the contents from source to destination file . so that both contents are same.

Syntax :

$cp <source filename> <destination filename>

$cp <source filename path > <destination filename path>

d.SORTING A FILE :

To sort the contents in alphabetical order in reverse order.

Syntax :

$sort <filename >

Option : $ sort –r <filename>

e.MOVE Command :

To completely move the contents from source file to destination file and to remove the

source file.

Syntax :

$ mv <source filename> <destination filename>

f.REMOVE Command :

To permanently remove the file we use this command .

Syntax :

$rm <filename>

16
3. LIST Command :

It is used to list all the contents in the current working directory.

Syntax : $ ls – options <arguments>

If the command does not contain any argument means it is working in the Current

directory.

Options :

a– used to list all the files including the hidden files. c–

list all the files columnwise.

d- list all the directories.

m- list the files separated by commas.

p- list files include „/‟ to all the directories.


r- list the files in reverse alphabetical order.

f- list the files based on the list modification date.x-

list in column wise sorted order.

4.WORD Command :

To list the content count of no of lines , words, characters .Syntax

$wc <filename>

Options :

-c – to display no of characters.

-l – to display only the lines.

-w – to display the no of words.

17
5.PAGE Command :

This command is used to display the contents of the file page wise & next page can beviewed

by pressing the enter key.

Syntax :

$pg <filename>

FILTERS AND PIPES

HEAD : It is used to display the top ten lines of file.

Syntax: $head<filename>

TAIL : This command is used to display the last ten lines of file.

Syntax: $tail<filename>

MORE : It also displays the file page by page .To continue scrolling with more command ,

press the space bar key.

Syntax: $more<filename>

7.GREP :This command is used to search and print the specified patterns from the file.

Syntax: $grep [option] pattern <filename>

8.SORT : This command is used to sort the datas in some order.

Syntax: $sort <filename>

9.PIPE : It is a mechanism by which the output of one command can be channeled into the
input

of another command.

Syntax: $who | wc-l

18
10. DATE Command :

This command is used to display the current data and time. Syntax :

$date

$date +%ch

Options : -

a = Abbrevated weekday.

A = Full weekday.

b = Abbrevated month.

B = Full month.

c = Current day and time.

C = Display the century as a decimal number. d

= Day of the month.

D = Day in „mm/dd/yy‟ format h


= Abbrevated month day.

H = Display the hour.

L = Day of the year.

m = Month of the year.

M = Minute.

P = Display AM or

PMS = Seconds

T = HH:MM:SS

format u = Week of the

year.

y = Display the year in 2 digit.

Y = Display the full year.

Z = Time zone .

To change the format :

19
Syntax :

$date „+%H-%M-%S‟

11. CALENDER Command:

This command is used to display the calendar of the year or the particular month of calendar
year.

Syntax:

$cal <year>

$cal <month> <year>


Here the first syntax gives the entire calendar for given year & the second Syntax gives

the calendar of reserved month of that year.

12.Echo Command :

This command is used to print the arguments on the screen .

Syntax : $echo <text>

Multi line echo command :

To have the output in the same line , the following commands can be used.

Syntax : $echo <text\>text

To have the output in different line, the following command can be used.

Syntax : $echo “text

>line2

>line3”

13. ’who’ Command :

It is used to display who are the users connected to our computer currently.

Syntax : $who – option

Options : -

20
H–Display the output with headers.

b–Display the last booting date or time or when the system was lastly rebooted.

14. ’who am i’ Command :

Display the details of the current working directory.

Syntax : $who am i

’tty’ Command :

It will display the terminal name.

Syntax : $tty

Binary’ Calculator Command :

This command is used to go to the binary calculator mode.

Syntax :

$bc operations

^d

’CLEAR’ Command :

It is used to clear the screen.

Syntax : $clear

’MAN’ Command :

It help us to know about the particular command and its options & working. It is like

“help” command in windows .

Syntax : $man <command name>

21
OUTPUT :
cal command:
[oscse18@localhost ~]$ cal
January 2011
Su Mo Tu We Th Fr
Sa1
234 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

Date command:
[oscse18@localhost ~]$ date
Wed Jan 12 10:32:11 IST 2011
[oscse18@localhost ~]$ date +%d
12
[oscse18@localhost ~]$ date +%m
01
[oscse18@localhost ~]$ date +%h
Jan
[oscse18@localhost ~]$ date +%y
11

Who command:
[oscse18@localhost ~]$ who root
:0 2011-01-12 09:55
oscse10 pts/6 2011-01-12 10:26 (192.168.0.52)
oscse09 pts/8 2011-01-12 10:27 (192.168.0.53)
oscse01 pts/11 2011-01-12 10:27 (192.168.0.56)
oscse08 pts/10 2011-01-12 10:27 (192.168.0.54)
oscse06 pts/4 2011-01-12 10:27 (192.168.0.60)
oscse03 pts/13 2011-01-12 10:27 (192.168.0.58)
oscse19 pts/3 2011-01-12 10:28 (192.168.0.46)

create a directory: [oscse18@localhost


~]$ mkdir muthu [oscse18@localhost ~]$
cd muthu Create a file:
[oscse18@localhost muthu]$ cat > stud
name
rollno
marks
grade
Display the file:
[oscse18@localhost muthu]$ cat stud
name
rollno
marks
grade
22
[oscse18@localhost muthu]$ cat > student
name
address
college
Copy the file from one to other:
[oscse18@localhost muthu]$ cp stud student
[oscse18@localhost muthu]$ cat student name
rollno
marks
grade
[oscse18@localhost muthu]$ cat > college
staff
students
nonteachstaff
Remove the file:
[oscse18@localhost muthu]$ rm college
[oscse18@localhost muthu]$ cat college cat:
college: No such file or directory

[oscse18@localhost muthu]$ cat > stud


usha geetha
ravi
ponmathi
wordcount command: [oscse18@localhost
muthu]$ wc -l stud3 stud
[oscse18@localhost muthu]$ wc -w stud
4 stud
[oscse18@localhost muthu]$ wc -c stud
26 stud
[oscse18@localhost muthu]$ cat > college
muthu usha
geetha

[oscse18@localhost muthu]$ cat > home


muthu
lakshmi
geetha
Different command:
[oscse18@localhost muthu]$ diff college home
1c1,2
< muthu usha
---
> muthu
> lakshmi
Listout the files:
[oscse18@localhost muthu]$ ls
college home stud student
[oscse18@localhost muthu]$ ls -a

23
. .. college home stud student
[oscse18@localhost muthu]$ ls -l
total 32
-rw-r--r-- 1 oscse18 oscse 18 Jan 12 11:40 college
-rw-r--r-- 1 oscse18 oscse 21 Jan 12 11:41 home
-rw-r--r-- 1 oscse18 oscse 26 Jan 12 11:31 stud
-rw-r--r-- 1 oscse18 oscse 24 Jan 12 11:11 student
[oscse18@localhost muthu]$ ls -r
student stud home college
Tail command:
[oscse18@localhost muthu]$ tail -2 student
marks
grade
Password command:
[oscse18@localhost muthu]$ pwd
/home/oscse18/muthu
Move command:
[oscse18@localhost muthu]$ mv college home
[oscse18@localhost muthu]$ cat home
muthu usha
geetha
[oscse18@localhost muthu]$ cat college
cat: college: No such file or directory
Grep command:
[oscse18@localhost muthu]$ grep -c ha home
2

RESULT:

Thus all the UNIX commands are executed and studied.

24
EX.NO: 3(A) SYSTEM CALLS OF UNIX OPERATING SYSTEMS

DATE :

AIM:
To write a program for system calls of UNIX operating systems (opendir, readdir, closedir)

ALGORITHM :
1. Start the program.
2. Create struct dirent.
3. Declare the variable buff and pointer dptr.
4. Get the directory name.
5. Open the directory.
6. Read the contents in directory and print it.
7. Close the directory.

PROGRAM:
#include<stdio.h>
#include<dirent.h>
struct dirent *dptr;
int main(int argc, char *argv[])
{
char buff[100];
DIR *dirp;
printf(“\n\n ENTER DIRECTORY NAME”);
scanf(“%s”, buff); if((dirp=opendir(buff))==NULL)
{
printf(“The given directory does not exist”);
exit(1);
}
while(dptr=readdir(dirp))
{
printf(“%s\n”,dptr->d_name);
}
closedir(dirp);
}

25
OUTPUT:
cc opdir.c
./a.out
Enter the directory name UNIT
Chap1.c
Chap2.c

RESULT:
Thus a program for system calls of UNIX operating systems (opendir, readdir, closedir) was
written and executed successfully.

26
EX.NO: 3(B) SYSTEM CALLS OF UNIX OPERATING SYSTEMS
DATE :

AIM:
To write a program for system calls of UNIX operating systems (fork, getpid, exit)
ALGORITHM:
1. Start the program.
2. Declare the variables pid, pid1, pid2.
3. Call fork() system call to create process.
4. If pid==-1, exit.
5. If pid!=-1 , get the process id using getpid().
6. Print the process id.
7. Stop the program
PROGRAM:
#include<stdio.h>
#include<unistd.h>
main()
{
int pid,pid1,pid2;
pid=fork();
if(pid==-1)
{
printf(“ERROR IN PROCESS CREATION \n”);
exit(1);
}
if(pid!=0)
{
pid1=getpid();
printf(“\n the parent process ID is %d\n”, pid1);
}
else
{
pid2=getpid();
printf(“\n the child process ID is %d\n”, pid2);
}}
OUTPUT:
cc fork.c
./a.out
The child process ID is 8640
The parent process ID is 8644

RESULT:
Thus a program for system calls of UNIX operating systems (fork, getpid, exit) waswritten
and executed successfully.
27
EX.NO: 3(C) SIMULATION OF LS UNIX COMMAND

DATE :

AIM:
To write a program for simulation of LS command.

ALGORITHM:
1. Start the program
2. Open the directory with directory object dp
3. Read the directory content and print it.
4. Close the directory.

PROGRAM:
#include<stdio.h>
#include<dirent.h> main(int
argc, char **argv)
{
DIR *dp;
struct dirent *link;
dp=opendir(argv[1]);
printf(“\n contents of the directory %s are \n”, argv[1]);
while((link=readdir(dp))!=0)
printf(“%s”,link->d_name);
closedir(dp);
}

OUTPUT:
cc list.c
./a.out OS
Contents of the directory OS are
Priority.c
Robin.c
copy

RESULT:

Thus a program for simulation of LS command was written and executed successfully.

28
EX.NO: 3(d) SIMULATION OF GREP UNIX COMMAND

DATE :

AIM:
To write a program for simulation of grep command.

ALGORITHM:
1. Start the program
2. Declare the variables fline[max], count=0, occurrences=0 and pointers *fp,
*newline.
3. Open the file in read mode.
4. In while loop check fgets(fline,max,fp)!=NULL
5. Increment count value.
6. Check newline=strchr(fline, „\n‟)
7. Print the count, fline value and increment the occurrence value.
8. Stop the program

PROGRAM:

#include<stdio.h>
#include<string.h>
#define max 1024
void usage()
{
printf(“usage:\t. /a.out filename word \n “);
}
int main(int argc, char *argv[])
{
FILE *fp;
char fline[max];
char *newline;
int count=0;
int occurrences=0;
if(argc!=3)
{
usage();
exit(1);
}
if(!(fp=fopen(argv[1],”r”)))
{
printf(“grep: couldnot open file : %s \n”,argv[1]);
exit(1);
}
while(fgets(fline,max,fp)!=NULL)
{
29
count++;
if(newline=strchr(fline, „\n‟))
*newline=‟\0‟;
if(strstr(fline,argv[2])!=NULL)
{
printf(“%s: %d %s \n”, argv[1],count, fline);
occurrences++;
}
}
}

OUTPUT:
CAT>SAMP
ONE
ONE TWO
THREE FOUR
cc grep.c
./a.out samp one
Samp: 1 one
Samp: 2 one two

RESULT:

Thus a program for simulation of grep command was written and executed
successfully.

30
EX.NO: 4(a) SHELL PROGRAM TO CHECK THE GIVEN NUMBER IS ODD OR EVEN

DATE :

AIM:
To write a shell program to check the given number is odd or even.
ALGORITHM:
1. Start the program.
2. Read the value of n.
3. Calculate “r=expr $n%2‟.
4. If the value of r equals 0 then print the number is even
5. If the value of r not equal to 0 then print the number is odd.

PROGRAM:

echo "Enter the Number"


read n
r=`expr $n % 2`
if [ $r -eq 0 ]
then
echo "$n is Even number"
else
echo "$n is Odd number"
fi

OUTPUT:
Enter the number 4
4 is Even number

RESULT:
Thus a shell program to check the given number is odd or even was written and
executed successfully.

31
EX.NO: 4(b) SHELL PROGRAM TO CHECK THE GIVEN YEAR IS LEAP YEAR OR NOT

DATE :

AIM:
To write a shell program to check the given year is leap year or not.
ALGORITHM:
1. Start the program.
2. Read the value of year.
3. Calculate “b=expr $y%4‟.
4. If the value of b equals 0 then print the year is a leap year
5. If the value of r is not equal to 0 then print the year is not a leap year.

PROGRAM:
echo "Enter the year"
read y
b=`expr $y % 4`
if [ $b -eq 0 ]
then
echo "$y is a leap year"
else
echo "$y is not a leap year"
fi

OUTPUT:
Enter the year 2004
2004 is a leap year

RESULT:
Thus a shell program to check the given year is leap year or not was written and
executed successfully.

32
EX.NO: 4(c) SHELL PROGRAM TO FIND THE FACTORIAL OF A NUMBER

DATE :

AIM:
To write a shell program to find the factorial of a number.

ALGORITHM:
1. Start the program.
2. Read the value of n.
3. Calculate “i=expr $n-1‟.
4. If the value of i is greater than 1 then calculate “n=expr $n \* $i‟ and “i=expr $i – 1‟
5. Print the factorial of the given number.

PROGRAM:

echo "Enter a Number"


read n
i=`expr $n - 1`
p=1
while [ $i -ge 1 ]
do
n=`expr $n \* $i`
i=`expr $i - 1`
done
echo "The Factorial of the given Number is $n"

OUTPUT:
Enter a number 5
The Factorial of the given Number is 120

RESULT:

Thus a shell program to find the factorial of a number was written and executed
successfully.

33
EX.NO: 4(d) SHELL PROGRAM TO SWAP THE TWO INTEGERS

DATE :

AIM:
To write a shell program to swap the two integers.

ALGORITHM:
1. Start the program.
2. Read the value of a,b.
3. Calculate the swapping of two values by using a temporary variable temp.
4. Print the value of a and b.

PROGRAM:
echo "Enter Two Numbers"
read a b
temp=$a
a=$b
b=$temp
echo "after swapping"
echo $a $b

OUTPUT:
Enter Two Numbers 10 20
After swapping 20 10

RESULT:

Thus a shell program to swap the two integers was written and executed successfully.

34
EX.NO: 5 SIMULATION OF CPU SCHEDULING ALGORITHMS
a) FCFS (First Come First Serve) b) SJF (Shortest Job First)
c) Priority d) Round Robin
DATE :

a) FCFS:
AIM:
A program to simulate the FCFS CPU scheduling algorithm
ALGORITHM :
1. Start the process
2. Get the number of processes to be inserted
3. Get the value for burst time of each process from the user
4. Having allocated the burst time(bt) for individual processes , Start with the first
process from it’s initial position let other process to be in queue
5. Calculate the waiting time(wt) and turn around time(tat) as
Wt(pi) = wt(pi-1) + tat(pi-1) (i.e wt of current process = wt of previous process + tatof
previous process)

tat(pi) = wt(pi) + bt(pi) (i.e tat of current process = wt of current process + bt of


current process)

6. Calculate the total and average waiting time and turn around time
7. Display the values
8. Stop the process
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
`char pn[10][10];
int arr[10],bur[10],star[10],finish[10],tat[10],wt[10],i,n; int
totwt=0,tottat=0;
clrscr();
printf("Enter the number of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Process Name, Arrival Time & Burst Time:");
scanf("%s%d%d",&pn[i],&arr[i],&bur[i]);
}
for(i=0;i<n;i++)
{
if(i==0)
{star[i]=arr[i]; wt[i]=star[i]-arr[i];

35
finish[i]=star[i]+bur[i];
tat[i]=finish[i]-arr[i];
}
else
{
star[i]=finish[i-1];
wt[i]=star[i]-arr[i];
finish[i]=star[i]+bur[i];
tat[i]=finish[i]-arr[i];
}
}
printf("\nPName Arrtime Burtime Start TAT Finish");
for(i=0;i<n;i++)
{
printf("\n%s\t%6d\t\t%6d\t%6d\t%6d\t%6d",pn[i],arr[i],bur[i],star[i],tat[i],finish[i]); totwt+=wt[i];
tottat+=tat[i];
}
printf("\nAverage Waiting time:%f",(float)totwt/n);
printf("\nAverage Turn Around Time:%f",(float)tottat/n); getch();
}
OUTPUT:
Enter the number of processes: 3
Enter the Process Name, Arrival Time & Burst Time: 1 2 3
Enter the Process Name, Arrival Time & Burst Time: 2 5 6
Enter the Process Name, Arrival Time & Burst Time: 3 6 7

PName Arrtime Burtime Srart TAT Finish


1 2 3 2 3 5
2 5 6 5 6 4
3 6 7 6 7 10
Average Waiting Time: 3.333
Average Turn Around Time: 7.000

36
b) SJF:
AIM:
A program to simulate the SJF CPU scheduling algorithm
ALGORITHM

1. Start the process


2. Get the number of processes to be inserted
3. Sort the processes according to the burst time and allocate the one with shortest burst to
execute first
4. If two process have same burst length then FCFS scheduling algorithm is used
5. Calculate the total and average waiting time and turn around time
6. Display the values
7. Stop the process
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int et[20],at[10],n,i,j,temp,st[10],ft[10],wt[10],ta[10]; int
totwt=0,totta=0;
float awt,ata;
char pn[10][10],t[10];
clrscr();
printf("Enter the number of process:"); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter process name, arrival time & execution time:");
flushall();
scanf("%s%d%d",pn[i],&at[i],&et[i]);
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(et[i]<et[j])
{
temp=at[i];
at[i]=at[j];
at[j]=temp;
temp=et[i];
et[i]=et[j];
et[j]=temp;
strcpy(t,pn[i]);
strcpy(pn[i],pn[j]);

37
strcpy(pn[j],t);
}
}
for(i=0;i<n;i++)
{
if(i==0)
st[i]=at[i];
else
st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
totwt+=wt[i]; totta+=ta[i];
}
awt=(float)totwt/n;
ata=(float)totta/n;
printf("\nPname\tarrivaltime\texecutiontime\twaitingtime\ttatime"); for(i=0;i<n;i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],wt[i],ta[i]); printf("\nAverage
waiting time is:%f",awt);
printf("\nAverage turnaroundtime is:%f",ata);
getch();
}
OUTPUT:
Enter the number of processes: 3
Enter the Process Name, Arrival Time & Burst Time: 1 4 6
Enter the Process Name, Arrival Time & Burst Time: 2 5 15
Enter the Process Name, Arrival Time & Burst Time: 3 6 11

Pname arrivaltime executiontime waitingtime tatime


1 4 6 0 6
3 6 11 4 15
2 5 15 16 31
Average Waiting Time: 6.6667
Average Turn Around Time: 17.3333

38
c) Priority:
AIM:
A program to simulate the priority CPU scheduling algorithm
ALGORITHM

1. Start the process


2. Get the number of processes to be inserted
3. Get the corresponding priority of processes
4. Sort the processes according to the priority and allocate the one with highest priority to
execute first
5. If two process have same priority then FCFS scheduling algorithm is used
6. Calculate the total and average waiting time and turn around time
7. Display the values
8. Stop the process
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int et[20],at[10],n,i,j,temp,p[10],st[10],ft[10],wt[10],ta[10]; int
totwt=0,totta=0;
float awt,ata;
char pn[10][10],t[10];
clrscr();
printf("Enter the number of process:"); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter process name,arrivaltime,execution time & priority:"); flushall();
scanf("%s%d%d%d",pn[i],&at[i],&et[i],&p[i]);
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(p[i]<p[j])
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
temp=at[i];
at[i]=at[j];
at[j]=temp;
temp=et[i];

39
et[i]=et[j];
et[j]=temp;
strcpy(t,pn[i]);
strcpy(pn[i],pn[j]);
strcpy(pn[j],t);
}
}
for(i=0;i<n;i++)
{
if(i==0)
{
st[i]=at[i];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
else
{
st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
totwt+=wt[i];
totta+=ta[i];
}
awt=(float)totwt/n;
ata=(float)totta/n;
printf("\nPname\tarrivaltime\texecutiontime\tpriority\twaitingtime\ttatime"); for(i=0;i<n;i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],p[i],wt[i],ta[i]); printf("\nAverage
waiting time is:%f",awt);
printf("\nAverage turnaroundtime is:%f",ata);
getch();
}

40
OUTPUT:
Enter the number of processes: 3
Enter the Process Name, Arrival Time, execution time & priority: 1 2 3 1
Enter the Process Name, Arrival Time, execution time & priority: 2 4 5 2
Enter the Process Name, Arrival Time, execution time & priority: 3 5 6 3

Pname AT ExeT priority WT tat

1 2 3 1 0 3
2 4 5 2 1 6
3 5 3 5 1 1
Average Waiting Time: 2.0000
Average Turn Around Time: 6.6667

41
d) Round Robin:
AIM:
A program to simulate the Round Robin CPU scheduling algorithm
ALGORITHM:

1. Start the process


2. Get the number of elements to be inserted
3. Get the value for burst time for individual processes
4. Get the value for time quantum
5. Make the CPU scheduler go around the ready queue allocating CPU to each processfor
the time interval specified

6. Make the CPU scheduler pick the first process and set time to interrupt after quantum. And
after it's expiry dispatch the process
7. If the process has burst time less than the time quantum then the process is released by the
CPU
8. If the process has burst time greater than time quantum then it is interrupted by the OS
and the process is put to the tail of ready queue and the schedule selects next process
from head of the queue
9. Calculate the total and average waiting time and turnaround time
10. Display the results

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int et[30],ts,n,i,x=0,tot=0;
char pn[10][10];
clrscr();
printf("Enter the no of processes:"); scanf("%d",&n);
printf("Enter the time quantum:"); scanf("%d",&ts);
for(i=0;i<n;i++)
{
printf("enter process name & estimated time:");
scanf("%s %d",pn[i],&et[i]);
}
printf("The processes are:");
for(i=0;i<n;i++)
printf("process %d: %s\n",i+1,pn[i]); for(i=0;i<n;i++)
tot=tot+et[i];
while(x!=tot)
{

42
for(i=0;i<n;i++)
{
if(et[i]>ts)
{
x=x+ts;
printf("\n %s -> %d",pn[i],ts);
et[i]=et[i]-ts;
}
else
if((et[i]<=ts)&&et[i]!=0)
{
x=x+et[i];
printf("\n %s -> %d",pn[i],et[i]);
et[i]=0;}
}}
printf("\n Total Estimated Time:%d",x);
getch();
}
OUTPUT:
Enter the no of processes: 2
Enter the time quantum: 3
Enter the process name & estimated time: p1 12
Enter the process name & estimated time: p2 15
Output:
p1 -> 3
p2 -> 3
p1 -> 3
p2 -> 3
p1 -> 3
p2 -> 3
p1 -> 3
p2 -> 3
p2 -> 3
Total Estimated Time: 27

Result :

Thus the following CPU scheduling program was written and the output was verified successfully.

a) FCFS (First Come First Serve)


b) SJF (Shortest Job First) c) Priority d) Round Robin

43
EX NO: 6 IMPLEMENTING SEMAPHORE FOR PRODUCER CONSUMER PROBLEM

DATE :

AIM:
To write a c-program to implement the producer – consumer problem using semaphores.

ALGORITHM:
1. Start the program.
2. Declare the required variables.
3. Initialize the buffer size and get maximum item you want to produce.
4. Get the option, which you want to do either producer, consumer or exit from the operation.
5. If you select the producer, check the buffer size if it is full the producer should not produce
the item or otherwise produce the item and increase the value buffer size.
6. If you select the consumer, check the buffer size if it is empty the consumer should not
consume the item or otherwise consume the item and decrease the value of buffer size.
7. If you select exit come out of the program.
8. Stop the program.

PROGRAM:
#include<stdio.h>
#include<conio.h>
int mutex=1,full=0,empty=3,x=0;main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.PRODUCER\n2.CONSUMER\n3.EXIT\n");while(1)
{
printf("\nENTER YOUR
CHOICE\n"); scanf("%d",&n);
switch(n)
{
case 1:
if((mutex==1)&&(empty!=0))
producer();

44
else
printf("BUFFER IS FULL");
break;
case 2:
if((mutex==1)&&(full!=0))
consumer();
else
printf("BUFFER IS EMPTY");
break;
case 3:
exit(0);
break;
}
}
}
int wait(int s)
{
return(--s);
}
int signal(int s)
{
return(++s);
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\nproducer produces the item%d",x);
mutex=signal(mutex);

45
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\n consumer consumes item%d",x);x--;
}
OUTPUT:-
1. PRODUCER

2. CONSUMER

3. EXIT

ENTER YOUR CHOICE: 1


producer produces the item1

ENTER YOUR
:C1HOICE
producer produces the
item2

ENTER YOUR CHOICE:1


producer produces the
item3ENTER YOUR CHOICE
: 1 BUFFER IS FULL
ENTER YOUR CHOICE : 2
consumer consumes
item3ENTER YOUR
CHOICE : 2
consumer consumes
item2ENTER YOUR
CHOICE : 2
consumer consumes item1
ENTER YOUR CHOICE: 2 BUFFER IS EMPTY

RESULT:

Thus the C Program to implement the producer – consumer problem using


semaphores was written and the output was verified successfully.
46
EX.NO:7 INTER PROCESS COMMUNICATION

DATE :

AIM
To developing Application using Inter Process communication (using shared memory, pipes or
message queues)

ALGORITHM

1 . St art t h e p rogr a m.
2. Read the input from parent process and perform in child process.
3. Write the date in parent process and read it in child process.
4. Fibonacci Series was performed in child process. 5 .
Stoptheprogram.

//Implementation of Shared memory and Inter Process Communication


Client-server program
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
int main()
{
struct msgbuf
{
long mtype;
char a[100];
};
struct msgbuf *p;
int i,n,j,flag=0,flag1=0,id,l,count,f=0;
p=(struct msgbuf*)malloc(sizeof(struct msgbuf));
printf("Waiting for clients queries..\n");
id=msgget((key_t)4066,0733|IPC_CREAT|IPC_EXCL);
if(id==-1)
{
perror("error");
47
}
while(1)
{
msgrcv(id,p,601,0,0);
if(p->mtype==1)
{
if((strcmp(p->a,"quit"))!=0)
{
printf("%s",p->a);
l=strlen(p->a);
for(i=l-1,j=0;i>=0;i--,j++)
{
if(p->a[i]==p->a[j])
f=1;
else
f=2;
}
if(f==1)
printf("\n The string is a palindrome \n");
else
printf("\n The string is not a palindrome \n");
}
else
flag=1;
}
if(p->mtype==2)
{
if((strcmp(p->a,"quit"))!=0)
{
printf("%s\n",p->a);
n=strlen(p->a);
count=0;
for(i=0;i<n;i++)
{

48
if(p->a[i]=='a'||p->a[i]=='e'||p->a[i]=='i'||p->a[i]=='o'||p->a[i]=='u')
{
count=count+1;
}
}
printf("The number of vowels in the string is %d \n",count);
}
else
flag1=1;
}
if((flag==1)&&(flag1==1))
break; }
msgctl(id,IPC_RMID,NULL);
}

Client1:
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
struct msgbuf
{
long mtype;
char a[100];
};
struct msgbuf *p;
int main()
{
int id;
id=msgget((key_t)4066,0733);
p=(struct msgbuf *)malloc(sizeof(struct msgbuf)); do
{

49
printf("Enter the string:\n");
printf("Type quit for exit:\n");
scanf("%s",p->a);
p->mtype=1;
msgsnd(id,p,601,0);
}
while(strcmp(p->a,"quit")!=0);
}

Client2:
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h> struct
msgbuf
{
long mtype;
char a[100];
};
struct msgbuf *p;
int main()
{
int id;
id=msgget((key_t)4066,0733);
p=(struct msgbuf *)malloc(sizeof(struct msgbuf)); do
{
printf("Enter the string \n");
printf("Type quit 4r exit \n");
scanf("%s",p->a);
p- >mtype=2; msgsnd(id,p,601,0);
}
while(strcmp(p->a,"quit")!=0);

50
}
OUTPUT:
Server: waiting for client queries……..
Client1:enter the string
Type quit for exit
Madam
Server: the string is palindrome
Client2: enter the string
Type quit for exit
Computer
Server:
The no.of vowels in the string is 3

RESULT

Thus the C Program To developing Application using Inter Process


communication (using shared memory, pipes or message queues) was written and the
output was verified successfully.

51
Ex.No : 8 . BANKERS ALGORITHM FOR DEADLOCK AVOIDANCE

DATE :
.

AIM:
A program to simulate the Bankers Algorithm for Deadlock Avoidance

.ALGORITHM:
1. Start the program.

2. Get the values of resources and processes.

3. Get the avail value.

4. After allocation find the need value.

5. Check whether its possible to allocate.

6. If it is possible then the system is in safe state.

Else system is not in safety state.

7. If the new request comes then check that the system is in safety. Or
not if we allow the request.

8. Stop the process.

PROGRAM:

#include<stdio.h>

int main() {

/* array will store at most 5 process with 3 resoures if your process or

resources is greater than 5 and 3 then increase the size of array */

int p, c, count = 0, i, j, alc[5][3], max[5][3], need[5][3], safe[5], available[3], done[5], terminate = 0;

printf("Enter the number of process and resources");

scanf("%d %d", & p, & c);

// p is process and c is diffrent resources

printf("enter allocation of resource of all process %dx%d matrix", p, c);

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

for (j = 0; j < c; j++) {


52
scanf("%d", & alc[i][j]);

printf("enter the max resource process required %dx%d matrix", p, c);

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

for (j = 0; j < c; j++) {

scanf("%d", & max[i][j]);

printf("enter the available resource");

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

scanf("%d", & available[i]);

printf("\n need resources matrix are\n");

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

for (j = 0; j < c; j++) {

need[i][j] = max[i][j] - alc[i][j];

printf("%d\t", need[i][j]);

printf("\n");

/* once process execute variable done will stop them for again execution */

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

done[i] = 0;

while (count < p) {

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

if (done[i] == 0) {

53
for (j = 0; j < c; j++) {

if (need[i][j] > available[j])

break;

//when need matrix is not greater then available matrix then if j==c will true

if (j == c) {

safe[count] = i;

done[i] = 1;

/* now process get execute release the resources and add them in available resources */

for (j = 0; j < c; j++) {

available[j] += alc[i][j];

count++;

terminate = 0;

} else {

terminate++;

if (terminate == (p - 1)) {

printf("safe sequence does not exist");

break;

if (terminate != (p - 1)) {

printf("\n available resource after completion\n");

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

54
printf("%d\t", available[i]);

printf("\n safe sequence are\n");

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

printf("p%d\t", safe[i]);

} }

return 0;

OUTPUT :

Enter the number of process and resources

5 3

enter allocation of resource of all process 5x3 matrix

010

200

302

211

002

enter the max resource process required 5x3 matrix

753

322

902

422

533

enter the available resource 3 3 2

need resources matrix are

7 4 3

1 2 2

6 0 0

55
2 1 1

5 3 1

available resource after completion

10 5 7

safe sequence are

p1 p3 p4 p0 p2

RESULT:

Thus a program to simulate Bankers Algorithm for Deadlock Avoidance was written and
output was verified successfully.

56
EX.NO:9 BANKERS ALGORITHM FOR DEADLOCK PREVENTION.

DATE :

AIM:
A program to simulate Bankers Algorithm for Deadlock Prevention.
ALGORITHM:
1. Start the program
2. Attacking Mutex condition: never grant exclusive access. But this may not be possible for
several resources.
3. Attacking preemption: not something you want to do.
4. Attacking hold and wait condition: make a process hold at the most 1 resource
5. At a time. Make all the requests at the beginning. Nothing policy. If you feel, retry.
6. Attacking circular wait: Order all the resources. Make sure that the requests are issued in the
7. Correct order so that there are no cycles present in the resource graph. Resources
numbered 1 ... n.
8. Resources can be requested only in increasing
9. Order. i.e. you cannot request a resource whose no is less than any you may be holding.
10. Stop the program
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int cl[10][10],al[10][10],av[10],i,j,k,m,n,ne[10][10],flag=0; clrscr();
printf("\nEnter the matrix");
scanf("%d %d",&m,&n);
printf("\nEnter the claim matrix:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&cl[i][j]);
}
}

57
printf("\nEnter allocated matrix:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&al[i][j]);
}
}
printf("\nThe need matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
ne[i][j]=cl[i][j]-al[i][j];
printf("\t%d",ne[i][j]);
}
printf("\n");
}
printf("\nEnter avaliable matrix");
for(i=0;i<n;i++)
scanf("%d",&av[i]);
printf("Claim matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%d",cl[i][j]);
}
printf("\n");
}
printf("\n Allocated matrix:\n");
for(i=0;i<m;i++)
{

58
for(j=0;j<n;j++)
{
printf("\t%d",al[i][j]);
}
printf("\n");
}
printf("Available matrix:\n");
for(i=0;i<n;i++)
{
printf("%d\t",av[i]);
}
//for(k=0;k<m;k++)
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(av[j]>=ne[i][j])
flag=1;
else
flag=0;
}
}
if(flag==0)
printf("Unsafe State");
else
printf("Safe State");
getch();
}

59
OUTPUT:
Input:
Enter the claim matrix:3 2 2 6 1 3 3 1 4 4 2 2
Enter allocated matrix:1 0 0 5 1 1 2 1 1 0 0 2
The need matrix:
222
102
103
420
Enter available matrix1 1 2
Output:
Claim matrix:
322
613
314
422
Allocated matrix:
100
511
211
002
Available matrix:
1 1 2 Safe State

RESULT

Thus a program to simulate Bankers Algorithm for Deadlock Prevention was written and
output was verified successfully.

60
E X.NO :10 Implementation of Threading concept
DATE :

AIM :
To write and execute C programs that demonstrate various thread-related concepts using the POSIX
thread (pthreads) library, including thread creation, joining and passing data to threads.
ALGORITHM:

Step 1 :Define a thread function (printNumber) that prints the thread index.

Step 2 :In main(), create an array of 5 threads and arguments.

Step 3 :For each thread:

1. Assign an index.
2. Create the thread and pass the index.

Step 4 :Join all threads to ensure completion before program exits.

PROGRAM :

#include <stdio.h>
#include <pthread.h>
void* threadFunction(void* arg) {
int id = *(int*)arg;
printf("Thread %d is running.\n", id);
return NULL;
}
int main() {
pthread_t threads[5];
int ids[5];

for (int i = 0; i < 5; i++) {


ids[i] = i + 1;
pthread_create(&threads[i], NULL, threadFunction, &ids[i]);
}

for (int i = 0; i < 5; i++) {


pthread_join(threads[i], NULL);
}
return 0;
}
OUTPUT:
Thread 1 is running.
Thread 3 is running.
Thread 2 is running.
Thread 4 is running.
Thread 5 is running.
RESULT :
Thus the C program for thread related concept were written , executed and output was verified
Successfully.
61
EX.NO: 11 IMPLEMENTATION OF MEMORY ALLOCATION
METHODS FORFIXED PARTITION
a) First Fit b) Best Fit c) Worst Fit
DATE :

A. First Fit Allocation


AIM:
To allocate memory requirements for processes using first fit allocation.

ALGORITHM:
1. Declare structures hole and process to hold information about set of holes and
processes respectively.
Get number of holes, say nh.
Get the size of each hole
Get number of processes, say np.
Get the memory requirements for each process.
Allocate processes to holes, by examining each hole as follows:
If hole size > process size then
Mark process as allocated to that hole.
Decrement hole size by process size.
Otherwise check the next from the set of hole
Print the list of process and their allocated holes or unallocated status.
Print the list of holes, their actual and current availability.
Stop
PROGRAM:

/* First fit allocation - ffit.c */

#include <stdio.h>

structprocess

int size; int flag; int


holeid;
} p[10];
struct hole

int size; int actual;


} h[10];

main()

int i, np, nh,j;

printf("Enter the number of Holes:"); scanf("%d", &nh);


for(i=0; i<nh; i++)
{
printf("Enter sizefor hole H%d :",i); scanf("%d", &h[i].size);
h[i].actual = h[i].size;

62
}
printf("\nEnternumber of process:"); scanf("%d",&np);
for(i=0;i<np;i++)
{
printf("enter the size of process P%d :",i); scanf("%d", &p[i].size); p[i].flag
= 0;
}
for(i=0; i<np; i++)
{
for(j=0; j<nh; j++)
{
if(p[i].flag != 1)
{
if(p[i].size <=h[j].size)
{
p[i].flag = 1; p[i].holeid = j; h[j].size -=
p[i].size;
}
}
}
}

printf("\n\tFirst Fit\n"); printf("\nProcess\tPSize\tHole");


for(i=0; i<np; i++)
{
if(p[i].flag != 1) printf("\nP%d\t%d\tNotallocated",i,p[i].size);
else printf("\nP%d\t%d\tH%d", i, p[i].size,p[i].holeid);
}

printf("\n\nHole\tActual\tAvailable"); for(i=0; i<nh ;i++)


printf("\nH%d\t%d\t%d",i,h[i].actual,h[i].size); printf("\n");
}

OUTPUT:

$ gcc ffit.c

$ ./a.out
Enter the number of Holes :5
Enter size for hole H0 : 100
Enter size for hole H1 : 500
Enter size for hole H2 : 200
Enter size for hole H3 : 300
Enter size for hole H4 :600

Enter number of process : 4


enter the size of process P0 : 212 enter the size of
process P1 : 417 enter the size of process P2 : 112
enterthe sizeof process P3 : 426
First Fit
Process PSize Hole
P0 212 H1
63
P1 417 H4
P2 112 H1
P3 426 Not allocated

Hole Actual Available


H0 100 100
H1 500 176
H2 200 200
H3 300 300
H4 600 183

B. BEST FIT ALLOCATION


AIM:
To allocate memory requirements for processes using best fit allocation.

ALGORITHM:

Step 1: Read the number of memory blocks n and their sizes.

 Read the number of processes m and their sizes.

Step 2: Initialize Mark all memory blocks as free initially.

Step 3: Allocation (Main Logic)

For each process:

1. Search all free memory blocks.

2. Find the block with the smallest size that is big enough to fit the process (i.e., minimal wastage).

3. If such a block is found:

o Allocate the process to that block.

o Mark the block as occupied (or reduce its available size accordingly).

4. If no suitable block is found:

o Mark the process as not allocated.

Step 4: Display which process is allocated to which block .

PROGRAM:
#include <stdio.h>

int main() {
int blockSize[20], processSize[20], blockCount, processCount;
int allocation[20];

// Input number of blocks and processes


printf("Enter the number of memory blocks: ");
scanf("%d", &blockCount);

64
printf("Enter the size of each memory block:\n");
for (int i = 0; i < blockCount; i++) {
printf("Block %d: ", i + 1);
scanf("%d", &blockSize[i]);
}

printf("\nEnter the number of processes: ");


scanf("%d", &processCount);

printf("Enter the size of each process:\n");


for (int i = 0; i < processCount; i++) {
printf("Process %d: ", i + 1);
scanf("%d", &processSize[i]);
allocation[i] = -1; // Initialize allocation array to -1 (not allocated)
}

// Best Fit Allocation


for (int i = 0; i < processCount; i++) {
int bestIndex = -1;
for (int j = 0; j < blockCount; j++) {
if (blockSize[j] >= processSize[i]) {
if (bestIndex == -1 || blockSize[j] < blockSize[bestIndex]) {
bestIndex = j;
}
}
}
if (bestIndex != -1) {
allocation[i] = bestIndex;
blockSize[bestIndex] -= processSize[i]; // Reduce available memory
}
}

// Display allocation result


printf("\nProcess No.\tProcess Size\tBlock No.\n");
for (int i = 0; i < processCount; i++) {
printf("%d\t\t%d\t\t", i + 1, processSize[i]);
if (allocation[i] != -1)
printf("%d\n", allocation[i] + 1); // +1 because array index starts from 0
else
printf("Not Allocated\n");
}

return 0;
}

C) WORST FIT ALLOCATION

AIM :
To allocate memory requirements for processes using w o r s t fit allocation.

ALGORITHM:

65
1. Start the program.

2. Initialize arrays such as

o b[] for block sizes,

o f[] for file sizes,

o frag[] for fragmentation sizes,

o bf[] and ff[] as helper arrays to track block usage.

3. Input to the program.

o Number of blocks (nb),

o Number of files (nf),

o Sizes of each block,

o Sizes of each file.

4. For each file (i = 1 to nf):

o Find the worst fit block:

 For each block (j = 1 to nb):

 If block j is not already allocated (bf[j] != 1):

 Calculate temp = b[j] - f[i].

 If temp >= 0 (block can accommodate file):

 Select this block (store block number j in ff[i]).

 Break out of loop.

o Update fragmentation:

 frag[i] = temp (space left after placing file).

o Mark block as allocated:

 bf[ff[i]] = 1.

5. Display the allocation results:

o For each file, print:

 File number,

 File size,

 Allocated block number,

 Block size,

 Internal fragmentation.

66
6. End the program.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
clrscr();
printf("\n\tMemory Management Scheme - worst Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j;
break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

OUTPUT:

Enter the number of blocks: 3


Enter the number of files: 2

67
Enter the size of the blocks:-
Block 1: 5
Block 2: 2
Block 3: 7

Enter the size of the files:-


File 1: 1
File 2: 4

File No File Size Block No Block Size Fragment


1 1 1 5 4
2 4 3 7 3

RESULT:

Thus a program to simulate memory allocation scheme was written and output was verified
successfully.

68
EX.NO: 12 IMPLEMENT PAGING TECHNIQUE OF MEMORY MANAGEMENT
Date :

AIM:
A program to simulate Paging technique of memory management.

ALGORITHM:
Step 1: Read all the necessary input from the keyboard.
Step 2: Pages - Logical memory is broken into fixed - sized blocks. Step
3: Frames – Physical memory is broken into fixed – sized blocks. Step 4:
Calculate the physical address using the following
Physical address = ( Frame number * Frame size ) + offset
Step 5: Display the physical address.
Step 6: Stop the process.

PROGRAM:
#include<stdio.h>
#include<conio.h>
main()
{
int np,ps,i;
int *sa;
clrscr();
printf("Enter how many pages\n");
scanf("%d",&np);
printf("Enter the page size \n");
scanf("%d",&ps); for(i=0;i<np;i++)
{
sa[i]=(int)malloc(ps);
printf("Page%d\t Address %u\n",i+1,sa[i]);
}
getch();
}
OUTPUT:
Enter how many pages: 5
Enter the page size: 4
Page1 Address: 1894
Page2 Address: 1902
Page3 Address: 1910
Page4 Address: 1918
Page5 Address: 1926
RESULT:

Thus the program to simulate Paging technique of memory management was written and the output was
verified successfully.
69
Ex.No:13 SIMULATE PAGE REPLACEMENT ALGORITHMS
Date:

a) FIFO: (First In First out Page Replacement Algorithm)


AIM:

A program to simulate FIFO Page Replacement Algorithm

ALGORITHM:
Step 1: create a queue to hold all pages in memory

Step 2: when the page is required replace the page at the head of the queue

Step 3: now the new page is inserted at the tail of the queue

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],b[20],n,p=0,q=0,m=0,h,k,i,q1=1;
char f='F';
clrscr();
printf("Enter the Number of Pages:");
scanf("%d",&n);
printf("Enter %d Page Numbers:",n);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<n;i++)
{if(p==0)
{
if(q>=3)
q=0;
a[q]=b[i];
q++;
if(q1<3)
{
q1=q;
70
}
}
printf("\n%d",b[i]);
printf("\t");
for(h=0;h<q1;h++)
printf("%d",a[h]);
if((p==0)&&(q<=3))
{
printf("-->%c",f);
m++;
}
p=0;
for(k=0;k<q1;k++)
{
if(b[i+1]==a[k])
p=1;
}
}
printf("\nNo of faults:%d",m);
getch();
}
OUTPUT:
Input:
Enter the Number of Pages: 12
Enter 12 Page Numbers:
232152453252
Output:
2 2-> F
3 23-> F
2 23
1 231-> F
5 531-> F
2 521-> F
4 524-> F
5 524
71
3 324-> F
2 324
5 354-> F
2 352-> F
No of faults: 9

b) LRU: (Last Recently Used Page Replacement Algorithm)

AIM:
A program to simulate LRU Page Replacement Algorithm

ALGORITHM:
Step 1: Create a queue to hold all pages in memory

Step 2: When the page is required replace the page at the head of the queue

Step 3: Now the new page is inserted at the tail of the queue

Step 4: Create a stack

Step 5: When the page fault occurs replace page present at the bottom of the stack

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

void main()
{
int
g=0,a[5],b[20],p=0,q=0,m=0,h,k,i,q1=1,j,u,n;
char f='F';
clrscr();
printf("Enter the number of pages:");
scanf("%d",&n);
printf("Enter %d Page Numbers:",n);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<n;i++)
{if(p==0)
{

72
if(q>=
3)
q=0;
a[q]=b[
i]; q++;
if(q1<3)
{
q1=q;
}}
printf("\n%d",b[i]);
printf("\t");
for(h=0;h<q1;h++)
printf("%d",a[h]);
if((p==0)&&(q<=3))
{
printf("-->%c",f);
m++;
}
p=
0;
g=
0;
if(q1==3)
{
for(k=0;k<q1;k++)
{
if(b[i+1]==a[k]) p=1;
}
for(j=0;j<q1;j++)
{
u=
0;
k=i;
while(k>=(i-1)&&(k>=0))
{
73
if(b[k]==a[j])
u++; k--;}
if(u==0)
q=j;
}}
else {
for(k=0;k<q;k++)
{
if(b[i+1]==a[k
]) p=1;
} }}
printf("\nNo of faults:%d",m);
getch();}

OUTPUT:
Enter the Number of Pages:
12

Enter 12 Page Numbers:


232152453252
2 2-> F
3 23-> F
2 23
1 231-> F
5 251-> F
2 251
4 254-> F
5 254
3 354-> F
2 352-> F
5 352
2 352
No of faults: 7
RESULT:
Thus a program to simulate Page Replacement Algorithms was written and output was verified successfully.

74
EX.NO :14 IMPLEMENTATION OF THE VARIOUS FILE ORGANIZATION TECHNIQUES
DA T E:

AIM:
Write a C program to simulate the following file organization techniques. Such as
a) Single level directory b) Two level directory c) Hierarchical

a)Single level directory organization

ALGORITHM :
1. Start the program.
2. Define a structure directory containing:
o fname (file name),
o dname (directory name).
3. Initialize:
o Array dir[] of structure type to store files and directory,
o Variables count, ch, f[], d[].
4. Display a menu repeatedly (inside a while(1) infinite loop):
5. Take user's choice (ch) as input.
6. Perform operations based on user's choice:
o Case 1: Create Directory
 If no directory exists (count == 0), ask for directory name and create it.
 Else, display that directory already exists.
o Case 2: Create File
 If directory doesn't exist, prompt to create directory first.
 Else, ask for file name and add it under the directory.
 Increment count.
o Case 3: Delete File
 If no files exist, display message.
 Else, ask for file name to delete.
 Search through existing files.
 If found, remove (empty the name).
 Else, show "file not found."
o Case 4: Search File
 If no files exist, show message.
 Else, search for given file name.
 If found, display message.
 Else, show "file not found."
o Case 5: Display Directory
 If no directory exists, show message.
 Else, print directory name and list all files created.
o Case 6: Exit
 Exit the program.

75
7. Repeat the process until user selects Exit.

PROGRAM:
#include <stdio.h>
#include <string.h>
struct directory
{
char fname[10];
char dname[10];
} dir[10];

void main()
{
int i, ch, count = 0;
char f[10];
char d[10];

printf("\nSingle Level Directory Implementation\n");

while (1)
{
printf("\n1. Create Directory\n2. Create File\n3. Delete File\n4. Search File\n5. Display Directory\n6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);

switch (ch)
{
case 1:
if (count == 0) {
printf("Enter name of directory: ");
scanf("%s", dir[count].dname);
printf("Directory created.\n");
} else {
printf("Directory already exists!\n");
}
break;

case 2:
if (count == 0) {
printf("No directory found. Create a directory first.\n");
} else {
printf("Enter file name: ");
scanf("%s", dir[count].fname);
printf("File created.\n");
count++;
}

76
break;

case 3:
if (count == 0) {
printf("No files to delete.\n");
} else {
printf("Enter file name to delete: ");
scanf("%s", f);
for (i = 1; i < count; i++) {
if (strcmp(f, dir[i].fname) == 0) {
printf("File %s deleted.\n", f);
strcpy(dir[i].fname, ""); // delete file
break;
}
}
if (i == count)
printf("File not found.\n");
}
break;

case 4:
if (count == 0) {
printf("No files to search.\n");
} else {
printf("Enter file name to search: ");
scanf("%s", f);
for (i = 1; i < count; i++) {
if (strcmp(f, dir[i].fname) == 0) {
printf("File %s found.\n", f);
break;
}
}
if (i == count)
printf("File not found.\n");
}
break;

case 5:
if (count == 0) {
printf("No directory and files to display.\n");
} else {
printf("\nDirectory name: %s\n", dir[0].dname);
printf("Files:\n");
for (i = 1; i < count; i++) {
if (strcmp(dir[i].fname, "") != 0)
printf("%s\n", dir[i].fname);

77
}
}
break;

case 6:
printf("Exiting...\n");
return;

default:
printf("Invalid choice!\n");
}
}
}

OUTPUT:
Single Level Directory Implementation
1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 1
Enter name of directory: mydir
Directory created.

1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 2
Enter file name: file1
File created.

1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 2
78
Enter file name: file2
File created.

1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 5

Directory name: mydir


Files:
file1
file2

1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 4
Enter file name to search: file1
File file1 found.

1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 3
Enter file name to delete: file2
File file2 deleted.

1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory

79
6. Exit
Enter your choice: 5

Directory name: mydir


Files:
file1

1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 6
Exiting...

B) Two level directory organization

ALGORITHM:
Step1: Create Root Directory:
o Use the mkdir("root", 0755) function to create a root directory named root.
o Check if the directory creation is successful. If it fails, print an error and terminate the program.
Step 2:Create Subdirectories Inside Root:
o Use the mkdir("root/subdir1", 0755) function to create a subdirectory named subdir1 inside the
root directory.
o Use the mkdir("root/subdir2", 0755) function to create another subdirectory named subdir2
inside the root directory.
o Check if each directory creation is successful. If either fails, print an error and terminate the
program.
Step3:Create Files Inside Subdirectories:
o Open file1.txt inside subdir1 using fopen("root/subdir1/file1.txt", "w"). Write some content to
the file and close it.
o Open file2.txt inside subdir2 using fopen("root/subdir2/file2.txt", "w"). Write some content to
the file and close it.
o If file creation or writing fails, print an error and terminate the program.
Step4:List Contents of Root Directory:
o Use opendir("root") to open the root directory.
o Use readdir() in a loop to read and print the entries inside the root directory (including subdir1,
subdir2, and the . and .. entries).
o Close the root directory using closedir().
Step5:List Contents of Subdirectory 1:
o Use opendir("root/subdir1") to open the subdir1 directory.
o Use readdir() in a loop to read and print the entries inside subdir1 (including file1.txt and the .
and .. entries).
o Close subdir1 using closedir().
Step6:List Contents of Subdirectory 2:
o Use opendir("root/subdir2") to open the subdir2 directory.
o Use readdir() in a loop to read and print the entries inside subdir2 (including file2.txt and the .
80
and .. entries).
o Close subdir2 using closedir().
Step7: End Program:

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

void createDirectories() {
// Create a root directory
if (mkdir("root", 0755) == -1) {
perror("Error creating root directory");
exit(1);
}

// Create subdirectories within the root directory


if (mkdir("root/subdir1", 0755) == -1) {
perror("Error creating subdir1");
exit(1);
}

if (mkdir("root/subdir2", 0755) == -1) {


perror("Error creating subdir2");
exit(1);
}

printf("Directories created successfully.\n");


}

void listDirectories() {
DIR *d;
struct dirent *dir;

// Open the root directory


d = opendir("root");
if (d) {
printf("Contents of root directory:\n");
// Read and print the contents of the root directory
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
} else {
perror("Error opening root directory");
}

// List contents of subdirectories


char subdirPath[256];
81
// List subdir1
snprintf(subdirPath, sizeof(subdirPath), "root/subdir1");
d = opendir(subdirPath);
if (d) {
printf("\nContents of subdir1:\n");
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
} else {
perror("Error opening subdir1");
}

// List subdir2
snprintf(subdirPath, sizeof(subdirPath), "root/subdir2");
d = opendir(subdirPath);
if (d) {
printf("\nContents of subdir2:\n");
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
} else {
perror("Error opening subdir2");
}
}

int main() {
// Create the two-level directory structure
createDirectories();

// List the directories and their contents


listDirectories();

return 0;
}

OUTPUT:
Directories and files created successfully.

Contents of root:
.
..
subdir1
subdir2
Contents of root/subdir1:
.
82
..
file1.txt

Contents of root/subdir2:
.
..
file2.txt

c) hierarchical directory organization

ALGORITHM:
Step 1: Define Structures
 Define a structure File to store file names.
 Define a structure Directory to store:
o Directory name,
o Array of files,
o Array of subdirectories,
o File count and subdirectory count.
Step 2: Create Root Directory
 Allocate memory dynamically (malloc) for the root directory.
 Initialize:
o Name of root ("root"),
o Set file count = 0,
o Set subdirectory count = 0.
Step 3: Create Subdirectories and Files
 Create Directory Function:
o Take a parent directory and a directory name.
o Allocate memory for a new directory.
o Copy the name into the new directory.
o Set its file count and subdirectory count to 0.
o Attach this new directory to the parent's subdirectory list.
 Create File Function:
o Take a directory and file name.
o Add the file to the directory’s file list.
o Increase the file count by 1.
Step 4: Build Hierarchy
 Using createDirectory() and createFile() functions:
o Create subdirectories and files under the root and further under subdirectories.
o Example:
 Create subdir1 inside root.
 Create subsubdir1 inside subdir1.
 Create files at different levels.
Step 5: Display the Directory Structure
o Print the current directory’s name.
o For each file inside the directory:
 Print the file name with appropriate indentation.
o For each subdirectory inside the directory:
 Recursively call the display function, increasing the indentation.
Step 6: End Program

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

struct File {
char name[50];
};

struct Directory {
char name[50];
struct File files[10];
int fileCount;
struct Directory *subDirs[10];
int subDirCount;
};

void createDirectory(struct Directory *parent, char *name) {


struct Directory *newDir = (struct Directory *)malloc(sizeof(struct Directory));
strcpy(newDir->name, name);
newDir->fileCount = 0;
newDir->subDirCount = 0;
parent->subDirs[parent->subDirCount++] = newDir;
}

void createFile(struct Directory *dir, char *name) {


strcpy(dir->files[dir->fileCount++].name, name);
}

void display(struct Directory *dir, int depth) {


for (int i = 0; i < depth; i++)
printf(" "); // Indentation for hierarchy

printf("Directory: %s\n", dir->name);

for (int i = 0; i < dir->fileCount; i++) {


for (int j = 0; j < depth + 1; j++)
printf(" ");
printf("File: %s\n", dir->files[i].name);
}

for (int i = 0; i < dir->subDirCount; i++) {


display(dir->subDirs[i], depth + 1);
}
}

int main() {
struct Directory *root = (struct Directory *)malloc(sizeof(struct Directory));
strcpy(root->name, "root");
root->fileCount = 0;
84
root->subDirCount = 0;

// Creating structure
createDirectory(root, "subdir1");
createFile(root, "file1.txt");

createDirectory(root->subDirs[0], "subsubdir1");
createFile(root->subDirs[0], "file2.txt");
createFile(root->subDirs[0]->subDirs[0], "file3.txt");

createDirectory(root, "subdir2");
createFile(root->subDirs[1], "file4.txt");

// Display the hierarchical structure


printf("Hierarchical Directory Structure:\n");
display(root, 0);

return 0;
}

OUTPUT:

Hierarchical Directory Structure:


Directory: root
File: file1.txt
Directory: subdir1
File: file2.txt
Directory: subsubdir1
File: file3.txt
Directory: subdir2
File: file4.txt

RESULT:

Thus the C program to simulate the file organization techniques was written and output was
verified successfully.

85
Ex.No 15A IMPLEMENTATION OF FILE ALLOCATION STRATEGIES

SEQUENTIAL FILE ALLOCATION


Date :

AIM :
To implement Sequential file allocation in C.
ALGORITHM:
Step 1: Initialize Memory
 Create an array memory[50], initialized to 0.
o (0 → free block, 1 → occupied block)
Step 2: Input Number of Files
 Ask the user to enter the number of files n.

Step 3: For Each File (Repeat for n files)


1. Ask the user to input:
o File name,
o Starting block number,
o Length (number of blocks the file needs).
2. Check if the required blocks are free:
o From startBlock to startBlock + length - 1,
o If any block is already allocated (i.e., memory[j] == 1), set a flag to indicate failure.
3. If free (flag = 0):
o Mark all the required blocks as allocated (memory[j] = 1).
o Save file information into the files array.
o Increase the total file count.
4. If not free (flag = 1):
o Print an error message ("blocks already allocated").

Step 4: Display File Allocation Table


 Print a table showing:
o File Name,
o Start Block,
o Length (number of blocks allocated).

Step 5: End Program

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

struct File {
char name[20];
int startBlock;
int length;
};

int main() {
int memory[50] = {0}; // 0 means free, 1 means occupied
86
struct File files[10];
int n, i, j, totalFiles = 0;

printf("Enter the number of files: ");


scanf("%d", &n);

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


printf("\nEnter file name: ");
scanf("%s", files[totalFiles].name);
printf("Enter starting block and length of the file: ");
scanf("%d %d", &files[totalFiles].startBlock, &files[totalFiles].length);

// Check if blocks are free


int flag = 0;
for (j = files[totalFiles].startBlock; j < (files[totalFiles].startBlock + files[totalFiles].length); j++) {
if (memory[j] == 1) {
flag = 1;
break;
}
}

if (flag == 0) {
// Allocate the file
for (j = files[totalFiles].startBlock; j < (files[totalFiles].startBlock + files[totalFiles].length); j++) {
memory[j] = 1;
}
totalFiles++;
printf("File allocated successfully.\n");
} else {
printf("Error: Blocks already allocated, can't allocate file '%s'.\n", files[totalFiles].name);
}
}

// Display file allocation table


printf("\nFile Allocation Table:\n");
printf("File Name\tStart Block\tLength\n");
for (i = 0; i < totalFiles; i++) {
printf("%s\t\t%d\t\t%d\n", files[i].name, files[i].startBlock, files[i].length);
}

return 0;
}

87
OUTPUT:

Enter the number of files: 3

Enter file name: file1


Enter starting block and length of the file: 2 4
File allocated successfully.

Enter file name: file2


Enter starting block and length of the file: 7 3
File allocated successfully.

Enter file name: file3


Enter starting block and length of the file: 4 2
Error: Blocks already allocated, can't allocate file 'file3'.

File Allocation Table:


File Name Start Block Length
file1 2 4
file2 7 3

RESULT:

Thus the C program to implement sequential file allocation was written and output was
verified successfully.

88
EX.NO:15b INDEXED FILE ALLOCATION
DATE:

AIM:
To implement Indexed file allocation technique in C.
ALGORITHM:

1. Start

2. Declare the index block no. and total no.of files in a block

3. Get the index block no. and total no.of files in a block from the user.

4. Allocate files based on the index block no.

5. Arrange the files based on indexes which are created for each fragment of the file such
that each and every similar indexed file is maintained by the primary index to provide the
flow to file fragments.

6. stop

PROGRAM:

#include <stdio.h>
#include <stdlib.h>

struct File {
char name[20];
int indexBlock;
int blocks[10];
int length;
};

int main() {
int memory[50] = {0}; // 0 = free, 1 = allocated
struct File files[10];
int n, i, j, totalFiles = 0;

printf("Enter the number of files: ");


scanf("%d", &n);

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


printf("\nEnter file name: ");
scanf("%s", files[totalFiles].name);

89
printf("Enter number of blocks needed: ");
scanf("%d", &files[totalFiles].length);

// Allocate index block


int indexBlockFound = 0;
for (j = 0; j < 50; j++) {
if (memory[j] == 0) {
files[totalFiles].indexBlock = j;
memory[j] = 1;
indexBlockFound = 1;
break;
}
}

if (!indexBlockFound) {
printf("Error: No free block available for index block!\n");
continue;
}

printf("Enter the block numbers for file '%s':\n", files[totalFiles].name);


int success = 1;
for (j = 0; j < files[totalFiles].length; j++) {
int blockNum;
scanf("%d", &blockNum);

if (blockNum < 0 || blockNum >= 50) {


printf("Invalid block number!\n");
success = 0;
break;
}

if (memory[blockNum] == 0) {
files[totalFiles].blocks[j] = blockNum;
memory[blockNum] = 1;
} else {
printf("Block %d is already allocated! Cannot assign.\n", blockNum);
success = 0;
break;
}
}

if (success) {
totalFiles++;
printf("File allocated successfully.\n");
} else {
// Rollback allocation if failure
memory[files[totalFiles].indexBlock] = 0;
for (int k = 0; k < j; k++) {
memory[files[totalFiles].blocks[k]] = 0;
90
}
printf("File allocation failed. Try again.\n");
}
}

// Display file allocation details


printf("\nFile Allocation Table:\n");
printf("File Name\tIndex Block\tBlocks\n");

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


printf("%s\t\t%d\t\t", files[i].name, files[i].indexBlock);
for (j = 0; j < files[i].length; j++) {
printf("%d ", files[i].blocks[j]);
}
printf("\n");
}

return 0;
}

OUTPUT:
Enter the number of files: 2

Enter file name: file1


Enter number of blocks needed: 3
Enter the block numbers for file 'file1':
578
File allocated successfully.

Enter file name: file2


Enter number of blocks needed: 2
Enter the block numbers for file 'file2':
89
Block 8 is already allocated! Cannot assign.
File allocation failed. Try again.

File Allocation Table:


File Name Index Block Blocks
file1 0 578

RESULT:

Thus the C program to implement indexed file allocation was written and output was
verified successfully.

91
EX.NO. 16 Disk Scheduling Algorithms

DATE :

AIM:

To Write a C program to simulate disk scheduling algorithms. Such as


A) FCFS , B) SCAN , C) C-SCAN

A) FCFS :

ALGORITHM:

Step 1: Read the number of disk requests (n).

 Read the sequence of disk requests into an array request[].

 Read the initial head position (initial).

Step 2: Initialize Set totalMovement = 0 to keep track of total head movement.

Step 3: Process Each Request for each request in the order they were entered:

1. Calculate the absolute difference between the current head


position and the next request.

movement = |current head position - next request position|

2. Add this movement to totalMovement.

3. Update the current head position to the current request.

Step 4: Print the order of service (head movement path) and total head movement

Step 5: Exit the program.

PROGRAM:

#include <stdio.h>
#include <stdlib.h>

int main() {
int n, i, initial, totalMovement = 0;
int request[100];
printf("Enter the number of disk requests: ")
scanf("%d", &n);
printf("Enter the disk request sequence:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &request[i]);
}
92
printf("Enter the initial head position: ");
scanf("%d", &initial);
printf("\nOrder of service:\n");
printf("%d", initial);
for (i = 0; i < n; i++)
{
totalMovement += abs(request[i] - initial);
initial = request[i];
printf(" -> %d", initial);
}
printf("\n\nTotal head movement = %d cylinders\n", totalMovement);
return 0;
}

OUTPUT :

Enter the number of disk requests: 5


Enter the disk request sequence:
98 183 37 122 14
Enter the initial head position: 53

Order of service:
53 -> 98 -> 183 -> 37 -> 122 -> 14

Total head movement = 640 cylinders

B) SCAN

ALGORITHM:
Step 1: Start the program
 Read the number of disk requests n.
 Read the disk request sequence into array request[].
 Read the initial head position (head).
 Read the total disk size (disk_size).
Step 2: Add Special Points
 Insert the initial head position into the request list.
 Insert 0 into the request list (assuming the head moves toward 0
first).

Step 3: Sort the request[] array in ascending order (using bubble sort or any sorting
technique).
Step 4: Find the index (position) of the head in the sorted request array.
Step 5: Service Requests
1. Move left (toward 0):
o From the head's position, move backward in the sorted
array.
o For each movement:
 Print the current request.
 Add the absolute difference between current and
next request to total movement.
93
2. Move right (after reaching 0):
o After reaching the start (0), move forward in the sorted
array.
o For each movement:
 Print the current request.
 Add the absolute difference between current and
next request to total movement.
Step 6: Display the order of head movements and total head movement.

Step 7:Stop the program

PROGRAM:
#include <stdlib.h>

void sort(int arr[], int n) {


// Simple Bubble Sort
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

int main() {
int n, head, disk_size, i, j;
int request[100];

printf("Enter the number of disk requests: ");


scanf("%d", &n);

printf("Enter the disk request sequence:\n");


for (i = 0; i < n; i++) {
scanf("%d", &request[i]);
}

printf("Enter the initial head position: ");


scanf("%d", &head);

printf("Enter the total disk size (max cylinder number): ");


scanf("%d", &disk_size);

// Add head and disk end points into request array


request[n] = head;
n++;
request[n] = 0; // Assuming we move towards 0 first
n++;

94
sort(request, n);

// Find head position after sorting


int position;
for (i = 0; i < n; i++) {
if (request[i] == head) {
position = i;
break;
}
}

int total_movement = 0;

printf("\nOrder of service:\n");

// Move towards 0 first (left)


for (i = position; i >= 0; i--) {
printf("%d ", request[i]);
if (i != 0)
total_movement += abs(request[i] - request[i-1]);
}

// Then move towards the maximum side (right)


for (i = position + 1; i < n; i++) {
printf("%d ", request[i]);
if (i != n-1)
total_movement += abs(request[i] - request[i+1]);
}

printf("\n\nTotal head movement = %d cylinders\n", total_movement);

return 0;
}

OUTPUT:
Enter the number of disk requests: 5
Enter the disk request sequence:
82 170 43 140 24
Enter the initial head position: 50
Enter the total disk size (max cylinder number): 200

Order of service:
50 43 24 82 140 170 0

Total head movement = 208 cylinders

95
C) C-SCAN

ALGORITHM:

1. Define Event Structure: Create a structure to store event details such as the event
name and priority.

2. Initialize Event Array: Store predefined events in an array, each having a name and
a priority value.

3. Display Events: Create a function to display all the events and their priorities.

4. Find and Schedule Event:


Search for the event with the smallest priority value (higher priority).Schedule that
event by printing its name.

5. Remove Scheduled Event: After scheduling, remove the event from the array by
shifting the remaining events.

6. Repeat the Process: Continue scheduling the next event until no events are left in the
array.

PROGRAM:

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

// Define Event structure struct


Event {
char name[50];
int priority; // Lower value means higher priority
};

// Function to schedule the next event based on priority


void scheduleNextEvent(struct Event events[], int n) {
if (n == 0) {
printf("No events to schedule!\n");
return;
}

// Find the event with the highest priority (smallest priority value) int
min_priority_index = 0;

96
for (int i = 1; i < n; i++) {
if (events[i].priority < events[min_priority_index].priority) {
min_priority_index = i;
}
}

// Print the scheduled event


printf("Next event to be scheduled: %s (Priority: %d)\n",
events[min_priority_index].name, events[min_priority_index].priority);

// Remove the scheduled event by shifting the rest for


(int i = min_priority_index; i < n - 1; i++) {
events[i] = events[i + 1];
}
}

// Function to display all events


void displayEvents(struct Event events[], int n) {
if (n == 0) {
printf("No events in the queue!\n");
return;
}

printf("Current events in the queue:\n");


for (int i = 0; i < n; i++) {
printf("Event: %s, Priority: %d\n", events[i].name, events[i].priority); }
}

int main() { // Array of


events struct Event
events[5];

// Adding events to the array


strcpy(events[0].name, "Meeting with team"); events[0].priority
= 2;

strcpy(events[1].name, "Submit report");


events[1].priority = 1;

strcpy(events[2].name, "Client call");


events[2].priority = 3;

// Number of events
int n = 3;

// Display the current events displayEvents(events,


n);

// Schedule and remove events one by one


while (n > 0) { printf("\n");

97
scheduleNextEvent(events, n);
n--; // Decrease number of events after
scheduling displayEvents(events, n);
}

return 0;
}

OUTPUT:
Current events in the queue:
Event: Meeting with
team, Priority: 2 Event:
Submit report, Priority: 1
Event: Client call,
Priority: 3

Next event to be scheduled: Submit report (Priority: 1)


Current events in the queue:
Event: Meeting with
team, Priority: 2 Event:
Client call, Priority: 3

Next event to be scheduled: Meeting with team (Priority: 2)


Current events in the queue:
Event: Client call, Priority: 3

Next event to be scheduled: Client call


(Priority: 3) No events in the queue!

RESULT:

Thus C program to simulate FCFS,SCAN,C-SCAN disk scheduling


algorithms was executed Successfully.

98
EX.NO . Selfish Round Robin CPU scheduling
DATE :

AIM:
write a c program for Selfish Round Robin CPU Scheduling

ALGORITHM:

Step 1: Read the number of processes n.


For each process:
 Read Burst Time.
 Read Priority (lower number = higher priority).
 Initialize:
remaining_time = burst_time
completed = 0 (false)
Step 2: Read the time quantum value.
Step 3: Initialize
 Set total_time = 0.
 Set completed_processes = 0.
Step 4: Process Execution Loop
 While completed_processes < n:
1. Find the process with the highest priority:
Among all incomplete processes (completed == 0),
Pick the one with the lowest priority number.
2. If no process is left, break the loop.
3. Execute the selected process:
If remaining_time > time_quantum:
Subtract time_quantum from remaining_time.
Add time_quantum to total_time.
Else:
Add remaining_time to total_time.
Set remaining_time = 0.
Mark completed = 1.
Increment completed_processes.
4.Print the process ID to show execution order.

Step 5: Print total execution time.


Step 6: Stop the program

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

typedef struct {
int id;
int burst_time;
int remaining_time;
int priority;
int completed;
99
} Process;

int main() {
int n, time_quantum;
printf("Enter the number of processes: ");
scanf("%d", &n);
Process p[n];
printf("Enter burst time and priority (lower number = higher priority) for each
process:\n");
for (int i = 0; i < n; i++) {
p[i].id = i + 1;
printf("Process %d Burst Time: ", i + 1);
scanf("%d", &p[i].burst_time);
printf("Process %d Priority: ", i + 1);
scanf("%d", &p[i].priority);
p[i].remaining_time = p[i].burst_time;
p[i].completed = 0;
}
printf("Enter the time quantum: ");
scanf("%d", &time_quantum);
int total_time = 0;
int completed_processes = 0;
printf("\nExecution Order:\n");
while (completed_processes < n) {
int min_priority = 9999;
int index = -1;
// Find process with highest priority (smallest priority number)
for (int i = 0; i < n; i++) {
if (p[i].completed == 0 && p[i].priority < min_priority) {
min_priority = p[i].priority;
index = i;
}
}
if (index == -1) {
break; // No more processes left
}
// Execute selected process
printf("P%d ", p[index].id);

if (p[index].remaining_time > time_quantum) {


p[index].remaining_time -= time_quantum;
total_time += time_quantum;
} else {
total_time += p[index].remaining_time;
p[index].remaining_time = 0;
p[index].completed = 1;
completed_processes++;
}
}

100
printf("\nTotal execution time: %d units\n", total_time);
return 0;
}

OUTPUT:
Enter the number of processes: 4
Enter burst time and priority (lower number = higher priority) for each process:
Process 1 Burst Time: 10
Process 1 Priority: 2
Process 2 Burst Time: 5
Process 2 Priority: 1
Process 3 Burst Time: 8
Process 3 Priority: 3
Process 4 Burst Time: 6
Process 4 Priority: 2
Enter the time quantum: 4
Execution Order:
P2 P1 P4 P1 P4 P1 P3 P3
Total execution time: 29 units

RESULT:

Thus the C program to implement selfish round robin scheduling algorithm was written and
output was verified successfully.

101

You might also like