You are on page 1of 128

EXPERIMENT-1

Experiment: 1
Shell
programming
a. Identify the command to print the home directory of each user.
b. Develop an interactive grep script that asks for a word and a file name and then finds the
number of occurrences of that word in the file.
c. Write a shell script that takes a command line argument and reports on whether it is
directory, a file, or something else.
d. Write a shell script that determines the period for which a specified user is working on the
system.
e. Write an interactive file-handling shell program. Let it offer the user the choice of copying,
removing, renaming, or linking files. Once the user has made a choice, have the program ask
the user for the necessary information, such as the file name, new name and so on.
f. Write a shell script that displays a list of all the files in the current directory to which the user
has read, write and execute permissions.

a.)
COD
E:
#!/bin/
sh

echo "Home Directory is:"; echo


$HOME
b.)
#!/bin/
sh
echo "Enter file name with extension:"; read file;
echo "Enter word to be counted:"; read word;
grep -o $word $file | wc -l;

c.)
echo "Enter arguement:"; read
PASSED;
if [ -d "${PASSED}" ] ;
then
echo "$PASSED is a directory"; else
if [ -f "${PASSED}" ];
then
echo "${PASSED} is a file"; else
echo "${PASSED} is not valid"; exit 1
fi
OUTPUT:

d.)
t1=`who | grep "$1" | tr -s " " | cut -d " " -f 5 | cut -d ":" -f 1 ` t2=`who | grep "$1" | tr -s " " | cut -d " " -f 5
| cut -d ":" -f 2 ` t1=`expr $t1 \* 60 `
min1=`expr $t1 + $t2`
d1=`date +%H` d2=`date
+%M` d1=`expr $d1 \* 60`
min2=`expr $d1 + $d2`
sub=`expr $min2 - $min1` p=`expr
$min2 - $min1` p=`expr $p / 60`
p1=`expr $min2 - $min1` p1=`expr
$p1 % 60`
echo " The user $1 has been working since : $pr Hrs $pr1 minutes "
OUTPUT:

e.)
COD
E:
while true
do
echo "*******MENU*********"
echo "
1. List of files.
2. Copying files.
3. Removing files.
4. Renaming files.
5. Linking files. press
[CTRL+C] TO EXIT"
echo "enter your choice "; read
ch;
case "$ch" in 1 )
echo "The list of file names." ls -l || echo
"These are file";;
2 ) echo "Enter the old filename." read ofile
echo "Enter the new file name." read nfile
cp $ofile $nfile && echo "Copied sucessfully." || echo
"Copied is not possible." ;;
3 ) echo "Enter the file name to remove." read rfile
rm -f $rfile && echo "Successfully removed." ;;
4 ) echo "Enter the old file name." read ofile
echo "Enter the new file name." read nfile
mv $ofile $nfile && echo "The file $ofile name renamed to
$nfile." || echo "You can't Rename the file.".;;
5 ) echo "Enter the original filename." read ofile
echo "Enter the new filename to link a file."
read lfileln $ofile $lfile && echo "Creat the linking file Sccessfully." ||
echo "You can't Link the file.";;
*)
echo "Invalid option."
echo " Enter correct choice." esac
done
OUTPUT:
f.)
CODE:
echo "List of Files which have Read, Write and Execute Permissions in Current
Directory"
for file in * do
if [ -r $file -a -w $file -a -x $file ] then
echo $file fi
done
EXPERIMENT-2
ITE2002-(OPERATING
SYSTEM LAB) SLOT-L41+L42
SUBMITTED BY- ASHISH RAJ
(16BIT0138) SUBMITTED TO-
PROF. SHASHIKIRAN V.

Experiment 2
Program to illustrate various methods for process and thread handling
a. Assume that you have given a complex program that contains large number of
instructions. The program takes more time to execute if it is executed as a single
thread of execution. Analyze the role of the system calls given below and
restructure the program using it, so that the execution time of the program can be
minimized considerably. Fork(), exec(), getpid(), exit(), wait(), close(), stat(),
opendir(), readdir().
b. Programs using the I/O system calls of UNIX operating system (open, read,
write, etc)
c. Program to create processes, child processes and orphan process.
d. Program to create a thread to find the factorial of a natural number n.
e. The Collatz conjecture concerns what happens when we take any positive
integer n and apply the following algorithm:
n = n/2, if n is even
n = 3 n + 1, if n is odd
The conjecture states that when this algorithm is continually applied, all positive
integers will eventually reach 1. For example, if n = 35, the sequence is 35, 106,
53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1.Write a C program using the fork () system
call that generates this sequence in the child process. The starting number will be
provided from the command line. For example, if 8 is passed as a parameter on the
command line, the child process will output 8, 4, 2, 1. Because the parent and child
processes have their own copies of the data, it will be necessary for the child to
output the sequence. Have the parent invoke the wait () call to wait for the child
process to complete before exiting the program. Perform necessary error checking
to ensure that a positive integer is passed on the command line.
a. Assume that you have given a complex program that contains large number of
instructions. The program takes more time to execute if it is executed as a single
thread of execution. Analyze the role of the system calls given below and
restructure the program using it, so that the execution time of the program can be
minimized considerably. Fork(), exec(), getpid(), exit(), wait(), close(), stat(),
opendir(), readdir().
Fork()-
#include<stdio.h>
int main(void)
{
int fork(void),value;
value=fork();
printf("main:value =%d\n",value);
return 0;
}
Exec()-
#include<stdio.h>
main()
{
int pid;
char *args[ ]={"/bin/ls","-l",0};
printf("\nParent Process");
pid=fork();
if(pid==0)
{
execv("/bin/ls",args);
printf("\nChild process");
}else
{
wait();
printf("\nParent process");
exit(0);

}
Getpid()-
#include<stdio.h>
int main()
{
int pid;
pid=getpid();
printf("process ID is %d\n",pid);
pid=getppid();
printf("parent process ID id %d\n",pid);
}

Wait() & Exit()-


perror(fork failed);
exit(0);
}
else if(pid==0)
{
printf(\n Child process starts);
for(i=0; i<5; i++)
{
printf(\n Child process %d is called, i);
}
printf(\n Child process ends);
}
else
{
wait(0);
printf(\n Parent process ends);
}exit(0);}
OUTPUT:
close()-
#include<stdio.h>
#include <fcntl.h>
int main()
{
int fd1 = open("foo.txt", O_RDONLY);
if (fd1 < 0)
{
perror("c1");
}
printf("opened the fd = % d\n", fd1);

if (close(fd1) < 0)
{
perror("c1");
}
printf("closed the fd.\n");
}
stat()-

#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
int main(void)
{
char *path,path1[10];
struct stat *nfile;
nfile=(struct stat *) malloc (sizeof(struct stat));
printf("enter name of file whose stsistics has to");
scanf("%s",path1);
stat(path1,nfile);
printf("user id %d\n",nfile->st_uid);
printf("block size :%d\n",nfile->st_blksize);
printf("last access time %d\n",nfile->st_atime);
printf("time of last modification %d\n",nfile->st_atime);
printf("porduction mode %d \n",nfile->st_mode);
printf("size of file %d\n",nfile->st_size);
printf("number of links:%d\n",nfile->st_nlink);
}
Wait,fork,exec-
b. Programs using the I/O system calls of UNIX operating system (open, read,
write, etc)

opendir(),readdir()-

#include<stdio.h>
#include<dirent.h>
struct dirent *dptr;
int main(int argc,char *argv[])
{
char buff[256];
DIR *dirp;
printf("\n\nEnter directory name");
scanf("%s",buff);
if((dirp=opendir(buff))==NULL)
{
printf("Error");
exit(1);
}
while(dptr=readdir(dirp))
{
printf("%s\n",dptr->d_name);
}
}

closedir(dirp);
}
b. Programs using the I/O system calls of UNIX operating system used:

1. open( )
2. read( )
3. write( )
4.close.

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>

#define BUF_SIZE 8192

int main(int argc, char* argv[]) {

int input_fd, output_fd;


ssize_t ret_in, ret_out;
char buffer[BUF_SIZE];

if(argc != 3){
printf ("Usage: cp file1 file2");
return 1;
}

input_fd = open (argv [1], O_RDONLY);


if (input_fd == -1) {
perror ("open");
return 2;
}

output_fd = open(argv[2], O_WRONLY | O_CREAT, 0644);


if(output_fd == -1){
perror("open");
return 3;
}

while((ret_in = read (input_fd, &buffer, BUF_SIZE)) > 0){


ret_out = write (output_fd, &buffer, (ssize_t) ret_in);
if(ret_out != ret_in){
/* Write error */
perror("write");
return 4;
}
}

close (input_fd);
close (output_fd);

return (EXIT_SUCCESS);
}
c. Program to create processes, child processes and orphan process.
Child process:
#include <stdio.h>

main ()

int pid;

printf ("I'm the original process with PID %d and PPID %d.\n", getpid (), getppid
());

pid = fork ();

if (pid != 0)

printf ("I'm the parent process with PID %d and PPID %d.\n", getpid (),
getppid());

printf ("My child's PID is %d\n", pid);

else

printf ("I'm the child process with PID %d and PPID %d.\n", getpid
(),getppid());

printf ("PID %d terminates.\n", getpid ());

}
Orphan process:

#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int pid = fork();
if (pid > 0)
printf("In parent process\n");
else if (pid == 0)
{
sleep(30);
printf("In child process\n");
}
return 0;
}

d. Program to create a thread to find the factorial of a natural number n.

#include<stdio.h>

#include<pthread.h>

void* threadFunction(void* args)


{

int mul=1,i,n;

printf("Enter the value: ");

scanf("%d",&n);

for(i=n;i>0;i--)

mul=mul*i;

printf("The Factorial is: %d",mul);

void main()

pthread_t id;

int ret,mul=1,i,n;

ret=pthread_create(&id,NULL);

if(ret==0)

scanf("%d",&n);

for(i=n;i>0;i--)

mul=mul*i;
}

printf("The Factorial is: %d",n);

else

printf("Thread not created.\n");

}
e. The Collatz conjecture concerns what happens when we take any positive
integer n and apply the
following algorithm:
n = n/2, if n is even
n = 3 n + 1, if n is odd
The conjecture states that when this algorithm is continually applied, all positive
integers will eventually reach 1. For example, if n = 35, the sequence is 35, 106,
53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1.
Write a C program using the fork () system call that generates this sequence in the
child process. The starting number will be provided from the command line. For
example, if 8 is passed as a parameter on the command line, the child process will
output 8, 4, 2, 1. Because the parent and child processes have their own copies of
the data, it will be necessary for the child to output the sequence. Have the parent
invoke the wait () call to wait for the child process to complete before exiting the
program. Perform necessary error checking to ensure that a positive integer is
passed on the command line.

#include <stdio.h>

int main()

int number = 0;

int pid,status;

printf("Please enter a number \n");

scanf("%d", &number);

if(number < 0)

{
printf("Please enter a positive number, greather than 0 \n");

scanf("%d", &number);

pid = fork();

if(pid < 0)

printf(" Unsuccessful to create Child Process \n");

exit(-1);

else if(pid == 0)

do

if(number%2 != 0)

number = (number*3)+1;

else if(number%2 == 0)

{
number = number/2;

printf("%d \n",number);

}while(number != 1);

else

printf("pid %d \n",pid);

printf("Waiting on child process to finish \n");

wait(&status);

return 0;

}
EXPERIMENT-1
ITE2002-(OPERATING
SYSTEM LAB) SLOT-L41+L42
SUBMITTED BY- ASHISH RAJ
(16BIT0138) SUBMITTED TO-
PROF. SHASHIKIRAN V.

a. Assume that two processes named client and server running in the system. It is
required that these two processes should communicate with each other using
shared memory concept. The server writes alphabets from a..z to the shared
memory .the client should read the alphabets from the shared memory and
convert it to AZ. Write a program to demonstrate the above mentioned
scenario.

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

/* We'll name our shared memory segment "5678". */


key = 5678;

/* Create the segment. */

if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) <


0) { perror("shmget");
exit(1);
}

/* Now we attach the segment to our data space. */

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


1) { perror("shmat");
exit(1);
}
/* Now put some things into the memory for the other process to read. */ s
= shm;
for (c = 'a'; c <= 'z'; c++)
*s++ = c;
*s = NULL;

/* Finally, we wait until the other process converts a..z to 'A..Z', indicating that it has read what
we put there. */

while (*shm !=
'*') sleep(1);
exit(0);
}

CODE FOR CLIENT:


#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHMSZ 27
main()
{
int shmid;
key_t key;
char *shm, *s;
/* We need to get the segment named "5678", created by the server. */
key = 5678;
/* Locate the segment. */
if ((shmid = shmget(key, SHMSZ, 0666)) <
0) { perror("shmget");
exit(1);
}
/* * Now we attach the segment to our data space. */ if
((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
/* Now read what the server put in the memory. */
for (s = shm; *s != NULL; s++)
putchar(*s);
putchar('\n');

/* Finally, change the segment to 'AZ', indicating we have read the segment. */

int i;
for (i=65;i<91;i++)
{*shm=(char)i
; shm++;}
exit(0);
}
EXPERIMENT-4
ITE2002-(OPERATING
SYSTEM LAB) SLOT-L41+L42
SUBMITTED BY-
ASHISH RAJ Reg. No.-
16BIT0138)
SUBMITTED TO- PROF. SHASHIKIRAN V.

Consider a corporate hospital where we have n number of patients waiting for consultation.
The amount of time required to serve a patient may vary, say 10 to 30 minutes. If a patient
arrives with an emergency, he /she should be attended immediately before other patients,
which may increase the waiting time of other patients. If you are given this problem with the
following algorithms how would you devise an effective scheduling so that it optimizes the
overall performance such as minimizing the waiting time of all patients. [Single queue or
multi-level queue can be used].
Consider the availability of single and multiple doctors
Assign top priority for patients with emergency case, women, children, elders, and youngsters.
Patients coming for review may take less time than others. This can be taken into account
while using SJF.
a. FCFS
b. SJF (primitive and non-pre-emptive )

FCFS

#include <stdio.h>

int wt[10],bt[10],at[10],tat[10],n;

float awt,atat;

void input(){

printf("Enter Number of patients:");

scanf("%d",&n);

int i;

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

+)

printf("Enter Burst Time of process

%d:",i+1); scanf("%d",&bt[i]);
printf("Enter Arrival Time of process

%d:",i+1); scanf("%d",&at[i]);

void

calculate(){

wt[0]=0;

atat=tat[0]=bt[0];

int btt=bt[0];

int i;

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

wt[i]=btt-at[i];

btt+=bt[i];

awt+=wt[i];

tat[i]=

wt[i]+bt[i];

atat+=tat[i];

atat/=n;

awt/=n;

void

display(){ int

i;

printf("SR.\tA.T.\tB.T.\tW.T.\tT.A.T.\n"

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

{
printf("%3d\t%3d\t%3d\t%3d\t%4d\n",i+1,at[i],bt[i],wt[i],tat[i]);

printf("Average Waiting Time: %f\nAverage Turn Around Time:%f",awt,atat);

int main(){

input();

calculate();

display();

return 0;

SJF (primitive and non-pre-emptive )


Primitive

#include<stdio.h>

#include<stdbool.h>

typedef struct

int pid;

float at,wt,bt,ta,st;

bool isComplete;

}process;

void procdetail(int i,process p[])

printf("Patient id: ");

scanf("%d",&p[i].pid);

printf("Arrival Time: ");

scanf("%f",&p[i].at);

printf("Burst Time(visit time):

"); scanf("%f", &p[i].bt);

p[i].isComplete=false;

}//procdetail

void sort(process p[],int i,int start)

int k=0,j;

process temp;
for(k=start;k<i;k++)

for(j=k+1;j<i;j++)

if(p[k].bt<p[j].bt) continue;

else

temp=p[k]; p[k]=p[j]; p[j]=temp;

}//sort int

main()

printf("SJF PRE EMPTIVE ALGORITHM\n\n");

int n,i,k=0,j=0;

float avgwt = 0.0,avgta=0.0,tst=0.0;

printf("Enter number of patients: ");

scanf("%d",&n);

process p[n];

for

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

printf("\nEnter patient %d's details: \n",i);


procdetail(i,p);

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

if (p[i].isComplete == true)

continue; else

k=i; while(p[i].at<=tst&&i<n)

i++; sort(p,i,k); i=k;

if(p[i].at<=tst)

p[i].st=tst; else p[i].st=p[i].at; p[i].st=tst;

p[i].isComplete=true; tst+=p[i].bt; p[i].wt=p[i].st-p[i].at;

p[i].ta=p[i].bt+p[i].wt; avgwt+=p[i].wt; avgta+=p[i].ta;

avgwt/=n; avgta/=n;

printf("Patient Schedule Table: \n");

printf("\tPatient ID\tArrival Time\tVisit time\tWait Time\tTurnaround Time\n"); for (i = 0;


i<n; i++) printf("\t%d\t\t%f\t%f\t%f\t%f\n",p[i].pid,p[i].at,p[i].bt,p[i].wt

,p[i].ta); printf("\nAverage wait time: %f",avgwt);

printf("\nAverage turnaround time: %f\n",avgta); return 0;

}
Non-preemptive

#include<stdio.h>

int main()

printf("//SJF NON-PRE EMPTIVE

ALGORITHM//\n\n"); printf("16BIT0138-ashish\n");

int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;

printf("Enter number of patients:");

scanf("%d",&n);

printf("\nEnter Burst Time(visit time):\n");

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

printf("p%d:",i+1);

scanf("%d",&bt[i])

; p[i]=i+1;

//sorting burst time in ascending order using selection sort for(i=0;i<n;i++)

pos=i;

for(j=i+1;j<n;j+

+)

if(bt[j]<bt[pos]) pos=j;

temp=bt[i];

bt[i]=bt[pos];

bt[pos]=temp;

temp=p[i];

p[i]=p[pos];

p[pos]=temp;

}
wt[0]=0; //waiting time for first process will be zero

//calculate waiting time for(i=1;i<n;i++)

wt[i]=0; for(j=0;j<i;j++) wt[i]+=bt[j]; total+=wt[i];}

avg_wt=(float)total/n; //average waiting time total=0;

printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");

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

tat[i]=bt[i]+wt[i];

total+=tat[i];

printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);

avg_tat=(float)total/n; //average turnaround time printf("\n\nAverage Waiting


Time=%f",avg_wt); printf("\nAverage Turnar

ound Time=%f\n",avg_tat);

}
EXPERIMENT-5
ITE2002-(OPERATING
SYSTEM LAB) SLOT-L41+L42
SUBMITTED BY-
ASHISH RAJ Reg. No.-
16BIT0138
SUBMITTED TO- PROF. SHASHIKIRAN V.
Apply the following algorithms for the above case and determine the variations in the
resulting parameters.
a. Priority
b. Round robin.

a. Priority

#include<stdio.h>

int main()

int at[10],bt[10],rt[10],endTime,i,smallest;

int remain=0,n,time,sum_wait=0,sum_turnaround=0;

printf("Enter no of Processes : ");

scanf("%d",&n)

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

printf("Enter arrival time for Process P%d :

",i+1); scanf("%d",&at[i]);

printf("Enter burst time for Process P%d :

",i+1); scanf("%d",&bt[i]);

rt[i]=bt[i];

printf("\n\nProcess\t|Turnaround Time| Waiting Time\n\n");


rt[9]=9999;

for(time=0;remain!=n;time++)

smallest=9;

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

+)

if(at[i]<=time && rt[i]<rt[smallest] && rt[i]>0)

smallest=i;

rt[smallest]--;

if(rt[smallest]==0

remain++;

endTime=time+1;

printf("\nP[%d]\t|\t%d\t|\t%d",smallest+1,endTime-at[smallest],endTime-bt[smallest]-at[smallest]);

sum_wait+=endTime-bt[smallest]-at[smallest];

sum_turnaround+=endTime-at[smallest];

printf("\n\nAverage waiting time = %f\n",sum_wait*1.0/n);

printf("Average Turnaround time = %f",sum_turnaround*1.0/5);

return 0;

}
b. Round robin.

#include<stdio.h>

int main()

int i,j,n,time,sum_wait=0,sum_turnaround=0,smallest;

int at[10],bt[10],pt[10],rt[10],remain;

printf("Enter no of Processes : ");

scanf("%d",&n);

remain=n;

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

+)

{
printf("Enter arrival time, burst time and priority for process p%d :",i+1);

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

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

scanf("%d",&pt[i])

; rt[i]=bt[i];

pt[9]=11;

printf("\n\nProcess\t|Turnaroundtime|waiting time\n");

for(time=0;remain!=0;time++)

smallest=9;

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

+)

if(at[i]<=time &&pt[i]<pt[smallest] &&rt[i]>0)

smallest=i;

rt[smallest]--;

if(rt[smallest]==0

remain--;

printf("P[%d]\t|\t%d\t|\t%d\n",smallest+1,time+1-at[smallest],time+1-at[smallest]-bt[smallest]);

sum_wait+=time+1-at[smallest];

sum_turnaround+=time+1-at[smallest]-bt[smallest];
}

printf("\nAvg waiting time = %f\n",sum_wait*1.0/n);

printf("Avg turnaround time = %f",sum_turnaround*1.0/n);

return 0;

}
EXPERIMENT-6
ITE2002-(OPERATING
SYSTEM LAB) SLOT-L41+L42
SUBMITTED BY- ASHISH RAJ
(16BIT0138) SUBMITTED TO-
PROF. SHASHIKIRAN V.

a. Write a program to calculate the below mentioned parameters and write your inference on
implementing future knowledge algorithm [which starts scheduling only after fixed amount of
time, even if processes have arrived]. Suppose that the following processes arrive for execution
at the times indicated. Each process will run for the amount of time listed. [use non pre- emptive
scheduling ] Process Arrival Time Burst Time

P1 0.0 8

P2 0.4 4

P3 1.0 1

b. Calculate the average turnaround time for these processes with the FCFS and SJF scheduling
algorithm.

c. The SJF algorithm is supposed to improve performance, but notice that we chose to run
process P1 at time 0 because we did not know that two shorter processes would arrive soon.
Compute what the average turnaround time will be if the CPU is left idle for the first 1 unit and
then SJF scheduling is used. Remember that processes P1 and P2 are waiting during this idle
time, so their waiting time may increase. [This type of algorithm is called as future knowledge
algorithm].

d. Consider a system running ten I/O-bound tasks and one CPU-bound task. Assume that the
I/O-bound tasks issue an I/O operation once for every millisecond of CPU computing and that
each I/O operation takes 10 milliseconds to complete. Also assume that the context-switching
overhead is 0.1 Milli second and that all processes are long-running tasks. Write a program to
calculate the CPU utilization for a round-robin scheduler when:

The time quantum is 1 millisecond The time quantum is 10 milliseconds


SJF

#include<stdio.h>

int p[30],bt[30],tot_tat=0,wt[30],n,tot_wt=0,tat[30],SJF_wt=0,SJF_tat=0;

float awt,avg_tat,avg_wt;

int swap(int *a, int *b)

int t;

t = *a;

*a = *b;

*b = t;

return 0;

int sort()

int t,i,j;

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

+)

for(j=i+1;j<n;j++)

if(bt[i]>bt[j])

swap(&bt[j],&bt[i]);

swap(&p[j],&p[i]);

}
}

return 0;

int WT_TAT(int *a, int *b)

int i;

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

+)

if(i==0)

tat[i] =

bt[i]; else

tat[i] = tat[i-1] + bt[i];

tot_tat=tot_tat+tat[i];

*a = tot_tat;

wt[0]=0;

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

wt[i]=wt[i-1]+bt[i-1];

tot_wt = tot_wt+wt[i];

*b = tot_wt;
printf("\nPROCESS\t\tBURST TIME\tTURN AROUND TIME\tWAITING TIME");

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

printf("\nprocess[%d]\t\t%d\t\t%d\t\t%d",p[i]+1,bt[i],tat[i],wt[i]);

return 0;

int main()

int i;

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

scanf("%d",&n);

printf("Enter burst time for each process\n");

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

scanf("%d",&bt[i])

; p[i] = i;

sort();

WT_TAT(&SJF_tat,&SJF_

wt);

printf("\n\nTotal Turn around Time:%d",SJF_tat);

printf("\nAverage Turn around Time :%d ",

SJF_tat/n); printf("\nTotal Waiting

Time:%d",SJF_wt); printf("\nTotal avg. Waiting

Time:%d",SJF_wt/n); return 0;

}
FCFS

#include<stdio.h>

int p[30],bt[30],tot_tat=0,wt[30],n,tot_wt=0,tat[30],FCFS_wt=0,FCFS_tat=0;

float awt,avg_tat,avg_wt;

int WT_TAT(int *a, int

*b); int main()

int i;

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

scanf("%d",&n);

printf("Enter burst time for each process\n");


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

scanf("%d",&bt[i])

; p[i] = i;

printf("\n FCFS Algorithm \n");

WT_TAT(&FCFS_tat,&FCFS_

wt);

printf("\n\nTotal Turn around Time:%d",FCFS_tat);

printf("\nAverage Turn around Time :%d ",

FCFS_tat/n); printf("\nTotal Waiting

Time:%d",FCFS_wt); printf("\nTotal avg. Waiting

Time:%d",FCFS_wt/n); return 0;

int WT_TAT(int *a, int *b)

int i;

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

+)

if(i==0)

tat[i] =

bt[i]; else

tat[i] = tat[i-1] + bt[i];

tot_tat=tot_tat+tat[i];

}
*a = tot_tat;

wt[0]=0;

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

wt[i]=wt[i-1]+bt[i-1];

tot_wt = tot_wt+wt[i];

*b = tot_wt;

printf("\nPROCESS\t\tBURST TIME\tTURN AROUND TIME\tWAITING TIME");

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

{printf("\nprocess[%d]\t\t%d\t\t%d\t\t%d",p[i],bt[i],tat[i],wt[i]);}

return 0;

b. The average turnaround time for these processes with the FCFS scheduling algorithm
P1 arrives and starts executing at 0.0 and terminates at 8, thus turnaround time is (8-0.0) = 8
P2 arrives at 0.4, starts executing at time 8 and terminates at 12, thus turnaround time is (12-
0.4) = 11.6
P3 arrives at 1.0, starts executing at 12 and terminates at 13, and thus has a turnaround time is
(13-1)=12.
Average turnaround time = (8 + 11.6 + 12)/3 = 10.53

The average turnaround time for these processes with the SJF (no preemption)
scheduling algorithm
P1 arrives and starts executing at time 0.0 and terminates at 8, thus the turnaround time is (8- 0)
= 8.
P2 arrives at 0.4, starts executing at 9 (after P3 has executed), and terminates at 13, thus the
turnaround time is (13-0.4) = 12.6.
P3 arrives at 1.0, starts executing at 8 and terminates at 9, thus the turnaround time is (9-1) = 8.
Average turnaround time = (8+12.6+8)/3 = 9.53
c.
Remember that the CPU is left idle for the first 1 time unit.
P1 arrives time 0.0, starts executing at 6 (after P2 and P3 have executed) and terminates at 14, thus
the turnaround time is (14-0) = 14.
P2 arrives at 0.4, starts executing at 2.0 (after P3 has executed), and terminates at 6, thus the
turnaround time is (6-0.4) = 5.6.
P3 arrives at 1.0, starts executing at 1 (it has the shortest burst and starts executing first) and
terminates at 2, thus the turnaround time is (2-1) = 1.
Average turnaround time = (14+5.6+1)/3 = 6.87

d.
#include<stdio.h>
int TRUE = 0;
int FALSE = -1;
int tbt[30],bt[30],tat[30],n=0,wt[30],qt=0,tqt=0,time=0,lmore,t_tat=0,t_wt=0;
int main()
{
int i,j;

printf("\nEnter no. of processors:");


scanf("%d",&n);
printf("\nEnter Quantum Time:");
scanf("%d",&qt);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time of Processor[%d]:",i+1);
scanf("%d",&bt[i]);
tbt[i] = bt[i];
wt[i] = tat[i] = 0;

}
lmore = TRUE;
while(lmore ==
TRUE)
{
lmore =
FALSE;
for(i=0;i<n;i+
+)
{
if(bt[i] != 0)
wt[i] = wt[i] + (time -
tat[i]); tqt = 1;
while(tqt <= qt && bt[i] !=0)
{
lmore =
TRUE; bt[i] =
bt[i] -1;
tqt++;
time++;
tat[i] = time;
}
}
}
printf("\nProcessor ID\tBurstTime\tTurnAroundTime\tWaitingTime\n");
for(i=0;i<n;i++)
{
printf("Processor%d\t\t%d\t\t%d\t\t%d\n",i+1,tbt[i],tat[i],wt[i]);
t_tat = t_tat + tat[i];
t_wt = t_wt + wt[i];
}
printf("\nTotal Turn Around Time:%d",t_tat);
printf("\nAverage Turn Around Time:%d",t_tat/n);
printf("\nTotal Waiting Time:%d",t_wt);
printf("\nAverage Waiting Time:%d",t_wt/n);
return 0;
}
It will favor the I/O-bound programs because of the relatively short CPU burst request by them;
however, the CPU-bound programs will not starve because the I/O-bound programs will
relinquish the CPU relatively often to do their I/O. If the number of I/O processes is sufficiently
large to keep at least one I/O bound process in the ready queue, the CPU-bound process will be
starved.

(a) The time quantum is 1 millisecond: Irrespective of which process is scheduled, the scheduler
incurs a 0.1 millisecond context-switching cost for every context-switch. This results in a CPU
utilization of 1/1.1 * 100 = 91%.

(b) The time quantum is 10 milliseconds: The I/O-bound tasks incur a context switch after using
up only 1 millisecond of the time quantum. The time required to cycle through all the processes
is therefore 10*1.1 + 10.1 (as each I/O-bound task executes for 1 millisecond and then incur the
context switch task, whereas the CPU-bound task executes for 10 milliseconds before incurring a
context switch). The CPU utilization is therefore 20/21.1 * 100 = 94%.
EXPERIMENT-7
ITE2002-(OPERATING
SYSTEM LAB) SLOT-L41+L42

SUBMITTED BY-
ASHISH RAJ Reg. No.-
16BIT0138
SUBMITTED TO- PROF. SHASHIKIRAN V.
EXP-7

Many CPU-scheduling algorithms are parameterized. For example, the RR


algorithm requires a parameter to indicate the time slice. Multilevel feedback
queues require parameters to define the number of queues, the scheduling
algorithm for each queue, the criteria used to move processes between queues,
and so on.
These algorithms are thus really sets of algorithms (for example, the set of RR
algorithms for all time slices, and so on). One set of algorithms may include
another (for example, the FCFS algorithm is the RR algorithm with an infinite
time quantum). What (if any) relation holds between the following pairs of
algorithm sets? Implement the below mentioned algorithms for the data given
below and determine the efficiency of each algorithm.

1. Priority and SJF


2. Multilevel feedback queues and FCFS
3. Priority and FCFS
4. RR and SJF
The relation between above algorithms
1. The shortest job has the highest priority.
2. The lowest level of MLFQ is FCFS.
3. FCFS gives the highest priority to the job having been in existence the
longest.
4. None.
CODE:-
FFCS
#include<stdio.h>
main()
{
int sum=0,sum1=0,stt,bt[10],a[10],wt[10],tat[10],i,n;
float awt,atat;
printf("Enter the number of processes\n");
scanf("%d",&n);

for(i=1;i<=n;i++)
{
printf("Enter the burst time for process %d\n",i);
scanf("%d",&bt[i]);
}
stt=0;
for(i=1;i<=n;i+
+)
{
a[i]=stt+bt[i];
wt[i]=stt;
tat[i]=wt[i]+bt[i];
sum=sum+wt[i];
sum1=sum1+tat[i];
stt=a[i];
}
printf("Total waiting time is %d\n",sum);
printf("Total turn around time is %d\n",sum1);
awt=(float)sum/n;
atat=(float)sum1/n;
printf("Average waiting time is %f\n",awt);
printf("Average turn around time is %f\n",atat);
}
SJF
#include<stdio.h>
int main()
{
int p[10],bt[10],wt[10],t[10],totwt,totat,n,i,j,cur[10],temp[10],tembt[10];
float avgwt,avgtat;
printf("enter the no.of process\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter process id\n");
scanf("%d",&p[i]);
printf(" enter burst time \n");
scanf("%d",&bt[i]);
}
printf("processid\t\t burst time\n");
for(i=0;i<n;i++)
{
printf("%d\t\t%d\t\n",p[i],bt[i]);
}
for(j=0;j<n-1;j++)
{
for(i=0;i<n-1;i++)
{
if(bt[i]>bt[i+1])
{
temp[i]=p[i];
p[i]=p[i+1];
p[i+1]=temp[i];
tembt[i]=bt[i];
bt[i]=bt[i+1];
bt[i+1]=tembt[i];
}
}
}
totwt=0;
avgwt=0;
totat=0;
avgtat=0;
cur[0]=0;
wt[0]=0;
t[0]=bt[0];
for(i=1;i<n;i++)
{
wt[i]=wt[i-1]+bt[i-1];

totwt=totwt+wt[i];
t[i]=wt[i]+bt[i];
totat=totat+t[i];
}
avgwt=(float)totwt/n;
avgtat=(float)totat/n;
printf("The total waiting time is %d\n",totwt);
printf("The total turn around time is %d\n",totat);
printf(" The average waiting time is %f\n",avgwt);
printf(" The average turnaround time is %f\n",avgtat);
}
Round Robin
#include<stdio.h>
#define MAX
50 main()
{
int i,n,m,j=0;
int b[20],b1[20],f[20],w[20];
int start=0,finish=0,total=0,t;
float aw=0.0,at=0.0;
printf("Enter the no. of process");
scanf("%d",&n);
printf("Enter the time quantum");
scanf("%d",&t);
for(i=1;i<=n;i++)
{
printf("Enter the burst time of the process[i]");
scanf("%d",&b[i]);
b1[i]=b[i];
total=total+b[i];
}
start=0;
while (j<total)
{
for(i=1;i<=n;i++)
{
if(b[i]==0
)
continue;
if(b[i]>t)
{
finish=start+t;
j=j+t;
start=finish;
b[i]=b[i]-t;
}
else
{
finish=start+b[i]
; j=j+b[i];
start=finish;
f[i]=finish;
b[i]=0;
w[i]=finish-b1[i];
}
}
}
printf("\n\nProcess No\tbursttime\t WaitingTime\t TurnAroundTime");
for(i=1;i<=n;i++)
{
printf("\n\np%d\t\t%3d\t\t%3d\t\t%3d",i,b1[i],w[i],f[i]);
aw=aw+w[i];
at=at+f[i];
}
aw=aw/(float)n;
at=at/(float)n;
printf("\n Average Waiting Time : %0.2f",aw);
printf("\n Average Turn Around Time : %0.2f
",at);
}

Priority
#include<stdio.h>

int main()
{
int bt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_tat;
printf("Enter Total Number of Process:");
scanf("%d",&n);
printf("\nEnter Burst Time and Priority\n");
for(i=0;i<n;i++)
{
printf("\nP[%d]\n",i+1);
printf("Burst Time:");
scanf("%d",&bt[i]);
printf("Priority:");
scanf("%d",&pr[i]);
p[i]=i+1; //contains process number
}

//sorting burst time, priority and process number in ascending order using selection sort
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(pr[j]<pr[pos])
pos=j;
}

temp=pr[i];
pr[i]=pr[pos];
pr[pos]=temp;

temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;

temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}

wt[0]=0; //waiting time for first process is zero

//calculate waiting time


for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}

avg_wt=total/n; //average waiting time


total=0;

printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");


for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculate turnaround time
total+=tat[i];
printf("\nP[%d]\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}

avg_tat=total/n; //average turnaround time


printf("\n\nAverage Waiting Time=%d",avg_wt);
printf("\nAverage Turnaround Time=%d\n",avg_tat);

return 0;
}
EXPERIMENT-9
ITE2002-(OPERATING
SYSTEM LAB) SLOT-L41+L42

SUBMITTED BY-
ASHISH RAJ Reg. No.-
16BIT0138
SUBMITTED TO- PROF. SHASHIKIRAN V.

1
Experiment 8
A. Write a program to find the Fibonacci series using multi-threaded concept.

B. Write a multithreaded program that calculates various statistical values for a


list of numbers. This program will be passed a series of numbers on the
command line and will then create three
separate worker threads. One thread will determine the average of the numbers,
the second will
determine the maximum value, and the third will determine the minimum value.
For example,

suppose your program is passed the integers


90 81 78 95 79 72 85
The program will report
The average value is 82
The minimum value is 72
The maximum value is 95
The variables representing the average, minimum, and maximum values will be
stored globally. The worker threads will set these values, and the parent thread
will output the values once the workers have exited.

PART A

CODE:

#include<stdio.h>
#include<pthread.h>
void* fibonacci(void*);
int n;
void* fibonacci(void* arg)
{
int c, first = 0, second = 1, next;
for ( c = 0 ; c <n; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;

2
second = next;
}
printf(%d\n,next);
}
}
Int main()
{
pthread_t t;
printf("Enter the number of terms: ");
scanf(%d\n,&n);
printf("First %d terms of Fibonacci series are :- ",n);
pthread_create (&t , NULL , fibonacci,(void*)&n);
return 0;
}

PART B

CODE:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#define handle_error_en(en, msg)
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

volatile int running_threads = 0;


pthread_t thread[3];
int numOfElements;
struct Results{
int min;
int max;
int average;
}Results;

3
void *findMin(void *array_ptr){
int i;
int *elements = (int*)array_ptr;
Results.min = elements[0];
for(i = 0; i < numOfElements; i++){
if(elements[i] < Results.min){
Results.min = elements[i];
}
}
running_threads -= 1;
return NULL;
}

void *findMax(void *array_ptr){


int i;
int *elements = (int*)array_ptr;
for(i = 0; i < numOfElements; i++){
if(elements[i] > Results.max){
Results.max = elements[i];
}
}
running_threads -= 1;
return NULL;
}

void *findAverage(void *array_ptr){


int i;
int *elements = (int*)array_ptr;
for(i = 0; i < numOfElements; i++){
Results.average += elements[i];
}
Results.average = Results.average/numOfElements;
running_threads -= 1;
return NULL;
}
int getArrayInput(int n, int *array_ptr){
int input;
int numberOfElements = 0;
printf("Creating Dynamic Array...\n-\n");
for(;;){
printf("Enter a positive value:\nNegative Number to Stop\n-\n");
if (scanf("%d",&input) != 1){

4
printf("\nOops that wasn't an Integer\nlets try filling the
array again\nRemember INTEGERS only!\n");
exit(EXIT_FAILURE);
}
if (input >= 0){
if (numberOfElements == n){
n += 1;
array_ptr = realloc(array_ptr, n * sizeof(int));
}
array_ptr[numberOfElements++] = input;
} else {
printf("\nNumber of Integers: %d\n", numberOfElements);
break;
}
}
return numberOfElements;
}

void joinThreads(int numberOfThreads){


int i;
int s;
while(numberOfThreads >= 0){
s = pthread_join(thread[numberOfThreads], NULL);
if (s != 0){
handle_error_en(s, "pthread_create");
}
numberOfThreads--;
}
}
void createThreads(int *array_ptr){
int s;
s = pthread_create(&thread[0], NULL, findMin, (void *)array_ptr);
if (s != 0){
handle_error_en(s, "pthread_create");
}
running_threads += 1;
s = pthread_create(&thread[1], NULL, findMax, (void *)array_ptr);
if (s != 0){
handle_error_en(s, "pthread_create");
}
running_threads += 1;
s = pthread_create(&thread[2], NULL, findAverage, (void *)array_ptr);
if (s != 0){

5
handle_error_en(s, "pthread_create");
}
running_threads += 1;
}
int main()
{
int n = 1;
int *array_ptr = malloc(n * sizeof(int));
numOfElements = getArrayInput(n, array_ptr);
createThreads(array_ptr);
while(running_threads>0){
sleep(1);
}
joinThreads(2);
printf("\nThe average is %d\nThe maximum is %d\nThe minimum is
%d\n",Results.average, Results.max, Results.min);
return(0);
}

6
7
EXPERIMENT-9
ITE2002-(OPERATING
SYSTEM LAB) SLOT-L41+L42

SUBMITTED BY-
ASHISH RAJ Reg. No.-
16BIT0138
SUBMITTED TO- PROF. SHASHIKIRAN V.
EXP-9
A pair of processes involved in exchanging a sequence of integers. The
number of integers that can be produced and consumed at a time is
limited to 100. Write a Program to implement the producer and
consumer problem using POSIX semaphore for the above scenario.

CODE:
#include<stdio.h>
#include<semaphore.h>
#include<sys/types.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>

int shmid; // for storing return value from shmget; declaring globally so that each
thread function can access it without needing to pass it as arg

sem_t semaphore;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; // one mutex for
client as well as producer so that reading/writing is in synchronization and no race
condtion occurs in accessing the counter of buffer

int buffer*100+,buff_counter=0;

void *consumer_thread(void *arg)


,
do
,
/*first wait, and then lock the mutex. doing otherwise will create a deadlock in
case when semaphore=0*/

sem_wait(&semaphore);
pthread_mutex_lock(&mutex);
printf("Consumer consumed:\t%d\n",buffer*--buff_counter+);
pthread_mutex_unlock(&mutex);
sleep(1);
-while(buff_counter>0); //do while so that if buffer is yet to be filled, still
consumers can enter

return NULL;
-

void *producer_thread(void *arg)


,
pthread_mutex_lock(&mutex);
buffer*buff_counter+=rand()%100;
printf("Producer produced:\t%d\n",buffer*buff_counter+++);
sem_post(&semaphore);
int gf=0;
sem_getvalue(&semaphore,&gf);
//printf("hahaha:%d \n\n",gf);
pthread_mutex_unlock(&mutex); // once the mutex is unlocked any thread
(consum/prod) may lock it

return NULL;
-

int main(int argc,char **argv)


,
//int gf=0;
sem_init(&semaphore,0,0);
//sem_getvalue(&semaphore,&gf);
//printf("haha: %d\n\n",gf);

int i,num_prod=101,num_consum=101; //assigning any random number>100 to


both so that the two loops which follow immediately can run

for(;num_prod>100;)
,
puts("Enter the number of producer threads(<=100): ");
scanf("%d",&num_prod);
-
for(;num_consum>100;)
,
puts("Enter the number of consumer threads(<=100): ");
scanf("%d",&num_consum);
-

pthread_t producer_id*num_prod+, consumer_id*num_consum+;

for(i=0;i<num_prod;i++)
pthread_create(&producer_id*i+,NULL,producer_thread,NULL);

for(i=0;i<num_consum;i++)
pthread_create(&consumer_id*i+,NULL,consumer_thread,NULL);

for(i=0;i<num_prod;i++)
pthread_join(producer_id*i+,NULL);

for(i=0;i<num_consum;i++)
pthread_join(consumer_id*i+,NULL);

return 0;

-
EXPERIMENT-10
ITE2002-(OPERATING
SYSTEM LAB) SLOT-
L41+L42

SUBMITTED BY-
ASHISH RAJ Reg. No.-
16BIT0138
SUBMITTED TO- PROF. SHASHIKIRAN V.
EXP-10
a) Write a Program to implement the solution for dining philosophers problem.
Code-
#include<stdio.h>

#include<pthread.h>

#include<stdlib.h>

#include<unistd.h>

pthread_mutex_t mutex_fork[5];
// 5 mutexes for each fork

pthread_key_t phil_num;

void *philosopher_func(void *arg)

{
//printf("%d\n",*((int*)arg));

pthread_setspecific(phil_num,arg);

printf("Philosopher %d is thinking.\n",*(int*)pthread_getspecific(phil_num));

sleep(3);

/*philosopher number phi_no will now pick up two forks.*/

pthread_mutex_lock(&mutex_fork[*(int*)pthread_getspecific(phil_num)]);

pthread_mutex_lock(&mutex_fork[(*(int*)pthread_getspecific(phil_num)+1)%5]);

printf("Philosopher %d is eating.\n",*(int*)pthread_getspecific(phil_num));

sleep(2);

pthread_mutex_unlock(&mutex_fork[*(int*)pthread_getspecific(phil_num)]);

pthread_mutex_unlock(&mutex_fork[(*(int*)pthread_getspecific(phil_num)+1)%5]);

printf("Philosopher %d finished eating.\n",*(int*)pthread_getspecific(phil_num));

return NULL;
}
int main(int argc,char **argv)

{
pthread_t thread_philosopher[5];
pthread_key_create(&phil_num,NULL)
;

int*

i=(int*)malloc(sizeof(int)); int

j;

for(j=0;j<5;j++)
pthread_mutex_init(&mutex_fork[j],NULL
);

for(j=0,*i=j;j<5;i++,j++,*i=j)

{
//printf("%d\n",i);

pthread_create(&thread_philosopher[j],NULL,philosopher_func,(void*)i);
}

for(j=0;j<5;j++)
pthread_mutex_destroy(&mutex_fork[j]);
// freeing the space occupied by mutex

for(j=0;j<5;j++)
pthread_join(thread_philosopher[j],NULL)
;

return 0;
}
b. Servers can be designed to limit the number of open connections. For example, a
server may wish to have only N socket connections at any point in time. As soon as
N connections are made, the server will not accept another incoming connection
until an existing connection is released. Write a program to illustrate how
semaphores can be used by a server to limit the number of concurrent connections
CODE:
USING COUNTING SEMAPHORES:
#include <stdio.h>
#include<stdlib.h
> int wait(int s)
{
if(s==0)
printf("Reached maximum number of connections!\n");
else
{s--;
printf("Connection acquired\n");}
return s;
}
int signal(int s)
{
s++
;
printf("Connection released\n");
return s;
}
void main()
{
int n,choice;
printf("Enter the number of open connections: ");
scanf("%d",&n);
printf("\nWhat do you wish to do? \n1) Request a connection \n2) Terminate a
connection \n3) Exit\n");
while(1)
{
printf("\nEnter choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
n=wait(n);
break;
case 2 :
n=signal(n)
; break;
case 3 :
printf("Program terminated\n");
exit(0);
}
}
}
USING BOUNDED BUFFER:
CODE:
#include<stdio.h>
#include<stdlib.h>
int
mutex=1,full=0,empty=3,conn=0;
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return(++s);
}
void acquire()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
conn++;
printf("Server Acquires Socket Connection
%d\n",conn); mutex=signal(mutex);
}
void release()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("Server Releases Socket Connection %d\n",conn);
conn--;
mutex=signal(mutex);
}
int main()
{
int N;
printf("Enter Number of Open Connections N: 3\n");
int n;
void
acquire();
void release();
int wait(int);
int signal(int);
printf("\n1.Acquire Socket Connection\n2.Release Socket Connection\n3.Exit");
while(1)
{
printf("\nEnter your choice: ");
scanf("%d",&n);
switch(n)
{
case 1:
if((mutex==1)&&(empty!=0))
acquire();
else
printf("\nN Socket Connections Already Acquired!: RELEASE
CONNECTIONS TO CONTINUE\n");
break;
case 2:
if((mutex==1)&&(full!=0))
release();
else
printf("\nNo Socket Connections Made Currently!: ACQUIRE
CONNECTIONS TO CONTINUE\n");
break;
case 3:
printf("Terminate\n");
exit(0);
break;
}
}
return 0;
}
EXPERIMENT-11
ITE2002-(OPERATING
Experiment: 11 SYSTEM LAB)
a. Write a Program to implement bankers algorithm for Deadlock avoidance
CODE:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int Max[10][10], need[10][10], alloc[10][10], avail[10], completed[10], safeSequence[10]; int
p, r, i, j, process, count;
count = 0;
printf("Enter the no of processes : ");
scanf("%d", &p);
for(i = 0; i< p; i++)
completed[i] = 0;
printf("\n\nEnter the no of resources : ");
scanf("%d", &r);
printf("\n\nEnter the Max Matrix for each process : ");
for(i = 0; i < p; i++)
{
printf("\nFor process %d : ", i + 1);
for(j = 0; j < r; j++)
scanf("%d", &Max[i][j]);
}
printf("\n\nEnter the allocation for each process : ");
for(i = 0; i < p; i++)
{
printf("\nFor process %d : ",i + 1);
for(j = 0; j < r; j++)
scanf("%d", &alloc[i][j]);
}
printf("\n\nEnter the Available Resources : ");
for(i = 0; i < r; i++)
scanf("%d", &avail[i]);
for(i = 0; i < p; i++)

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


need[i][j] = Max[i][j] - alloc[i][j];
do
{
printf("\n Max matrix:\tAllocation matrix:\n");

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


{
for( j = 0; j < r; j++)
printf("%d ", Max[i][j]);
printf("\t\t");
for( j = 0; j < r; j++)
printf("%d ", alloc[i][j]);
printf("\n");
}
process = -1;
for(i = 0; i < p; i++)
{
if(completed[i] == 0)//if not completed
{
process = i ;
for(j = 0; j < r; j++)
{
if(avail[j] < need[i][j])
{
process = -1;
break;
}
}
}
if(process != -1)
break;
}
if(process != -1)
{
printf("\nProcess %d runs to completion!", process + 1);
safeSequence[count] = process + 1;
count++;
for(j = 0; j < r; j++)
{
avail[j] += alloc[process][j];
alloc[process][j] = 0;
Max[process][j] = 0;
completed[process] = 1;
}
}
}
while(count != p && process != -1);
if(count == p)
{
printf("\nThe system is in a safe state!!\n");
printf("Safe Sequence : < ");
for( i = 0; i < p; i++)
printf("%d ", safeSequence[i]);
printf(">\n");
}
else
printf("\nThe system is in an unsafe state!!");
}
b) Consider the following snapshot of a system:
Allocation Max A
BCD ABC
D
P0 3 0 1 4 5117
P1 2 2 1 0 3211
P2 3 1 2 1 3321
P3 0 5 1 0 4612
P4 4 2 1 2 6325
Using the bankers algorithm, determine whether or not each of the following states is
unsafe. If the state is safe, illustrate the order in which the processes may complete.
Otherwise, illustrate why the state is unsafe.
a. Available = (0, 3, 0, 1)
b. Available = (1, 0, 0, 2)
CODE:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int Max[10][10], need[10][10], alloc[10][10], avail[10], completed[10], safeSequence[10]; int
p, r, i, j, process, count;
count = 0;
printf("Enter the no of processes : ");
scanf("%d", &p);
for(i = 0; i< p; i++)
completed[i] = 0;
printf("\nEnter the no of resources : ");
scanf("%d", &r);
printf("\nEnter the Max Matrix for each process : ");
for(i = 0; i < p; i++)
{
printf("\nFor process %d : ", i + 1);
for(j = 0; j < r; j++)
scanf("%d", &Max[i][j]);
}

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


for(i = 0; i < p; i++)
{
printf("\nFor process %d : ",i + 1);
for(j = 0; j < r; j++)
scanf("%d", &alloc[i][j]);
}
printf("\n\nEnter the Available Resources : ");
for(i = 0; i < r; i++)
scanf("%d", &avail[i]);
for(i = 0; i < p; i++)
for(j = 0; j < r; j++)
need[i][j] = Max[i][j] - alloc[i][j];
do
{
printf("\n Max matrix:\tAllocation matrix:\n");
for(i = 0; i < p; i++)
{
for( j = 0; j < r; j++)
printf("%d ", Max[i][j]);
printf("\t\t");
for( j = 0; j < r; j++)
printf("%d ", alloc[i][j]);
printf("\n");
}
process = -1;

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


{
if(completed[i] == 0)//if not completed
{
process = i ;
for(j = 0; j < r; j++)
{
if(avail[j] < need[i][j])
{
process = -1;
break;
}
}
}
if(process != -1)
break;
}
if(process != -1)
{
printf("\nProcess %d runs to completion!", process + 1);
safeSequence[count] = process + 1;
count++;
for(j = 0; j < r; j++)
{
avail[j] += alloc[process][j];
alloc[process][j] = 0;
Max[process][j] = 0;
completed[process] = 1;
}
}
}
while(count != p && process != -1);

if(count == p)
{
printf("\nThe system is in a safe state!!\n");
printf("Safe Sequence : < ");
for( i = 0; i < p; i++)
printf("%d ", safeSequence[i]);
printf(">\n");
}
else
printf("\nThe system is in an unsafe state!!\n");
}
a) Available = (0, 3, 0, 1) b) Available = (1, 0, 0, 2)
EXPERIMENT-12
ITE2002-(OPERATING
Experiment: SYSTEM LAB)
12
Consider a memory hole of size 1kb initially. When a sequence of memory request
arrives as following, illustrate the memory allocation by various approaches and
calculate the total amount memory wasted by external fragmentation and internal
fragmentation in each approach.
a. First fit;
b. Best fit
c. Worst fit
Best Fit & First Fit
#include<stdio.h>
#include<stlib.h
> int main()
{
int ns,np,i,j,count,temp1,temp2;
int segments[10],request[10],flag[10],position[10];
printf("\nEnter the number of Page segments:");
scanf("%d",&ns);
for(i=0;i<ns;i++)
{
printf("\nEnter the Size of page segment%d:",(i+1));
scanf("%d",&segments[i]);
flag[i]=0;
position[i]=(i+1)
;
}
printf("\nEnter the number of Process:");
scanf("%d",&np);
for(i=0;i<np;i++)
{
printf("\nEnter the Size of required by segment%d:",(i+1));
scanf("%d",&request[i]);
}
printf("MEMORY MANAGEMENT ALGORITHMS");
printf("\n\nSize of page Segments");
for(i=0;i<ns;i++)
printf("\nPage%d:%d",(i+1),segments[i]);
printf("\n\nSize of page Segments
REQUESTED"); for(i=0;i<np;i++)
printf("\nProcess P%d:%d",(i+1),request[i]);
printf("\n\nFIRST FIT MEMORY MANAGEMENT ALOGRITH:");
printf("\n\nPROCESS ARE ALLOCATED AS FOLLOWS:");
if(np<=ns)
{
for(i=0;i<np;i++)
{
count=0;
while(count<ns)
{
if(segments[count]>=request[i] && flag[count]==0)
{
printf("\nThe process p%d is allocated to partision:%d and space left in the
partition:%d",(i+1),(count+1),(segments[count]-request[i]));
flag[count]=1;
break;
}
count++;
}
if(count==ns)
printf("\nThere is no page available of size process p%d to allocate!!!!",(i+1));
}
}
else
{
printf("\nThe number of requried pages is more than number of pages available");
}
printf("\n\nBest FIT MEMORY MANAGEMENT ALOGRITH:");
printf("\n\nPROCESS ARE ALLOCATED AS FOLLOWS:");
for(i=0;i<ns;i++)
{
flag[i]=0;
for(j=0;j<ns;j++
)
{
if(segments[i]<segments[j])
{
temp1=segments[i];
segments[i]=segments[j];
segments[j]=temp1;

temp2=position[i];
position[i]=position[j]
; position[j]=temp2;
}
}
}
if(np<=ns)
{
for(i=0;i<np;i++)
{
count=0;
while(count<ns)
{
if(segments[count]>=request[i] && flag[count]==0)
{
printf("\nThe process p%d is allocated to partision:%d and space left in the
partition:%d",(i+1),position[count],(segments[count]-request[i]));
flag[count]=1;
break;
}
count++;
}
if(count==ns)
printf("\nThere is no page available of size process p%d to allocate!!!!",(i+1));
}
}
else
{
printf("\nThe number of requried pages is more than number of pages available");
}
return 0;
}

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

int main()
{
int ns,np,i,j,count;
int segments[10],request[10],flag[10];
printf("\nEnter the number of Page segments:");
scanf("%d",&ns);

for(i=0;i<ns;i++)
{
printf("\nEnter the Size of page segment%d:",(i+1));
scanf("%d",&segments[i]);
flag[i]=0;
}

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


scanf("%d",&np);

for(i=0;i<np;i++)
{
printf("\nEnter the Size of required by segment%d:",(i+1));
scanf("%d",&request[i]);
}

printf("\n\nWORST FIT MEMORY MANAGEMENT ALOGRITH:");

printf("\n\nSize of page Segments");


for(i=0;i<ns;i++)
printf("\nPage%d:%d",(i+1),segments[i])
;

printf("\n\nSize of page Segments


REQUESTED"); for(i=0;i<np;i++)
printf("\nProcess P%d:%d",(i+1),request[i]);

printf("\n\nPROCESS ARE ALLOCATED AS

FOLLOWS:");

if(np<=ns)
{

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

while(count<ns)
{

if(segments[count]>=request[i] && flag[count]==0)


{
printf("\nThe process p%d is allocated to partision:%d and space left in the
partition:%d",(i+1),count,(segments[count]-request[i]));
flag[count]=1;
break;
}

count++;
}
if(count==ns)
printf("\nThere is no page available of size process p%d to allocate!!!!",(i+1));
}
}

else
{
printf("\nThe number of requried pages is more than number of pages available");
}

return 0;

}
EXPERIMENT-13
ITE2002-(OPERATING SYSTEM LAB)
Experiment: 13
Write a program to implement the page replacement algorithms.
a. FIFO
b. LRU
c. OPT
CODE:
#include<stdio.h>
void FIFO();
void LRU();
void OPTIMAL();

int main()
{
int ch;
do
{
printf("\n\n\t1.FIFO\n\t2.LRU\n\t3.Optimal\n\t4.Exit\n\tEnter Choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
FIFO(
);
break;
case 2:
LRU()
;
break;
case 3:
OPTIMAL();
break;
}
}while(ch!=4);
}
void FIFO()
{
int frame[3]={-1,-1,-
1},ref[20],cnt=0,i,j,no,flag; float
ratio,hitcnt=0.00;
printf("\n\tEnter length of reference string : ");
scanf("%d",&no);
printf("\n\tEnter reference String with giving space ....\n\t");
for(i=0;i<no;i++)
scanf("%d",&ref[i]);
//printf("\n\tExecution is started here .....");
for(i=0;i<no;i++)
{
flag=0;
for(j=0;j<3;j++)
if(frame[j]==ref[i]
)
{
printf("\n\tPage Hit ");
hitcnt++;
flag=1
;
break;
}

if(flag==0)
{
printf("\n\tPage Miss");
printf("\tBefore :\t");
for(j=0;j<3;j++)
printf("
%d",frame[j]);
frame[cnt]=ref[i];
cnt++;
if(cnt>=3
) cnt=0;
printf("\tAfter :\t");
for(j=0;j<3;j++)
printf("
%d",frame[j]);
}
}
ratio=hitcnt/no;
printf("\n\n\tHit ratio = %f ",ratio);
}
void LRU()
{
int frame[3]={-1,-1,-1},used[3]={-1,-1,-
1},cnt=0,ref[20],i,j,flag,no,index,value; float ratio,hitcnt=0;
printf("\n\tEnter length of reference string : ");
scanf("%d",&no);
printf("\n\tEnter reference String with giving space \n\t");
for(i=0;i<no;i++)
scanf("%d",&ref[i]);
//printf("\n\tExecution is started here ");
for(i=0;i<no;i++)
{
flag=0;
for(j=0;j<3;j++)
if(frame[j]==ref[i]
)
{
printf("\n\tPage Hit ");
hitcnt++;
flag=1;
used[j]=cnt;
break;
}
if(flag==0)
{
printf("\n\tPage Miss");
printf("\tBefore :");
for(j=0;j<3;j++)
printf(" %d",frame[j]);
//selection of victim for replacement
index=0;
value=used[0];
if(cnt!=0) {
for(j=0;j<3;j+
+)
if(value>used[j]&&value!=used[j])
{
index=j;
value=used[j];
}
}
//printf("\tVictim is %d ",index);
frame[index]=ref[i];
used[index]=cnt;
printf("\tAfter :");
for(j=0;j<3;j++)
printf("
%d",frame[j]);
}
cnt++;
}
ratio=hitcnt/no;
printf("\n\n\tHit ratio = %f ",ratio);
}
void OPTIMAL()
{
int frame[3]={-1,-1,-1},used[3]={-1,-1,-
1},cnt=0,ref[20],i,j,flag,no,val1,val2,val3,index; float ratio,hitcnt=0;
printf("\n\tEnter length of reference string : ");
scanf("%d",&no);
printf("\n\tEnter reference String with giving space \n\t");
for(i=0;i<no;i++)
scanf("%d",&ref[i]);
//printf("\n\tExecution is started here ");
for(i=0;i<no;i++)
{
flag=0;
for(j=0;j<3;j++)
if(frame[j]==ref[i]
)
{
flag=1;
printf("\n\tPage Hit");
hitcnt++;
break;
}
if(flag==0)
{
printf("\n\tPage Miss");
if(cnt<3)
{
frame[cnt]=ref[i];
printf("\tStatus :");
for(j=0;j<3;j++)
printf("
%d",frame[j]); cnt++;
}
else
{
printf("\tBefore :");
for(j=0;j<3;j++)
printf("
%d",frame[j]);
//selection of victim
val1=frame[0];
flag=0;
for(j=i;j<no;j++)
if(ref[j]==val1)
{
val1=j
;
flag=1
;
break;
}
if(flag==0)
val1=no;
val2=frame[1];
flag=0;
for(j=i;j<no;j+
+)
if(ref[j]==val2)
{
val2=j
;
flag=1
;
break;
}
if(flag==0)
val2=no;
val3=frame[2];
flag=0;
for(j=i;j<no;j+
+)
if(ref[j]==val3)
{
val3=j
;
flag=1
;
break;
}
if(flag==0)
val3=no;
if(val1<val2
)
if(val3<val2
) index=1;
else
index=2;
else
if(val3<val1
)
index=0;
else
index=2;

frame[index]=ref[i]
; printf("\tAfter :");
for(j=0;j<3;j++)
printf(" %d",frame[j]);
}
}
}
ratio=hitcnt/no;
printf("\n\n\tHit ratio = %f ",ratio);
}

a) FIFO
b) LRU

c) OPT
EXPERIMENT-14
ITE2002-(OPERATING
Experiment: 14
SYSTEM LAB)
Write a program that implements the FIFO, LRU, and optimal pager replacement algorithms.
First, generate a random page-reference string where page numbers range from 0 to 9. Apply
the random page reference string to each algorithm, and record the number of page faults
incurred by each algorithm.
Implement the replacement algorithms so that the number of page frames can vary from 1 to
7. Assume that demand paging is used.
CODE:
Optimal Page Replacement Algorithm
#include<stdio.h>

int main()
{
int no_of_frames, no_of_pages, frames[10], pages[30], temp[10], flag1, flag2, flag3, i, j, k, pos,
max, faults = 0,random;
printf("Enter number of frames: ");
scanf("%d", &no_of_frames);

printf("Enter number of pages: ");


scanf("%d", &no_of_pages);

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


random = rand()%10;
pages[i]=random;
}

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


frames[i] = -1;
}

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


flag1 = flag2 = 0;

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


if(frames[j] == pages[i]){
flag1 = flag2 = 1;
break;
}
}

if(flag1 == 0){
for(j = 0; j < no_of_frames; ++j){
if(frames[j] == -1){
faults++;
frames[j] = pages[i];
flag2 = 1;
break;
}
}
}

if(flag2 == 0){
flag3 =0;

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


temp[j] = -1;

for(k = i + 1; k < no_of_pages; ++k){


if(frames[j] == pages[k]){
temp[j] = k;
break;
}
}
}

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


if(temp[j] == -1){
pos = j;
flag3 = 1;
break;
}
}

if(flag3 ==0){
max = temp[0];
pos = 0;

for(j = 1; j < no_of_frames; ++j){


if(temp[j] > max){
max = temp[j];
pos = j;
}
}
}

frames[pos] = pages[i];
faults++;
}

printf("\n");

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


printf("%d\t", frames[j]);
}
}

printf("\n\nTotal Page Faults = %d", faults);

return 0;
}
LRU Page Replacement Algorithm
#include<stdio.h>

int findLRU(int time[], int n){


int i, minimum = time[0], pos = 0;

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


if(time[i] < minimum){
minimum = time[i];
pos = i;
}
}

return pos;
}

int main()
{
int no_of_frames, no_of_pages, frames[10], pages[30], counter = 0, time[10], flag1, flag2, i, j,
pos, faults = 0,random;
printf("Enter number of frames: ");
scanf("%d", &no_of_frames);

printf("Enter number of pages: ");


scanf("%d", &no_of_pages);

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


random = rand()%10;
pages[i]=random
}

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


frames[i] = -1;
}
for(i = 0; i < no_of_pages; ++i){
flag1 = flag2 = 0;

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


if(frames[j] == pages[i]){
counter++;
time[j] = counter;
flag1 = flag2 = 1;
break;
}
}

if(flag1 == 0){
for(j = 0; j < no_of_frames; ++j){
if(frames[j] == -1){
counter++;
faults++;
frames[j] = pages[i];
time[j] = counter;
flag2 = 1;
break;
}
}
}

if(flag2 == 0){
pos = findLRU(time, no_of_frames);
counter++;
faults++;
frames[pos] = pages[i];
time[pos] = counter;
}

printf("\n");

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


printf("%d\t", frames[j]);
}
}

printf("\n\nTotal Page Faults = %d", faults);

return 0;
}
FIFO Page Replacement Algorithm
#include<stdio.h>

int main()
{
int reference_string[10], page_faults = 0, m, n, s, pages, frames,random;
printf("\nEnter Total Number of Pages:\t");
scanf("%d", &pages); for(m
= 0; m < pages; m++)
{
random = rand() % 10;
reference_string[m]=random;
}
printf("\nEnter Total Number of Frames:\t");
{
scanf("%d", &frames);
}
int temp[frames];
for(m = 0; m < frames; m++)
{
temp[m] = -1;
}
for(m = 0; m < pages; m++)
{
s = 0;
for(n = 0; n < frames; n++)
{
if(reference_string[m] == temp[n])
{
s++;
page_faults--;
}
}
page_faults++;
if((page_faults <= frames) && (s == 0))
{
temp[m] = reference_string[m];
}
else if(s == 0)
{
temp[(page_faults - 1) % frames] = reference_string[m];
}
printf("\n");
for(n = 0; n < frames; n++)
{
printf("%d\t", temp[n]);
}
}
printf("\nTotal Page Faults:\t%d\n", page_faults);
return 0;
}
EXPERIMENT-15
ITE2002-(OPERATING
SYSTEM LAB)
Experiment: EXPERIMENT-15
15
Consider a file of size 1 MB. The size of a disk block is 512Bytes. Assume any number of
available free blocks in the disk contiguously or non-contiguously. Implement the following
algorithms to perform file allocation. Determine the efficiency of each file allocation
strategies.
a. Sequential
b. Linked
c. Indexed
A) Sequential:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int
f[50],i,st,j,len,c,k;
for(i=0;i<50;i++)
f[i]=0;
X:
printf("\n Enter the starting block & length of file");
scanf("%d%d",&st,&len);
for(j=st;j<(st+len);j++
) if(f[j]==0)
{
f[j]=1
;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("Block already
allocated"); break;
}
if(j==(st+len))
printf("\n the file is allocated to disk");
printf("\n if u want to enter more files?(y-1/n-0)");
scanf("%d",&c);
if(c==1)
goto X;
else
exit();
return 0;
}
B)Linked File Allocation Program:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int f[50],p,i,j,k,a,st,len,n,c;

for(i=0;i<50;i+
+) f[i]=0;
printf("Enter how many blocks that are already allocated\n");
scanf("%d",&p);
printf("\nEnter the blocks no.s that are already allocated\n");
for(i=0;i<p;i++)
{
scanf("%d",&a)
; f[a]=1;
}
X:
printf("Enter the starting index block & length\n");
scanf("%d%d",&st,&len);
k=len;
for(j=st;j<(k+st);j+
+)
{
if(f[j]==0)
{
f[j]=1
;
printf("\n%d->%d\n",j,f[j]);
}
else
{
printf("%d->file is already
allocated\n",j); k++;
}
}
printf("If u want to enter one more file? (yes-1/no-0)\n");
scanf("%d",&c);
if(c==1)
goto X;
else
exit(0);
return 0;
}

C) Indexed File Allocation Program:

#include<stdio.h>
#include<stdlb.h>
int
f[50],i,k,j,inde[50],n,c,count=0,p;
int main()
{
for(i=0;i<50;i+
+) f[i]=0;
x:
printf("enter index block\t");
scanf("%d",&p);
if(f[p]==0)
{
f[p]=1
;
printf("enter no of files on index\t");
scanf("%d",&n);
}
else
{
printf("Block already allocated\n");
goto x;
}
for(i=0;i<n;i++)
scanf("%d",&inde[i])
; for(i=0;i<n;i++)
if(f[inde[i]]==1)
{
printf("Block already
allocated"); goto x;
}
for(j=0;j<n;j++)
f[inde[j]]=1;
printf("\n allocated");
printf("\n file indexed");
for(k=0;k<n;k++)
printf("\n %d->%d:%d",p,inde[k],f[inde[k]]);
printf(" Enter 1 to enter more files and 0 to exit\t");
scanf("%d",&c);
if(c==1
) goto
x; else
exit(0);
}
EFFICIENCY OF SEQUENTIAL ALLOCATION:
Advantages:
Contiguous allocation is easy to implement.
Disadvantages:
It can be considered as a form of dynamic memory allocation, and external
fragmentation may occur and compaction may be needed.
It is difficult to estimate the file size. The size of a file may grow at run time
and may be larger than the specified number of allocated blocks. In this case,
the OS must move the blocks in order to provide mode space. In some
systems, this is simply an error.

EFFICIENCY OF LINKED ALLOCATION:


Advantages:
File size does not have to be specified.
No external fragmentation.
Disadvantages:
It does sequential access efficiently and is not for direct access
Each block contains a pointer, wasting space
Blocks scatter everywhere and a large number of disk seeks may be necessary
Reliability: what if a pointer is lost or damaged?

EFFICIENCY OF INDEXED ALLOCATION:


Efficient random access without external fragmentation,
Size of index block
One data block
Overhead of index block
Wastage of space
Small sized files
ITE-2002(OS LAB)
SLOT-L41+L42
Submitted by-ASHISH RAJ
Submitted to- Prof.
SHASHIKIRAN V.

Write a program to implement LRU page


replacement using STACK
#include<stdio.h>
main()
{
int
q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
printf("Enter no of pages:");
scanf("%d",&n);
printf("Enter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter no of frames:");
scanf("%d",&f);
q[k]=p[k];
printf("\n\t%d\n",q[k]);
c++;
k++;
for(i=1;i<n;i++)
{
c1=0;
for(j=0;j<f;j++)
{
if(p[i]!=q[j])
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i]
; k++;
for(j=0;j<k;j++)
printf("\t%d",q[j]);
printf("\n");
}
else
{
for(r=0;r<f;r++)
{
c2[r]=0;
for(j=i-1;j<n;j--)
{
if(q[r]!=p[j]
) c2[r]++;
else
break;

}
}
for(r=0;r<f;r++
) b[r]=c2[r];
for(r=0;r<f;r++
)
{
for(j=r;j<f;j++)
{
if(b[r]<b[j])
{
t=b[r];
b[r]=b[j]
; b[j]=t;
}
}
}
for(r=0;r<f;r++)
{
if(c2[r]==b[0])
q[r]=p[i];
printf("\t%d",q[r]);

}
printf("\n");
}

}
printf("\nThe no of page faults is %d",c);
}