Opearating System LAb Files
Opearating System LAb Files
Opearating System LAb Files
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
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);
}
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>
if(argc != 3){
printf ("Usage: cp file1 file2");
return 1;
}
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
());
if (pid != 0)
printf ("I'm the parent process with PID %d and PPID %d.\n", getpid (),
getppid());
else
printf ("I'm the child process with PID %d and PPID %d.\n", getpid
(),getppid());
}
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;
}
#include<stdio.h>
#include<pthread.h>
int mul=1,i,n;
scanf("%d",&n);
for(i=n;i>0;i--)
mul=mul*i;
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;
}
else
}
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;
scanf("%d", &number);
if(number < 0)
{
printf("Please enter a positive number, greather than 0 \n");
scanf("%d", &number);
pid = fork();
if(pid < 0)
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);
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;
/* 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);
}
/* 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(){
scanf("%d",&n);
int i;
for(i=0;i<n;i+
+)
%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]);
int main(){
input();
calculate();
display();
return 0;
#include<stdio.h>
#include<stdbool.h>
typedef struct
int pid;
float at,wt,bt,ta,st;
bool isComplete;
}process;
scanf("%d",&p[i].pid);
scanf("%f",&p[i].at);
p[i].isComplete=false;
}//procdetail
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
}//sort int
main()
int n,i,k=0,j=0;
scanf("%d",&n);
process p[n];
for
(i=0;i<n;i++)
for (i=0;i<n;i++)
if (p[i].isComplete == true)
continue; else
k=i; while(p[i].at<=tst&&i<n)
if(p[i].at<=tst)
avgwt/=n; avgta/=n;
}
Non-preemptive
#include<stdio.h>
int main()
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;
scanf("%d",&n);
for(i=0;i<n;i++)
printf("p%d:",i+1);
scanf("%d",&bt[i])
; p[i]=i+1;
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
for(i=0;i<n;i++)
tat[i]=bt[i]+wt[i];
total+=tat[i];
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;
scanf("%d",&n)
for(i=0;i<n;i++)
",i+1); scanf("%d",&at[i]);
",i+1); scanf("%d",&bt[i]);
rt[i]=bt[i];
for(time=0;remain!=n;time++)
smallest=9;
for(i=0;i<n;i+
+)
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];
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;
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+
+)
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];
}
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:
#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 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 i;
for(i=0;i<n;i+
+)
if(i==0)
tat[i] =
bt[i]; else
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");
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;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&bt[i])
; p[i] = i;
sort();
WT_TAT(&SJF_tat,&SJF_
wt);
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 i;
scanf("%d",&n);
scanf("%d",&bt[i])
; p[i] = i;
WT_TAT(&FCFS_tat,&FCFS_
wt);
Time:%d",FCFS_wt/n); return 0;
int i;
for(i=0;i<n;i+
+)
if(i==0)
tat[i] =
bt[i]; else
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[%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;
}
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
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;
}
total+=wt[i];
}
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.
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)
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;
}
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;
}
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;
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;
-
return NULL;
-
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);
-
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;
{
//printf("%d\n",*((int*)arg));
pthread_setspecific(phil_num,arg);
printf("Philosopher %d is thinking.\n",*(int*)pthread_getspecific(phil_num));
sleep(3);
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]);
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++)
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;
}
for(i=0;i<np;i++)
{
printf("\nEnter the Size of required by segment%d:",(i+1));
scanf("%d",&request[i]);
}
FOLLOWS:");
if(np<=ns)
{
for(i=0;i<np;i++)
{
count=0;
while(count<ns)
{
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);
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;
if(flag3 ==0){
max = temp[0];
pos = 0;
frames[pos] = pages[i];
faults++;
}
printf("\n");
return 0;
}
LRU Page Replacement Algorithm
#include<stdio.h>
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);
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");
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;
}
#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.
}
}
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);
}