Download as pdf or txt
Download as pdf or txt
You are on page 1of 80

GOVERNMENT COLLEGE OF ENGINEERING

ERODE-638316

RECORD NOTE BOOK


REGISTER NUMBER

Certified that this is the Bonafide record of work done by Selvan / Selvi
………………………. of the Fourth Semester Computer Science and Engineering
Branch during the academic year 2022-2023 in the Operating Systems(CS3461)
Laboratory.

STAFF INCHARGE HEAD OF THE DEPARTMENT

Submitted for the university practical examination on ……………. at Government


College of Engineering.
Date………………..

INTERNAL EXAMINER EXTERNAL EXAMINER


INDEX

S.NO DATE NAME OF THE EXPERIMENT PAGE SIGN


NO
1 INSTALLATION OF UNIX 01
OPERATING SYSTEMS
2 BASIC UNIX COMMANDS AND 02
SHELL PROGRAMMING
3 SYSTEM CALLS OF UNIX 10
4 CPU SCHEDULING ALGORITHM 15
5 SHARED MEMORY AND IPC 24
6 IMPLEMENTATION OF 27
SEMAPHORES
7 DEADLOCK AVOIDANCE 29
8 DEADLOCK DETECTION 34
9 THREADING AND 37
SYNCHRONIZATION
10 PAGING 38
11 MEMORY ALLOCATION METHOD 39
12 PAGE REPLACEMENT 45
13 FILE ORGANIZATION TECHNIQUES 51
14 FILE ALLOCATION STRATEGIES 62
15 DISK SCHEDULING ALGORITHMS 68
16 INSTALLATION OF LINUX USING 77
VMWARE
EX.NO:1 INSTALLATION OF UNIX OPERATING SYSTEMS

AIM:
To study the installation of UNIX Operating System.

PROCEDURE :
1. Instructions to Install Ubuntu Linux 12.04 (LTS) along with Windows
Back Up Your Existing Data!
a)This is highly recommended that you should take backup of your entire data before start
with the installation process.
b)Obtaining System Installation Media
c)Download latest Desktop version of Ubuntu from this link:
http://www.ubuntu.com/download/desktop
Booting the Installation System
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...
6 .In a few minutes installation wizard will be started. Select your language and click the
"Install Ubuntu" button to continue...
7 .Please select Ubuntu 12.04 (LTS) and press Enter to boot the machine in Ubuntu 12.04
Linux.
8 .Here you can see the users on the machine, Click on the user name and enter the password
and press Enter key to login.
9 .We have successfully install and login to Ubuntu 12.04 LTS.

CONCLUSION:

Thus the installation of UNIX Operating System has been completed successfully.

1
EX.NO : 2 IMPLEMENTATION OF UNIX COMMANDS AND SHELL
PROGRAMMING

AIM:
To write a c program to implement the following unix commands ls,cat,
grep,cp and shell programming.

a)UNIX COMMAMDS

1.ls command

ALGORITHM:
Step 1 : Store path of current working directory using getcwd system call.
Step 2 : Scan directory of the stored path using scandir system call and sort the resultant
array of structure.
Step 3 : Display dname member for all entries if it is not a hidden file.
Step 4 : Stop.

PROGRAM:

#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<dirent.h>
int main(int argc,char* argv[]){
DIR *dp;
struct dirent *sd;
dp = opendir(argv[1]);
while((sd=readdir(dp))!=NULL)
printf("%s\t",sd->d_name);
closedir(dp);
}

2.cat command

ALGORITHM:

Step 1: Go on the terminal window and write the following command:


cat >A.txt
Step 2: After this, type any text as you want.
Step 3: Now, press the Ctrl key and press d.
Step 4: Repeat the same process for the other file named B.txt

2
cat >B.txt
Step 5: Again type your desired content and press Ctrl + d.

PROGRAM:

#include<fcntl.h>
#include<sys/stat.h>
#include<stdio.h>
#define BUFFERSIZE 1
int main(int argc,char** argv){
int fd1;
int n;
char buf;
fd1 = open(argv[1],O_RDONLY);
while((n=read(fd1,&buf,1))>0)
printf("%c",buf);
return 0;
}

3. grep command

ALGORITHM:

Step 1 : Get filename and search string as command-line argument.


Step 2 : Open the file in read-only mode using open system call.
Step 3 : If file does not exist, then stop.
Step 4 : Let length of the search string be n.
Step 5 : Read line-by-line until end-of-file
a) Check to find out the occurrence of the search string in a line by examining
characters in the range 1–n, 2–n+1, etc.
b) If search string exists, then print the line.
Step 6 : Close the file using close system call.
Step 7 : Stop.

PROGRAM:

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

#define BUFFER_LENGTH 511

int main( int ac, char * av[] )


{

3
char lineBuffer[BUFFER_LENGTH+1];
FILE *fp = NULL;
int count = 0;
if( ac < 3 )
{
fprintf( stderr, "A string pattern and a file name are required\n" );
return 1;
}

fp = fopen( av[2], "r" );


if( ! fp )
{
fprintf( stderr, "Error - unable to open %s\n", av[2] );
return 2;
}

while( fgets( lineBuffer, BUFFER_LENGTH, fp ) )


{
if( strstr( lineBuffer, av[1] ) )
{
printf( "%s", lineBuffer );
++count;
}
}
fclose( fp );
printf( "found %d occurrences\n", count );
return 0;
}

4. cp command

ALGORITHM:

Step 1 : Get source and destination filename as command-line argument.


Step 2 : Declare a buffer of size 1KB
Step 3 : Open the source file in read only mode using open system call.
Step 4 : If file does not exist, then stop.
Step 5 : Create the destination file using creat system call.
Step 6 : If file cannot be created, then stop.
Step 7 : File copy is achieved as follows:
a) Read 1KB data from source file and store onto buffer using read system call.
b) Write the buffer contents onto destination file using write system call.
c) If end-of-file then step 8 else step 7a.

4
Step 8 : Close source and destination file using close system call.
Step 9 : Stop.

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#define BUFFERSIZE 1
int main(int argc,char** argv){
FILE *f1,*f2;
char buf;
int n;
f1 = fopen(argv[1],"r");
f2 = fopen(argv[2],"w");
while((buf=(fgetc(f1)))!=EOF){
fputc(buf,f2);
}
fclose(f1);
fclose(f2);
return 0;
}

b)SHELL PROGRAMMING

1.Sum
ALGORITHM:

Step 1 : Initialize two variables.


Step 2 : Declare and implement the addition function.
Step 3 : Call the add function with two arguments.

PROGRAM:

#!/bin/bash
a=10
b=20
sum=$(($a+$b))
echo "Sum is:$sum"

5
2.Area of Rectangle

ALGORITHM:

Step 1 : Read the breadth of the rectangle


Step 2 : Read the length of the rectangle
Step 3 : Calculate the area of the rectangle by multiplying the length and breadth of the
rectangle.
Step 4 : Assign the area of the rectangle to the area variable.
Step 5 : print the area of the rectangle.

PROGRAM:

#!/bin/bash
#shell script to find area of rectangle
echo "enter the length of rectangle:"
read length
echo "enter the breadth of rectangle:"
read breadth
area=`expr $length \* $breadth`
echo "area of rectangle= $area"

3.Simple Interest

ALGORITHM:
Step 1 : Read the Principle Amount
Step 2 : Read the rate of interest
Step 2 : Read the no of years
Step 3 : Calculate the simple interest by multiplying Principle amount,rate of interest ,no of
years and then divide the result by 100.
Step 4 : Assign the simple interest answer to the variable i.
Step 5 : print the value of simple interest.

PROGRAM:

echo "enter principle amount"


read p
echo "rate of interest"
read r
echo "enter no of years"
read n

6
i=`expr $p \* $r \* $n`
i=`expr $i / 100`
echo "the simple interest is rs. "
echo $i

4.Greatest of two number

ALGORITHM:

Step 1 : Read 2 numbers n1 and n2


Step 2 : Check if n1 is greater than n2 announce n1 as greatest else, announce n2 as greatest.

PROGRAM:
echo "enter first number"
read a
echo "enter second number"
read b
if [ $a -gt $b ]
then
echo $a "is greatest "
else
echo $b "is greatest "
fi
5.Factorial

ALGORITHM:

Step 1 : Read n
Step 2 : Initialize fact to 1 and i to n
Step 3 : Repeat the following until i>0
Assign fact i to fact
Decrement i by 1

PROGRAM:

echo "Total no of factorial wants"


read fact
ans=1
counter=0
while [ $fact -ne $counter ]
do
counter=`expr $counter + 1`
ans=`expr $ans \* $counter`
done

7
echo "Total of factorial is $ans"

6.Sum of N numbers

ALGORITHM:
Step 1 : Read n
Step 2 : Initialize x=1 and sum=0
Step 3 : Repeat the following until x <n Assign sum + x to sum Increment x by2

PROGRAM:

echo "enter size(n)"


read N
i=1
sum=0
echo "enter numbers"
while [ $i -le $N ]
do
read num
sum=$((sum+num))
i=$((i+1))
done
echo $sum

7.Display the first N even numbers

ALGORITHM:

Step 1 : Start
Step 2 : Declare a variable (Suppose $checker) and just initialize with 0.
Step 3 : Read number ( Suppose num) from the user.
Step 4 : Run while loop into $num
Step 5 : Give while loop condition -> $checker –le $num
Step 6 : Divide $checker by 2 and if it remainder equal to zero then it is even and just print it.
Step 7 : Otherwise increment $checker = $checker + 1
Step 8 : Print even series upto $num
Step 9 : Stop

PROGRAM:

echo "enter size(n)"


read N
i=1

8
even=0
echo "enter numbers"
while [ $i -le $N ]
do
echo $even
even=$((even+2))
i=$((i+1))
done

CONCLUSION:

Thus the unix command and shell programming was executed successfully.

9
EX.NO : 3 SYSTEM CALLS OF UNIX

AIM:
To write a program using the following system calls of unix fork,exec,getpid,
getppid,exit,wait,close,stat,opendir,readdir,open,read,write.

1.using fork,getpid and getppid

ALGORITHM:
Step 1 : Start
Step 2 : Declare int p1,p2,p3 and p4;
Step 3 : Call the fork function for p1.If p1 is equal to -1 print error and return 0.
Step 4 : If p1 is equal to 0 then call fork () for p2.If p2 =0 the print the parent and child by
getppid() and getpid().
Step 5 : Again call fork () for p3. If p3 is equal to -1 print error and return 0.
Step 6 : If p3 =0 then print the parent and child by getppid() and getpid().
Step 7 : Call fork () for p4. If p4=0 the print the parent and child by getppid() and
getpid().return 0
Step 8 : Stop

PROGRAM:

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
void main()
{
pid_t pid;
pid=fork();
if(pid==-1)
printf("\n error in creating process");
else if(pid==0)
{
printf("\n executing in child process");
printf("\n child process pid=%d",getpid());
printf("\n parent process pid=%d",getppid());
}
else
printf("\n Executing in parent process,pid=%d\n",getppid());
}

10
2. exec,exit,wait

ALGORITHM:

Step 1 : Get the Unix command from the user through the command line arguments.
Step 2 : Create a child process to execute the Unix command by calling the fork system call.
Step 3 : Check if the child is created successfully.
Step 4 : If the child is created successfully goto step 5 else exit.
Step 5 : Execute the command by passing the command line arguments to the execvp
function.
Step 6 : If any error occurred in this execution the error is thrown to the user using perror
function
Step 7 : Exit from child process
Step 8 : The terminated child process id is returned by wait function.
Step 9 : Stop.

PROGRAM:

#include<string.h>
#i#include<stdio.h>
nclude<sys/types.h>
#include<wait.h>
#include<unistd.h>
#include<stdlib.h>
int main(int argc,char* argv[]){
pid_t pid;
int cstatus;
pid_t c;
pid = fork();
if(pid == -1)
printf("\n Error in Creating process");
else if(pid==0){
printf("\n Executing in child process");
execlp(argv[1],&argv[1],argv[2],"home",NULL);
perror("exec failure");
exit(1);
}
else{
printf("\n Executing in parent process");
c=wait(&cstatus);
printf("\n Parent : child %ld exited with status = %d \n",(long)c,cstatus);
}
}

11
3. stat

ALGORITHM:
Step 1 : Get filename as command line argument.
Step 2 : If filename does not exist then stop.
Step 3 : Call stat system call on the filename that returns a structure
Step 4 : Display members st_uid, st_gid, st_blksize, st_block, st_size, st_nlink, etc.,
Step 5 : Convert time members such as st_atime, st_mtime into time using ctime function
Step 6 : Compare st_mode with mode constants such as S_IRUSR, S_IWGRP, S_IXOTH
and display file permissions.
Step 7 : Stop

PROGRAM:

#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>

void main(int argc,char** argv){


if(argc!=2)
printf("usage error: Invalid number of arguments");
struct stat fs;
if(stat(argv[1],&fs)<0)
printf("Usage error : File dosent exist.");
printf("Information for %s \n",argv[1]);
printf("File Size :\t\t %d bytes\n",fs.st_size);
printf("File inode:\t\t %d\n",fs.st_ino);
printf("File mode :\t\t %d\n",fs.st_mode);
printf("User ID of title owner:\t %d\n",fs.st_uid);
printf("File last access time :\t %d\n",fs.st_atime);
}

4. opendir_readdir

ALGORITHM:

Step 1 : Get directory name as command line argument.


Step 2 : If directory does not exist then stop.
Step 3 : Open the directory using opendir system call that returns a structure
Step 4 : Read the directory using readdir system call that returns a structure
Step 5 : Display d_name member for each entry.
Step 6 : Close the directory using closedir system call.

12
Step 7 : Stop

PROGRAM:

#include<stdio.h>
#include<dirent.h>
int main(){
struct dirent* de;
DIR *dr = opendir(".");
if(dr==NULL){
printf("Could not open current directory");
return 0;
}
while((de=readdir(dr))!=NULL)
printf("%s \n",de->d_name);
closedir(dr);
return 1;
}

5. open read write close

ALGORITHM:

Step 1 : Declare a character buffer buf to store 100 bytes.


Step 2 : Get exisiting and new filename as command line argument.
Step 3 : Create a file with the given name using open system call with O_CREATE ,
O_RDONLY, O_TRUNC, O_APPEND option.
Step 4 : Check the file descriptor.
a) If value is negative,or not exist then stop.
Step 5 : Get input from the console until user types Ctrl+D
a) Read 100 bytes (max.) from console and store onto buf using read system call
b) Write length of buf onto file using write system call.
Step 6 : Close the file using close system call.
Step 7 : Stop

PROGRAM:

#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

13
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char* argv[]){
int fd;
int n_char=0;
char buffer[10];
fd = open(argv[1],O_RDONLY);
if(fd==-1){
printf("File open error");
exit(1);
}
while((n_char=read(fd,buffer,1)!=0))
n_char = write(1,buffer,n_char);
close(fd);
return 0;
}

CONCLUSION:

Thus the programs to implement system calls are Successfully Written and Executed.

14
EX.NO:4 SCHEDULING ALGORITHM

AIM:
To write a c program to display the gantt chart for FCFS, SJF,Priority &
Round Robin Scheduling.

1. FCFS SCHEDULING

ALGORITHM:

Step 1 : Start the process


Step 2 : Accept the number of processes in the ready Queue
Step 3 : For each process in the ready Q, assign the process name and the burst time
Step 4 : Set the waiting of the first process as _0'and its burst time as its turnaround time
Step 5 : for each process in the Ready Q calculate
a) Waiting times(n)= waiting time (n-1) + Burst time (n-1)
b) Turnaround time (n)= waiting time(n)+Burst time(n)
Step 6 : Calculate
a) Average waiting time = Total waiting Time/ Number of process
b) Average Turnaround time = Total Turnaround Time / Number of process
Step 7 : Stop the process

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
typedef struct process
{
int pid,ft,wt,bt;
}pr;
int n;
pr p[10];
void fcfs();
void disp_gantt();
int main()
{
int i;
printf("\n how many process:");
scanf("%d",&n);

15
printf("\t enter the values of B.T \n");
for( i=0;i<n;i++)
{
printf("enter process %d B.T :",i);
scanf("%d",&p[i].bt);
p[i].pid=i;
}
fcfs();
}
void fcfs()
{
int i,j;
float avgwt,avgtat,sum_wt=0,sum_tat=0;
for( i=0;i<n;i++)
{
if(i==0)
p[i].wt-0;
else
p[i].wt=p[i-1].ft;
p[i].ft = p[i].wt + p[i].bt;
sum_wt = sum_wt+ p[i].wt;
sum_tat = sum_tat + p[i].ft;
}

avgwt=sum_wt/n;
avgtat=sum_tat/n;
disp_gantt(n);
printf("\n AVG.TAT : %5.2f ms",avgtat);
printf("\n AVG.WT : %5.2f ms",avgwt);
printf("\n Total.TAT : %.2f ms",avgtat*n);
printf("\n Total.WT : %.2f ms",avgwt*n);
}
void disp_gantt()
{
int i;
printf("\n\n GANTT CHART\n\n\t");
for(i=0;i<n;i++)
printf("P%d\t",p[i].pid);
printf("\n 0\t");
for(i=0;i<n;i++)
printf("%d\t",p[i].ft);

printf("\n");
}

16
2. SJF SCHEDULING

ALGORITHM:

Step 1 : Start the process


Step 2 : Accept the number of processes in the ready Queue
Step 3 : For each process in the ready Q ,assign the process id and accept the CPU burst time.
Step 4 : Start the Ready Q according the shortest Burst time by sorting according to lowest to
highest burst time.
Step 5 : Set the waiting time of the first process as _0' and its turnaround time as its burst
time.
Step 6 : Sort the processes names based on their Burt time
Step 7 : For each process in the ready queue, calculate
a) Waiting timess(n)= waiting time (n-1)+ Burst time (n-1) b) Turnaround time (n)=
waiting time(n)+Burst time(n)
Step 8 : Calculate
a) Average waiting time = Total waiting Time/ Number of process
b) Average Turnaround time = Total Turnaround Time/ Number of process
Step 9 : Stop the process

PROGRAM:

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

typedef struct process


{
int pid,ft,wt,bt;
}pr;
int n;
pr p[10];
void sjf();
void disp_gantt();
int main()
{
int i;
printf("\n how many process:");
scanf("%d",&n);
printf("\t enter the values of B.T \n");
for( i=0;i<n;i++)
{
printf("enter process %d B.T :",i);
scanf(" %d",&p[i].bt);

17
p[i].pid=i;
}
sjf();
}
void sjf()
{
int i,j;
pr temp;
float avgwt,avgtat,sum_wt=0,sum_tat=0;
for(i=0;i<n;i++)
for(j=0;j<n-i-1;j++)
if(p[i].bt>p[j+1].bt){
temp = p[i];
p[j] =p[j+1];
p[i+1]=temp;
}
for( i=0;i<n;i++){
if(i==0)
p[i].wt-0;
else
p[i].wt=p[i-1].ft;
p[i].ft = p[i].wt + p[i].bt;
sum_wt = sum_wt+ p[i].wt;
sum_tat = sum_tat + p[i].ft;
}
avgwt=sum_wt/n;
avgtat=sum_tat/n;
disp_gantt(n);
printf("\n AVG.TAT : %5.2f ms",avgtat);
printf("\n AVG.WT : %5.2f ms",avgwt);
printf("\n Total.TAT : %.2f ms",avgtat*n);
printf("\n Total.WT : %.2f ms",avgwt*n);
}
void disp_gantt()
{
int i;
printf("\n\n GANTT CHART\n\n\t");
for(i=0;i<n;i++)
printf("P%d\t",p[i].pid);
printf("\n 0\t");
for(i=0;i<n;i++)
printf(" %d\t",p[i].ft);
printf("\n");
}

18
3. PRIORITY SCHEDULING

ALGORITHM:

Step 1 : Start the process


Step 2 : Accept the number of processes in the ready Queue
Step 3 : For each process in the ready Q. assign the process id and accept the CPU burst time
Step 4 : Sort the ready queue according to the priority number. Step 5: Set the waiting of the
first process as _0' and its burst time as its turnaround time
Step 6 : Arrange the processes based on process priority
Step 7 :For each process in the Ready Q calculate
Step 8 : for each process in the Ready Q calculate
a) Waiting times(n)= waiting time (n-1) Burst time (n-1)
b) Turnaround time (n)= waiting time(n)+Burst time(n)
Step 9 : Calculate
a) Average waiting time - Total waiting Time Number of process
b) Average Turnaround time = Total Turnaround Time/ Number of process Print the
results in an order.
Step 10 : Stop the process

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
typedef struct process{
int pid,ft,wt,bt,priority;
}pr;
int n;
pr p[10];
void ps();
void disp_gantt();
int main(){
int i;
printf("\n How many Processes: ");
scanf("%d",&n);
printf("Enter the values: \n");
for(i=0;i<n;i++){
printf("\t Enter for Process %d: ",i);
printf("\t Burst time: ");
scanf("%d",&p[i].bt);
printf("\t\t\t\t Priority: ");
scanf("%d",&p[i].priority);
p[i].pid=i;
}

19
ps();
}
void ps(){
int i,j;
pr temp;
float avgwt,avgtat,sum_wt=0,sum_tat=0;
for(j=0;j<n-i-1;j++)
if(p[j].priority>p[j+1].priority){
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
for(i=0;i<n;i++){
if(i==0){
p[i].wt=0;
}
else{
p[i].wt=p[i-1].ft;
}
p[i].ft=p[i].wt+p[i].bt;
sum_wt=sum_wt+p[i].wt;
sum_tat=sum_tat+p[i].ft;
}
avgwt=sum_wt/n;
avgtat=sum_tat/n;
disp_gantt(n);
printf("Sum.TAT: %5.2f ms\t",sum_tat);
printf("Sum.WT: %5.2f ms\t",sum_wt);
printf("Avg.TAT: %5.2f ms\t",avgtat);
printf("Avg.WT: %5.2f ms\t",avgwt);
}

void disp_gantt(){
int i;
printf("\n\n GANTT CHART \n\n\t");
for(i=0;i<n;i++)
printf("P%d\t",p[i].pid);
printf("\n 0\t");
for(i=0;i<n;i++)
printf("%d\t",p[i].ft);
printf("\n");
}

20
4. ROUND ROBIN SCHEDULING

ALGORITHM:

Step 1 : Start the process


Step 2 : Accept the number of processes in the ready Queue and time quantum (or) time slice
Step 3 : For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4 : Calculate the no. of time slices for each process where No. of time slice for process
(n)= burst time process(n)/time slice
Step 5 : If the burst time is less than the time slice then the no. of time slices 1.
Step 6 : Consider the ready queue is a circular Q. calculate
a) Waiting time for process(n)= waiting time of process(n-1)+ burst time of
process(n-1) + the time difference in getting the CPU from process(n-1)
b) Turnaround time for process(n)= waiting time of process(n) + burst time of
process(n)+ the time difference in getting CPU from process(n)
Step 7 : Calculate
a) Average waiting time = Total waiting Time/ Number of process
b) Average Turnaround time = Total Turnaround Time/Number of process
Step 8 : Stop the process

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
typedef struct process
{
int pid, ft, wt, bt;
} pr;
int n;
pr p[10];
void rrs(int);

int main()
{
int i, tq;
printf("\n How many Processes: ");
scanf("%d", &n);
printf("Enter the values: \n");
for (i = 0; i < n; i++)
{
printf("\t Enter for Process %d: ", i);
printf("\t Burst time: ");
scanf("%d", &p[i].bt);
p[i].pid = i;
}

21
printf("\n\t Enter the Time Quantum");
scanf("%d", &tq);
rrs(tq);
}
void rrs(int TQ)
{
int i, j, k;
pr temp;
float avgwt, avgtat, sum_wt = 0, sum_tat = 0;
int AP[25], AT[25];
int fin = 0, count = 0, time = 0;
int fintime = 0;
AT[0] = 0;
while (fin < n)
{
for (i = 0; i < n; i++)
{
if (p[i].bt > 0)
{
k++;
time = (p[i].bt <= TQ) ? p[i].bt : TQ;
if (p[i].bt <= TQ)
p[i].ft = fintime + time;
p[i].bt = p[i].bt - time;
fintime += time;
AP[count] = p[i].pid;
AT[++count] = AT[count - 1] + time;
for (j = 0; j < n; j++)
if ((n - fin) != 1 && i != j && p[j].bt > 0)
p[j].wt += time;
if (p[i].bt == 0)
fin++;
}
}
}
for (i = 0; i < n; i++)
{
sum_wt = sum_wt + p[i].wt;
sum_tat = sum_tat + p[i].ft;
}
avgtat = sum_tat / n;
avgwt = sum_wt / n;
printf("Sum.WT: %5.2f ms\n", sum_wt);
printf("Sum.TAT: %5.2f ms\n", sum_tat);

22
printf("Avg.WT: %5.2f ms\n", avgwt);
printf("Avg.TAT: %5.2f ms\n", avgtat);
printf("\n\n GANTT CHART \n\n\t");
for (i = 0; i < count; i++)
printf("P%d\t", AP[i]);
printf("\n");

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


printf(" %d\t", AT[i]);
printf("\n");
}

CONCLUSION:

Thus the program to display various CPU scheduling algorithms were written and
executed.

23
EX.NO : 5 SHARED MEMORY AND IPC

AIM:
To write a c program to implement Shared memory and IPC

• server.c

ALGORITHM :

Step 1 : Initialize shared memory size to 27 and key is Initialized.


Step 2 : Create the shared memory segments and IPC.
Step 3 : Clear contents of shared region using function.
Step 4 : Write the shared region of the memory.
Step 5 : Fetch the process from shared memory using System call.

PROGRAM:
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
#include<stdlib.h>
#define SHMSZ 27

void main()
{
char c;
int shmid;
key_t key;
char *shm, *s;
key = 5678;
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0)
{
perror("Shmget");
exit(1);
}

if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)


{
perror("Shmat");
exit(1);
}

24
s = shm;

for (c = 'a'; c <= 'z'; c++)


*s++ = c;
*s = NULL;

while (*shm != '*')


sleep(1);

exit(0);
}

• client.c

ALGORITHM:

Step 1 : Initialize shared memory size to 27 and key is initialized.


Step 2 : Obtain access to same shared memory segment using same key.
Step 3 : If obtain display the shared memory and print it.
Step 4 : Attach client to server shared memory.
Step 5 : Stop.

PROGRAM:

#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
#include<stdlib.h>
#define SHMSZ 27
main()
{
int shmid;
key_t key;
char *shm, *s;

key = 5678;
if ((shmid = shmget(key, SHMSZ, 0666)) < 0)
{

25
perror("Shmget");
exit(1);
}

if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)


{
perror("Shmat");
exit(1);
}

for (s = shm; *s != NULL; s++)


putchar(*s);
putchar('\n');
*shm = '*';
exit(0);
}

CONCLUSION:
Thus the shared memory and interprocess communication has been implemented.

26
EX.NO : 6 IMPLEMENTATION OF SEMAPHORES

AIM:
To Write a C program to implement Semaphores

ALGORITHM:

Step 1 : Start
Step 2 : Initialize the semaphore variable S
Step 3 : In the producer function.
While s==1 do nothing
Produce the value
Assign s=1
Return
Step 4 : In the Consumer function
While s==0 do nothing
Display the consumed value
Assign s=0
Return
Step 5 : Create threads for producer and consumer function to make it run concurrently
Step 6 : Stop

PROGRAM:

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
sem_t mutex;
void* thread(void* arg)
{
//wait
sem_wait(&mutex);
printf("\nEntered thread\n");

//critical section
sleep(4);
//signal
printf("\n Exit thread\n");
sem_post(&mutex);
}
int main()
{

27
sem_init(&mutex, 0, 1);
pthread_t t1,t2;
pthread_create(&t1,NULL,thread,NULL);
sleep(2);
pthread_create(&t2,NULL,thread,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
sem_destroy(&mutex);
return 0;
}

CONCLUSION:

Thus the semaphore has been implemented successfully,.

28
EX.NO : 7 DEADLOCK AVOIDANCE

AIM:
To write a c program to implement Bankers Algorithm for DeadLock Avoidance

ALGORITHM:

Data Structures for the Banker’s Algorithm

Available : Vector of length m.


If available [j] = k, there are k instances of resource type Rj available.
Max : n x m matrix.
If Max [i,j] = k, then process Pi may request at most k instances of resource type Rj.
Allocation : n x m matrix.
If Allocation[i,j] = k then Pi is currently allocated k instances of Rj.
Need: n x m matrix.
If Need[i,j] = k, then Pi may need k more instances of Rj to complete its task.
Need [i,j] = Max[i,j] – Allocation [i,j].

Safety Algorithm

Step 1 : Work and Finish be the vector of length m and n respectively,


Work = Available and Finish[i] = False.
Step 2 : Find an i such that both Finish[i] = False and Needi <= Work
If no such i exists go to step 4.
Step 3 : Work = Work + Allocationi , Finish[i] = True;
Step 4 : if Finish[i] = True for all i, then the system is in safe state.

Resource request algorithm

Let Requesti be request vector for the process Pi, If requesti[j] = k, then process Pi wants k
instances of resource type Rj.
Step 1 : if Requesti <= Needi go to step 2. Otherwise raise an error condition
Step 2 : if Requesti <= Available go to step 3. Otherwise Pi must wait since the resources are
not available.
Step 3 : Have the system pretend to have allocated the requested resources to process Pi by
modifying the state as follows;
Available = Available - Requesti;
Allocationi = Allocationi + Requesti;
Needi = Needi - Requesti;
If the resulting resource allocation state is safe, the transaction is completed and process Pi is
allocated its resources. However if the state is unsafe, the Pi must wait for Requesti and the old
resource-allocation state is restored.

29
PROGRAM:
#include<stdio.h>

int check(int need[5][5],int f[5],int ava[5],int p,int r);


int sc(int need[5][5],int alloc[5][5],int ava[5],int p,int r,int n);

int res(int need[5][5],int alloc[5][5],int ava[5],int p,int r)


{
int i,j,n,re[5],c=0;
printf("Enter the process no.");
scanf("%d",&n);
printf("Enter the resources request\n");
for(i=0;i<r;i++)
{
scanf("%d",&re[i]);
if(need[n][i]>=re[i] && re[i]<=ava[i])
c++;
}
if(c!=r)
{
printf("resouses cannot be allocated");
return 0;
}
for(i=0;i<r;i++)
{
need[n][i] -= re[i];
ava[i] -= re[i];
alloc[n][i] +=re[i];
}
return sc(need,alloc,ava,p,r,n);
}

int sc(int need[5][5],int alloc[5][5],int ava[5],int p,int r,int n)


{
int f[5],i,j,k,c,c1=r,d=0,c2=0,com[5];
for(i=0;i<p;i++)
f[i]=0;
while(c1>0)
{
c1=check(need,f,ava,p,r);
if(c1!=0)
{
for(i=0;i<p;i++)
{
if(f[i]==0)
{
c=0;
for(j=0;j<r;j++)
if(need[i][j]<=ava[j])

30
c++;
if(c==r)
{
for(k=0;k<r;k++)
ava[k] += alloc[i][k];
f[i]=1;
d++;
com[c2++]=i;
}
}
}
}
}
if(d==p)
{
if(n==-1)
{
printf("The state is safe \n The safe sequence is");
for(i=0;i<p;i++)
printf("p%d\t",com[i]);
return 1;
}
else if(n==com[0])
{
printf("The state is safe\nThe safe sequence is");
for(i=0;i<p;i++)
printf("p%d\t ",com[i]);

return 1;
}

}
else{
printf("The state is unsafe");
return 0;
}
return -1;
}

int check(int need[5][5],int f[5],int ava[5],int p,int r)


{
int k=0,i,j,c;
for(i=0;i<p;i++)
{
c=0;
if(f[i]==0)
{
for(j=0;j<r;j++)
if(need[i][j] <= ava[j])
c++;

31
if(c==r)
k++;
}
}
return k;
}

void main()
{
int p,r,tn[5][5],tava[5],talloc[5][5],max[5][5],ava[5],alloc[5][5],i,j,need[5][5];
int a,result;
printf("Ente the no.of process and resouces");
scanf("%d%d",&p,&r);
printf("Enter the available resources");
for(i=0;i<r;i++)
scanf("%d",&ava[i]);
printf("Enter the max resources for each process");
for(i=0;i<p;i++)
for(j=0;j<r;j++)
scanf("%d",&max[i][j]);
printf("Enter the allocated matrix");
for(i=0;i<p;i++)
for(j=0;j<r;j++)
{
scanf("%d",&alloc[i][j]);
need[i][j]=max[i][j]-alloc[i][j];
}
printf("\n The need Matrix is \n");
for(i=0;i<p;i++)
{
for(j=0;j<r;j++)
printf("%d",need[i][j]);
printf("\n");
}
for(i=0;i<p;i++)
for(j=0;j<r;j++)
{
tn[i][j]=need[i][j];
tava[i]=ava[i];
talloc[i][j]=alloc[i][j];
}
sc(tn,talloc,tava,p,r,-1);
while(1)
{
printf("\n is there any request of resources(1/0)\n");
scanf("%d",&a);
if(a==1)
{
for(i=0;i<p;i++)
for(j=0;j<r;j++)

32
{
tn[i][j]=need[i][j];
tava[i]=ava[i];
talloc[i][j]=alloc[i][j];
}
result=res(tn,talloc,tava,p,r);
if(result == 1)
printf("\nThe request is granted");
else if(result == -1)
printf("\nThe request cannot be granted\nThe state is unsafe");

else
printf("\nThe resources are not available");
}
else
break;

}
}

CONCLUSION:
Thus the Banker's algorithm for deadlock avoidance has been implemented.

33
EX.NO : 8 DEADLOCK DETECTION

AIM:
To Write a c program to implement Bankers Algorithm for DeadLock Detection

ALGORITHM:

Data Structures for the Deadlock Detection Algorithm

Available : A vector of length m indicates the number of available resources of each type.
Allocation : An n x m matrix defines the number of resources of each type currently allocated
to each process.
Request : An n x m matrix indicates the current request of each process.
If Request [i j ] = k, then process Pi is requesting k more instances of resource type. Rj
.

Dead Lock Detection Algorithm

Step 1 : Let Work and Finish be vectors of length m and n, respectively


Initialize: (a) Work = Available
(b) For i = 1,2, …, n, if Allocationi ≠ 0, then
Finish[i] = false;
otherwise,Finish[i] = true.
Step 2 : Find an index i such that both: (a) Finish[i] == false
(b) Requesti ≤ Work
If no such i exists, go to step 4.
Step 3 : Work = Work + Allocation i Finish[i] = true go to step 2.
Step 4 : If Finish[i] == false, for some i, 1 ≤ i ≤ n, then the system is
in deadlock state.
Moreover, if Finish[i] == false, then Pi is deadlocked.

PROGRAM:
#include<stdio.h>

int check(int need[5][5],int f[5],int ava[5],int p,int r);


void sc(int need[5][5],int alloc[5][5],int ava[5],int p,int r)
{
int f[5],i,j,k,c,c1=r,d=0,c2=0,com[5];
for(i=0;i<p;i++)
f[i]=0;while(c1>0)
{
c1=check(need,f,ava,p,r);

34
if(c1!=0)
{
for(i=0;i<p;i++)
{
if(f[i]==0)
{
c=0;
for(j=0;j<r;j++)
if(need[i][j]<=ava[j])
c++;
if(c==r)
{
for(k=0;k<r;k++)
ava[k]+=alloc[i][k];
f[i]=1;
d++;
com[c2++]=i;
}
}
}
}}
if(d==p)
{
printf("No Deadlock \t");
printf("And the safe sequence is \n");
for(i=0;i<p;i++)
printf("p%d\t",com[i]);
}
else{
printf("Deadlock Detected");
printf("the state is unsafe \n");
}
}
int check(int need[5][5],int f[5],int ava[5],int p,int r)
{
int k=0,i,j,c;
for(i=0;i<p;i++)
{
c=0;
if(f[i]==0)
{
for(j=0;j<r;j++)
if(need[i][j]<=ava[j])
c++;

35
if(c==r)
k++;
}}
return k;
}
void main()
{
int p,r,max[5][5],ava[5],alloc[5][5],i,j,need[5][5];
int a;
printf("Enter the no.of process and resourses \n");
scanf("%d%d",&p,&r);
printf("Enter the available resourses \n");
for(i=0;i<r;i++)
scanf("%d",&ava[i]);
printf("Enter the request matrix \n");
for(i=0;i<p;i++)
for(j=0;j<r;j++)
scanf("%d",&need[i][j]);
printf("Enter the allocation matrix \n");
for(i=0;i<p;i++)
for(j=0;j<r;j++)
scanf("%d",&alloc[i][j]);
sc(need,alloc,ava,p,r);
}

CONCLUSION:

Thus the algorithm for deadlock detection has been implemented.

36
EX.NO : 9 THREADING AND SYNCHRONISATION

AIM:
To write a C program to implement Threading and Synchronisation

ALGORITHM:

Step 1 : Start
Step 2 : Get Pages - Logical memory is broken into fixed - sized blocks.
Step 3 : Get Frames – Physical memory is broken into fixed – sized blocks.
Step 4 : Read page table and logical address
Step 5 : Calculate the physical address using the following Physical address = ( Frame
number * Frame size ) + offset
Step 6 : Display the physical address.
Step 7 : Stop

PROGRAM:

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

void *myThreadFun(void *vargp)


{
sleep(1);
printf("Printing GeeksQuiz from Thread\n");
return NULL;
}

int main()
{
pthread_t tid;
printf("Before Thread\n");
pthread_create(&tid,NULL,myThreadFun,NULL);
pthread_join(tid,NULL);
printf("After Thread\n");
exit(0);
}

CONCLUSION:
Thus,the Threading and Synchronisation applications have been completed.

37
EX.NO : 10 PAGING

AIM:
Write a C program to implement Paging technique of memory Management.

ALGORITHM:
Step 1 : START
Step 2 : Get the Number of pages and Page size
Step 3 :Get the Frame Size
Step 4 :Enter the Page Table Entries
Step 5 :Get the logical Address that Needed to Be Converted Into Physical Address.
Step 6 : By Calculating Index Of page table , Frame Number can be found.
Step 7: Offset and be calculated by off=la%ps.
Step 8: Then Physical Address = (frame size * frame Number)+offset
Step 9 : Then display the Physical Address.
Step 10: END

PROGRAM:
#include<stdio.h>
void main()
{
int i,j,pt[10],np,ps,la,phy,pa,off,fs;
int addr;
int fno,inde;
printf("enter the number of pages and Page size\n");
scanf("%d%d",&np,&ps);
//pa = np * ps;
printf("Enter the frame size :\n");
scanf("%d",&fs);
printf("Enter the page table entries :\n");
for(i=0;i<np;i++)
scanf("%d",&pt[i]);
printf("Enter the logical address :\n");
scanf("%d",&la);
inde = la/ps;
fno = pt[inde];
off=la%ps;
addr = (fs*fno)+off;
printf("The physical address is : %d",addr);
}
CONCLUSION:

Thus,the paging technique of memory management has been implemented.

38
EX.NO : 11 MEMORY ALLOCATION METHOD

AIM:
To write a C program to memory allocation method for first fit,worst fit,best fit.

• First Fit

ALGORITHM:

Step 1 : START
Step 2 : Get the number of block size of each block, Number of processes,size of processes.
Step 3 : From the first block starting from the first process if the size allocated the processes.
Step 4 : Display the processes allocation in the memory block.
Step 5 : END

PROGRAM:
#include<stdio.h>
void main()
{
int frag[10],block[10],process[10],np,nb,i,j;
int p,temp;
printf("\nenter total no of blocks : \n");
scanf("%d",&nb);
printf("\nenter size of each block : \n");
for(i=1;i<=nb;i++)
{
printf("block %d \n: ",i);
scanf("%d",&block[i]);
frag[i]=block[i];
}
printf("\nenter total no of process : \n");
scanf("%d",&np);
printf("\nenter size of each process : \n");
for(i=1;i<=np;i++)
{
printf("process %d \n: ",i);
scanf("%d",&process[i]);
}
printf("\npros_no pros_sz bk_no bk_actual_sz bk_avail_sz fragmentation\n");
for(i=1;i<=np;i++)
{
for(j=1;j<=nb;j++)
{

39
if(frag[j]>process[i])
{
p=j;
break;
}
}
if(frag[p]>process[i])
{
temp=frag[p];
frag[p]=frag[p]-process[i];
printf("\n %d \t %d \t %d \t %d \t\t %d \t %d\n
",i,process[i],p,block[p],temp,frag[p]);
}
else
{
printf("\n %d \t %d \t\t process has to wait \n ",i,process[i]);
}
}
printf("\n");
}

• Worst Fit

ALGORITHM:

Step 1 : START
Step 2 : Get the numbers of blocks and processes size of each block and process.
Step 3 : For each processes,find the largest block available and allocate the process.
Step 4 : Display the process allocation in memory blocks.
Step 5 : END

PROGRAM:
#include<stdio.h>

void main()
{
int frag[10],block[10],process[10],np,nb,i,j;
int max,p,temp;
printf("\nenter total no of blocks : \t");
scanf("%d",&nb);
printf("\nenter size of each block : \n");

40
for(i=1;i<=nb;i++)
{
printf("block %d \t: ",i);
scanf("%d",&block[i]);
frag[i]=block[i];
}
printf("\nenter total no of process : \t");
scanf("%d",&np);
printf("\nenter size of each process : \n");
for(i=1;i<=np;i++)
{
printf("process %d \t: ",i);
scanf("%d",&process[i]);
}

printf("\npros_no pros_sz bk_no bk_actual_sz bk_avail_sz fragmentation");


for(i=1;i<=np;i++)
{
max=frag[1];
p=1;
for(j=1;j<=nb;j++)
{
if(frag[j]>max)
{
max=frag[j];
p=j;
}
}

if(frag[p]>process[i])
{
temp=frag[p];
frag[p]=frag[p]-process[i];
printf("\n %d \t %d \t %d \t %d \t\t %d \t %d" ,i, process[i], p, block[p]
,temp,frag[p]);

}
else
{
printf("\n %d \t\t %d \t\t process has to wait ",i,process[i]);
}

41
printf("\n");
}

• Best Fit

ALGORITHM:

Step 1 : START
Step 2 : Get the number of blocks and processes,size of each block and process.
Step 3 : For each process starting from first block allocate the smallest block which is the
largest for the Allocation.
Step 4 : Display the process allocation in the memory blocks.
Step 5 : END

PROGRAM:

#include<stdio.h>

void main()
{
int frag[10],block[10],process[10],np,nb,i,j,k;
int p,temp,sort[10],fr,pos;
printf("\nenter total no of blocks : \n");
scanf("%d",&nb);
printf("\nenter size of each block : \n");
for(i=1;i<=nb;i++)
{
printf("block %d :\n ",i);
scanf("%d",&block[i]);
frag[i]=block[i];
}
printf("\nenter total no of process : \n");
scanf("%d",&np);
printf("\nenter size of each process : \n");
for(i=1;i<=np;i++)
{
printf("process %d \t: ",i);
scanf("%d",&process[i]);
}
printf("\npros_no pros_sz bk_no bk_actual_sz bk_avail_sz fragmentation\n");
for(i=1;i<=np;i++)

42
{
for(j=1;j<=nb;j++)
{
sort[j]=frag[j];
}

for(j=1;j<=nb-1;j++)
{
p=j;
for(k=j;k<=nb;k++)
{
if(sort[p]>sort[k])
{
p=k;
}
}
if(p!=j)
{
temp=sort[j];
sort[j]=sort[p];
sort[p]=temp;
}
}

for(j=1;j<=nb;j++)
{
if(process[i]<sort[j])
{
fr=sort[j];
break;
}
}

for(j=1;j<=nb;j++)
{
if(fr==frag[j])
{
pos=j;
break;
}
}
if(frag[pos]>process[i])
{
temp=frag[pos];

43
frag[pos]=frag[pos]-process[i];
printf("\n %d \t %d \t %d \t %d \t\t %d \t%d\n
",i,process[i],pos,block[pos],temp,frag[pos]);
}
else
{
printf("\n %d \t\t %d \t\t process has to wait \n ",i,process[i]);
}
}
printf("\n");
}

CONCLUSION:

Thus,the program for memory allocation method-first fit,worst fit,best fit are executed
and the output was verified.

44
EX.NO : 12 PAGE REPLACEMENT

AIM:
Write a C program to implement all page replacement algorithms.
a.FIFO b.LRU c.LFU

• FIFO

ALGORITHM:

Step 1 : START
Step 2 : Read the number of frames.
Step 3 : Read the number of pages.
Step 4 : Initialize the values in frames as -1.
Step 5 : Read the page number(reference string).
Step 6 : Check whether the page is already in a frame
If not,replace the page that is allocation in a frame with new page from queue.
Step 7 : Display the number of page faults.
Step 8: END

PROGRAM:

#include<stdio.h>
void main()
{
int i,p=0,flag=0,num,t,j,pf=0,f,n,pg[50],fr[5];
printf("Enter the total no. of pages and frames");
scanf("%d%d",&n,&f);
printf("Enter the sequence");
for(i=0;i<n;i++)
scanf("%d",&pg[i]);
for(i=0;i<f;i++)
fr[i]=-1;
for(i=0;i<n;i++)
{
flag=0;
num=pg[i];
for(j=0;j<f;j++)
if(fr[j]==num)
{
p++;

45
flag=1;
break;
}

if(flag==0)
{
t=(i-p)%f;
fr[t]=pg[i];
pf++;
}
for(j=0;j<f;j++)
printf("%d\t",fr[j]);
printf("\n");

}
printf("No.of page faults=%d\n No.of page replacement=%d\n",pf,pf-f);
}

• LRU

ALGORITHM:

Step 1 : START
Step 2 : Read the number of frames.
Step 3 : Read the number of pages.
Step 4 : Initialize the values in frames as -1.
Step 5 : Read the page number(reference string).
Step 6 : Check whether the page is already in a frame.
If not then allocated the page in to frames by selecting the page that has not been
used for the longest period of time by counter value.
Step 7 : Display the number of page faults.
Step 8 : END

PROGRAM:

#include<stdio.h>
void main()
{
int i,p=0,flag=0,num,j,pf=0,f=3,n=17,pg[50],fr[5];
int m,u[5];
printf("Enter the total no. of pages and frames");
scanf("%d%d",&n,&f);

46
printf("Enter the sequence");

for(i=0;i<n;i++)
scanf("%d",&pg[i]);
for(i=0;i<f;i++)
{
fr[i]=-1;
u[i]=-1;
}
for(i=0;i<n;i++)
{
flag=0;
num=pg[i];
p=0;
for(j=0;j<f;j++)
{
if(num==fr[j])
{
p=j;
flag=1;
break;
}
}
if(flag==1)
{
u[p]=0;
for(j=0;j<f;j++)
if(j!=p)
u[j]++;
}
if(flag==0)
{
pf++;
if(i<f)
{
fr[i]=num;
u[i]=0;
for(j=0;j<f;j++)
if(j!=i&&u[j]!=-1)
u[j]++;
}
else
{
m=u[0];

47
p=0;
for(j=1;j<f;j++)
if(m<u[j])
{
m=u[j];
p=j;
}

for(j=0;j<f;j++)
if(j!=p)
u[j]++;
u[p]=0;
fr[p]=num;
}
}
for(j=0;j<f;j++)
printf("%d\t",fr[j]);
printf("\n");
}
printf("No.of page faults=%d\n No.of page replacement=%d\n",pf,pf-f);
}

• LFU

ALGORITHM:

Step 1 : START
Step 2: Read the number of frames.
Step 3 : Read the number of pages.
Step 4 : Initialize the values in frames to -1.
Step 5 : Read the page numbers(reference string)
Step 6 : Check whether the page is already in a frame
If not replace the page with the page that is Least recently used.
Step 7 : Display the number of page faults.
Step 8 : END

PROGRAM:

#include<stdio.h>
void main()
{
int i,p=0,flag=0,num,j,pf=0,f=3,n=17,pg[50],fr[5];

48
int m,u[5];
printf("enter the total no. of pages and frames");
scanf("%d%d",&n,&f);
printf("enter the sequence");
for(i=0;i<n;i++)
scanf("%d",&pg[i]);
for(i=0;i<f;i++)
{
fr[i]=-1;
u[i]=-1;
}
for(i=0;i<n;i++)
{
flag=0;
num=pg[i];
p=0;
for(j=0;j<f;j++)
{
if(num==fr[j])
{
u[j]++;
flag=1;
break;
}
}
if(flag==1)
{
u[p]=0;
for(j=0;j<f;j++)
if(j!=p)
u[j]++;
}
if(flag==0)
{
pf++;
if(i<f)
{
fr[i]=num;
u[i]=0;
}
else
{
m=u[0];
p=0;

49
for(j=1;j<f;j++)
if(m>u[j])
{
m=u[j];
p=j;
}

u[p]=0;
fr[p]=num;
for(j=0;j<f;j++)
if(j!=p)
u[j]++;
}
}
for(j=0;j<f;j++)
printf("%d\t",fr[j]);
printf("\n");
}
printf("no.of page faults=%d\nno.of page replacement=%d\n",pf,pf-f);
}

CONCLUSION:

Thus the FIFO,LRU and LFU page replacement algorithms have been
implemented.

50
EX.NO : 13 FILE ORGANIZATION TECHNIQUES

AIM:
To Write a C program to implement all file organisation techniques.
a.Single level b.Two-level c.Hierarchical level d. DAG

• Single level Directory structure

ALGORITHM:
Step 1 : START
Step 2 : Get the number of directories.
Step 3 : For each directory,get directory name,number of files in a directory and all the file
name.
Step 4 : Display all the directories with all its files.
Step 5 : END

PROGRAM:

#include<stdio.h>
struct dir
{
char dname[5];
int no;
char fn[5][10];
}d[5];

void get(int n)
{
int i,j;
for(i=0;i<n;i++)
{
printf("Enter the %d directory name : ",i+1);
scanf("%s",d[i].dname);
printf("\nEnter the no. of files in that directory : ");
scanf("%d",&d[i].no);
for(j=0;j<d[i].no;j++)
{
printf("\nEnter %d file name : ",j+1);
scanf("%s",d[i].fn[j]);
}

}
}

51
void display(int n)
{
int i,j;

for(i=0;i<n;i++)
{
printf("%s\n",d[i].dname);
for(j=0;j<d[i].no;j++)
{
printf("\t%s\n",d[i].fn[j]);
}
}
}

void main()
{
int n;
printf("Enter the no. of directories :\n");
scanf("%d",&n);
get(n);
display(n);
}

• Two level Directory structure

ALGORITHM:

Step 1 : START.
Step 2 : Get the number of use directories.
Step 3 : For each user get the user name,number of directories in a user.
Step 4 : For each directory ,get the directory name number of files in a directory and all file
name.
Step 5 : Display all the user with their directories and its files.
Step 6 : END

PROGRAM:

#include<stdio.h>
struct dir
{
char dname[15];
int no;

52
char fn[5][10];
};

struct us
{
char user[15];
int dn;
struct dir d[5];
}u[5];

void get(int n)
{
int i,j,k;

for(i=0;i<n;i++)
{
printf("Enter the %d user name",i+1);
scanf("%s",u[i].user);
printf("Enter the no. of directories\n");
scanf("%d",&u[i].dn);

for(k=0;k<u[i].dn;k++)
{
printf("Enter the %d directory name",k+1);
scanf("%s",u[i].d[k].dname);
printf("\nEnter the no. of files");
scanf("%d",&u[i].d[k].no);
//printf("%d",u[i].d[k].no);

for(j=0;j<u[i].d[i].no;j++)
{
printf("\nEnter %d file name",j+1);
scanf("%s",u[i].d[k].fn[j]);
// printf("\n%s",u[i].d[k].fn[j]);
}
}
}
}

void display(int n)
{
int i,j,k;
for(k=0;k<n;k++)

53
{
for(i=0;i<u[k].dn;i++)
{
printf("%s>%s>\n",u[k].user,u[k].d[i].dname);
// printf("%d\n",u[k].d[i].no);
for(j=0;j<u[k].d[k].no;j++)
{
printf("\t%s\n",u[k].d[i].fn[j]);
}
if(u[k].dn==0)
printf("%s>",u[k].user);
}
}
}
void main()
{
int n;
printf("Enter the no. of users\n");
scanf("%d",&n);
get(n);
display(n);
}

• Hierarchical Directory Structure

ALGORITHM:

Step 1 : START
Step 2 : Read the number of directories
Step 3 : Repeat
a.Read the names of the directory.
b.Read the sub-directory names.
c.Read the names of sub-sub-directories.
d. Read the size/number of files in the directories.
e. Read the file names.
Step 4 : Display the content of the directory.
Step 5 : END REPEAT
PROGRAM:

#include<stdio.h>
#include<stdlib.h>
int di=0;
struct node
{

54
char N[25];
int df;
struct node *pc;
struct node *ps;
};
struct node *A[20];
int in=0, c=0;

void create(struct node *P, int N)


{
int i;
struct node *Tmp, *T;
Tmp=P;
for(i=0;i<N;i++)
{
T=malloc(sizeof(struct node));
printf("Enter name : ");
scanf("%s", T->N);
printf("Enter user(2) dir(1) or file(0) : ");
scanf("%d", &T->df);
if(T->df==1||T->df==2)
{
A[c]=T;
c++;
}
T->pc=NULL;
T->ps=NULL;
if(i==0)
{
Tmp->pc=T;
Tmp=T;
}
else
{
Tmp->ps=T;
Tmp=T;
}
}
}
void display(struct node *P)
{
int j;
P=P->pc;
do

55
{
if(P->df==2)
{
di=1;
printf("\n%s(%d)",P->N, P->df);
}
else if(P->df==1)
{
printf("\n");
if(di==1)
printf("\t");

else if(j!=di-1)
for(j=0;j<di;j++)
printf("\t");
di++;
j=0;
printf(" %s(%d)-->",P->N, P->df);
}
else
{
printf("%s(%d)\n",P->N, P->df);
for(j=0;j<di-1;j++)
printf("\t");
}
if((P->df==1||P->df==2) && P->pc!=NULL)
display(P);
P=P->ps;
}while(P!=NULL);
di=1;
}
void main()
{
int nu,nc;
int i,j,k;
struct node *Hdr;
Hdr = malloc(sizeof(struct node));
Hdr->df=3;
Hdr->pc=NULL;
Hdr->ps=NULL;
printf("Enter number of users : ");
scanf("%d",&nu);
create(Hdr, nu);
for(in=0;in<c;in++)

56
{
printf("\nEnter number of child nodes for %s : ", A[in]->N);
scanf("%d", &nc);
create(A[in], nc);
}
printf("\nHierarchical\n");
display(Hdr);
}

• DAG

Alogrithm:

1. Start

2. Repeat

a. Get whether the directories or file

b. If file

Get the file name

c. If directory

d. Read the names of the directory.

e. Read the sub directory names

f. Read the names of sub-sub directories

g. Read the size/ number of files in the directory.

h. Read the file names

End Repeat

3. Display the content of the directory

4. Stop

Program

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

struct node

57
{

char N[25];

int df;

struct node *Ptr;

};

struct node *A[20];

int in=0, c=0;

void display()

int i;

struct node *P;

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

P=A[i];

printf("\n%s(%d)",P->N, P->df);

P=P->Ptr;

while(P!=NULL)

printf(" -> %s(%d)",P->N, P->df);

P=P->Ptr;

void DAG()

struct node *T, *P, *Tmp;

int i, j, Flag, nv;

58
for(in=0;in<c;in++)

P=A[in];

printf("\nEnter number of adjacent vertices for %s : ", A[in]->N);

scanf("%d", &nv);

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

T=malloc(sizeof(struct node));

printf("Enter name : ");

scanf("%s", T->N);

printf("Enter dir(1) or file(0) : ");

scanf("%d", &T->df);

T->Ptr=NULL;

P->Ptr=T;

P=T;

if(T->df==1)

Flag=1;

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

if(strcmp(A[j]->N, T->N)==0)

Flag=0;

break;

if(Flag==1)

59
{

Tmp=malloc(sizeof(struct node));

strcpy(Tmp->N, T->N);

Tmp->df = T->df;

Tmp->Ptr=NULL;

A[c]=Tmp;

c++;

void create(int N)

int i;

struct node *T;

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

T=malloc(sizeof(struct node));

printf("Enter name : ");

scanf("%s", T->N);

printf("Enter dir(1) or file(0) : ");

scanf("%d", &T->df);

T->Ptr=NULL;

A[c]=T;

c++;

60
}

void main()

int nu;

printf("Enter number of users : ");

scanf("%d",&nu);

create(nu);

DAG();

printf("\nDAG - Adjacency list representation\n");

display();

CONCLUSION:

Thus the Single level directory,Two level directory and Hierarchical level directory
file organisation techniques has been implemented.

61
EX.NO : 14 FILE ALLOCATION STRATEGIES

AIM:

To Write a C program to implement all the file allocation stategies.


a.Continuous b.Indexed c.Linked

• Continuous Memory Allocation

ALGORITHM:

Step 1: Get the number of files


Step 2: Get the file name, start of the file and length of the File.
Step 3: Check when the required location are free from selected location.
Step 4: Allocate and set flag=1; to the allocated location.
Step 5: Print the file number,length and blocks allocted

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
struct dir
{
char name[10];
int start,length;
}

main()
{
struct dir f[10];
int fa[32],n,st,len,i,j;
int count=0;
for(i=0;i<32;i++)
fa[i]=-1;
printf("Enter no of files to be loaded\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the file name\n");
scanf("%s",f[i].name);
printf("Enter starting block\n");
scanf("%d",&st);

62
printf("Enter length\n");
scanf("%d",&len);
for(j=st;j<(st+len);j++)
{
if(fa[j]==-1)
fa[j]=1;

else
{
printf("Block not empty cannot allocated\n");
exit(0);
}
}
f[i].start=st;
f[i].length=len;
}
printf("\n\n file\t Start\t Length\n");
for(i=0;i<n;i++)
printf("\n%s\t%d\t%d\t",f[i].name,f[i].start,f[i].length);
printf("\n Disk allocation\n");
j=0;
printf("%s\t",f[j].name);
for(i=0;i<32;i++)
{
if(fa[i]==-1)
continue;
printf("%d\t",i);
count++;
if(count==f[j].length&&j<n)
{
printf("\n");
j++;
count=0;
printf("%s\t",f[j].name);
}
}
}

• Indexed Allocation

ALGORITHM:

Step 1: Read the number of files.


Step 2: Read the index file for each file.

63
Step 3: For each file,read the number of blocks occupied and number of blocks of the file.
Step 4: Link all the blocks of the file to the index file.
Step 5: Display the file name,index block and the blocks occupied by the file.

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
struct dir
{
char name[10];
int indexblock;
int ind[8];
}
main()
{
struct dir f[10];
int fa[32],tmp,n,r1,r,len,i,j;
for(i=0;i<32;i++)
fa[i]=-1;
//printf("Create Directory\n");
printf("Enter no of files to be loaded\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter file name\n");
scanf("%s",f[i].name);
printf("Enter No. of blocks\n");
scanf("%d",&len);
while(1)
{
r=rand()%32;
if(fa[r]==-1)
{
fa[r]=-10;
f[i].indexblock=r;
for(j=0;j<8;j++)
f[i].ind[j]=-1;
tmp=0;
break;
}
}
while(1)
{

64
r=rand()%32;
if(fa[r]==-1)
{
fa[r]=i;
f[i].ind[tmp]=r;
tmp++;
if(tmp==len)
break;
}
}
}
printf("\n\nfile\t Index block\n");
for(i=0;i<n;i++)
printf("\n%s\t%d",f[i].name,f[i].indexblock);
//printf("\n\n\n indexblock");
for(i=0;i<n;i++)
{
printf("\n\n index block%d\n",f[i].indexblock);
for(j=0;j<8;j++)
printf("\t%d",f[i].ind[j]);
}
}

• Linked Allocation

ALGORITHM:

Step 1: Read the number of files.


Step 2: For each file;read the name,starting block,number of blocks and block numbers of the
file.
Step 3: Start from the starting block and link each block of the file to the new block in a
linked list fashion.
Step 4: Display the file name,starting block,size of the file and the blocks occupied by the
file.

PROGRAM:

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

65
struct dir
{
char name[10] ;
int Start ;
int len;
}F[10];

void main()
{
int f[32], t, n, r1, r, i , j ;
for(i=0; i<32; i++)
f[i]=-1;
printf ("\nEnter number of files to be loaded : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf ("\nEnter File name : ") ;
scanf("%s",F[i].name);
printf ("\nEnter number of blocks : ");
scanf("%d",&F[i].len);
t=0;

while(t!=F[i].len)
{
r=rand( )%32;
if(f[r]==-1)
{
if(t==0)
{
F[i].Start=r;
r1=r;
t++;
}
else
{
f[r1]=r;
r1=r;
t++;
}
}
}
f[r1]=-1;
}

66
printf ("\n\nFile\tStart \n");
for(i=0; i<n; i++)
printf ("\n%s\t%d", F[i].name, F[i].Start);
printf ("\n\n\nDisk allocation\n");
for(i=0; i<32; i++)
{
if(f[i] !=-1)
printf ("\n%d\t%d", i, f[i]);
}
printf("\n");

for(j=0;j<n;j++)
{
printf("%s:",F[j].name);
t=0;
i=F[j].Start;
while(t!=F[j].len)
{
printf("%d ",i);
t++;
i=f[i];
}
printf("\n");
}
}

CONCLUSION:
Thus, the sequential,indexed and linked file allocation strategies have been
implemented.

67
EX NO:15 DISK SCHEDULING ALGORITHM

AIM:
To Write a C program to implement disk scheduling algorithm.

• FCFS

ALGORITHM:

1. Let 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. Let us one by one take the tracks 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];
distance = fabs(head - cur_track);
seek_count += distance;
head = cur_track;
}
printf("Total number of seek operations: %d\n",seek_count);
printf("Seek Sequence is\n");
for (int i = 0; i < size; i++) {
printf("%d\n",arr[i]);
}
}
int main()
{
int arr[8] = { 176, 79, 34, 60, 92, 11, 41, 114 };
int head = 50;
FCFS(arr,head);
return 0;
}

68
• SSTF

ALGORITHM:

1. Let 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)
{

69
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;
}

• SCAN

ALGORITHM:

1. Let 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. Let 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>
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");

70
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;
}
}
}

71
for(i=1,j=0;j<temp1;i++,j++)
queue[i]=queue1[j];
queue[i]=max;
queue[i+1]=0;
for(i=temp1+3,j=0;j<temp2;i++,j++)
queue[i]=queue2[j];
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;
}

• C-SCAN

ALGORITHM:

1. Let 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. The head services only in the right direction from 0 to the size of the disk.
3. While moving in the left direction do not service any of the tracks.
4. When we reach the beginning(left end) reverse the direction.
5. While moving in the right direction it services all tracks one by one.
6. While moving in the right direction calculate the absolute distance of the track from the
head.
7. Increment the total seek count with this distance.
8. Currently serviced track position now becomes the new head position.
9. Go to step 6 until we reach the right end of the disk.

10.If we reach the right end of the disk reverse the direction and go to step 3 until all tracks in
the request array have not been serviced

72
PROGRAM:

#include <stdio.h>

int request[50];

int SIZE;

int pre;

int head;

int uptrack;

int downtrack;

struct max{

int up;

int down;

} kate[50];

int dist(int a, int b){

if (a > b)

return a - b;

return b - a;

void sort(int n){

int i, j;

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

for (j = 0; j < n - i - 1; j++){

if (request[j] > request[j + 1]){

int temp = request[j];

request[j] = request[j + 1];

request[j + 1] = temp;

73
}

j = 0;

i = 0;

while (request[i] != head){

kate[j].down = request[i];

j++;

i++;

downtrack = j;

i++;

j = 0;

while (i < n){

kate[j].up = request[i];

j++;

i++;

uptrack = j;

void scan(int n){

int i;

int seekcount = 0;

printf("SEEK SEQUENCE = ");

sort(n);

74
if (pre < head){

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

printf("%d ", head);

seekcount = seekcount + dist(head, kate[i].up);

head = kate[i].up;

for (i = downtrack - 1; i > 0; i--){

printf("%d ", head);

seekcount = seekcount + dist(head, kate[i].down);

head = kate[i].down;

else{

for (i = downtrack - 1; i >= 0; i--){

printf("%d ", head);

seekcount = seekcount + dist(head, kate[i].down);

head = kate[i].down;

for (i = 0; i < uptrack - 1; i++){

printf("%d ", head);

seekcount = seekcount + dist(head, kate[i].up);

head = kate[i].up;

printf(" %d\nTOTAL DISTANCE :%d", head, seekcount);

75
}

int main(){

int n, i;

printf("ENTER THE DISK SIZE :\n");

scanf("%d", &SIZE);

printf("ENTER THE NO OF REQUEST SEQUENCE :\n");

scanf("%d", &n);

printf("ENTER THE REQUEST SEQUENCE :\n");

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

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

printf("ENTER THE CURRENT HEAD :\n");

scanf("%d", &head);

request[n] = head;

request[n + 1] = SIZE - 1;

request[n + 2] = 0;

printf("ENTER THE PRE REQUEST :\n");

scanf("%d", &pre);

scan(n + 3);

CONCLUSION:

Thus the disk scheduling algorithm was executed successfully.

76
EX.NO:16 INSTALLATION OF LINUX USING VMWARE

AIM:
To study the installation of LINUX using VMWARE

PROCEDURE :

1.If you are installing the guest operating system from an installer disc, configure the virtual
machine to use a physical CD-ROM or DVD drive and configure the drive to connect at
power on.
a.Select the virtual machine and select Virtual Machine > Virtual Machine Settings.
b.On the Hardware tab, select CD/DVD drive.
c.Select Connect at power on.
d.Select Use physical drive and select a the drive.
e.Click OK to save your changes.
2.If you are installing the guest operating system from an ISO image file, configure the
CD/DVD drive in the virtual machine to point to the ISO image file and configure the drive
to connect at power on.
a.Select the virtual machine and select Virtual Machine > Virtual Machine Settings.
b.On the Hardware tab, select CD/DVD drive.
c.Select Connect at power on.
d.Select Use ISO image file and browse to the location of the ISO image file.
e.Click OK to save your changes.
3.If you are installing the guest operating system from an installer disc, insert the disc in the
CD-ROM or DVD drive.
4.Power on the virtual machine.
5.Follow the installation instructions provided by the operating system vendor.
6.If the operating system consists of multiple installer discs and you are prompted to insert
the next disc, insert the next disc in the physical drive.
7.If the operating system consists of multiple ISO image files, select the image file for the
next CD.
a.Select Virtual Machine > Removable Devices > CD/DVD > Disconnect and disconnect
from the current ISO image file..
b.Select Virtual Machine > Removable Devices > CD/DVD > Settings and select the
next ISO image file.
c.Select Connected and click OK.
8.Use the standard tools in the operating system to configure its settings.

CONCLUSION:

Thus the installation of LINUX using VMWARE has been completed successfully.

77
78

You might also like