OS Lab Manual (R18)
OS Lab Manual (R18)
LABORATORY MANUAL
II-B.TECH II-Semester(R18)
(a) FCFS
Aim: Write a C program to implement the various process scheduling mechanisms such
Description:
First-come, first-serve scheduling(FCFS): In this, which process enter the ready queue first is
served first. The OS maintains DS that is ready queue. It is the simplest CPU scheduling
algorithm. If a process request the CPU then it is loaded into the ready queue, which process is
the head of the ready queue, connect the CPU to that process.
Algorithm for FCFS scheduling:
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Set the waiting of the first process as ‘0’ and its burst time as its turn around time
(c) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-
1)
(d) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for
process(n)
Step 6: Calculate
#include<stdio.h>
#include<string.h>
main()
{
int i,j,n,bt[10],compt[10],at[10], wt[10],tat[10];
float sumwt=0.0,sumtat=0.0,avgwt,avgtat;
printf("Enter number of processes: ");
scanf("%d",&n);
printf("Enter the burst time of %d process\n", n);
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
}
printf("Enter the arrival time of %d process\n", n);
for(i=0;i<n;i++)
{
scanf("%d",&at[i]);
}
compt[0]=bt[0]-at[0];
for(i=1;i<n;i++)
compt[i]=bt[i]+compt[i-1];
for(i=0;i<n;i++)
{
tat[i]=compt[i]-at[i];
wt[i]=tat[i]-bt[i];
sumtat+=tat[i];
sumwt+=wt[i]; }
avgwt=sumwt/n;
avgtat=sumtat/n;
printf("---------------------------------- \n");
printf("PN\tBt\tCt\tTat\tWt\n");
printf("---------------------------------- \n");
for(i=0;i<n;i++)
{
printf("%d\t%2d\t%2d\t%2d\t%2d\n",i,bt[i],compt[i],tat[i],wt[i]);
}
printf("----------------------------------\n");
printf(" Avgwt = %.2f\tAvgtat = %.2f\n",avgwt,avgtat);
printf("-----------------------------------\n");
}
OUTPUT :
Shortest Job First: The criteria of this algorithm are which process having the smallest CPU
burst, CPU is assigned to that next process. If two process having the same CPU burst time
FCFS is used to break the tie.
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Start the Ready Q according the shortest Burst time by sorting according to lowest to
Step 5: Set the waiting time of the first process as ‘0’ and its turnaround time as its burst time.
(a) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-
1)
(b) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for
process(n)
Step 6: Calculate
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,n,bt[10],compt[10], wt[10],tat[10],temp; float
sumwt=0.0,sumtat=0.0,avgwt,avgtat; printf("Enter number of processes: ");
scanf("%d",&n);printf("Enter the burst time of %d process\n", n); for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
}
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(bt[i]>bt[j])
{
temp=bt[i];
bt[i]=bt[j];
bt[j]=temp;
}
compt[0]=bt[0];
for(i=1;i<n;i++)
compt[i]=bt[i]+compt[i-1];
for(i=0;i<n;i++)
{
tat[i]=compt[i];
wt[i]=tat[i]-bt[i];
sumtat+=tat[i];
sumwt+=wt[i];
}
avgwt=sumwt/n;
avgtat=sumtat/n;
printf("------------------------------ \n");
printf("Bt\tCt\tTat\tWt\n");
printf("------------------------------ \n");
for(i=0;i<n;i++)
{
printf("%2d\t%2d\t%2d\t%2d\n",bt[i],compt[i],tat[i],wt[i]);}
printf("------------------------------\n");
printf(" Avgwt = %.2f\tAvgtat = %.2f\n",avgwt,avgtat);
printf("--------------
-------------- \n");
getch();
}
OUTPUT:
Enter number of processes: 4
Enter the burst time of 4 process
6873
------------------------------------
Bt Ct Tat Wt
------------------------------------
3 3 3 0
6 9 9 3
7 16 16 9
8 24 24 16
--------------------------------------
Avgwt = 7.00 Avgtat = 13.00
{
char pn[10]; int
bt,ct,time;
}p[10];
int main()
{
scanf("%s%d",&p[i].pn,&p[i].bt);
p[i].time=p[i].bt;
}
printf("Enter quantum:");
scanf("%d",&tq); full=n;
while(full)
{
for(i=0;i<n;i++)
{
if(p[i].bt>=tq)
{
p[i].bt-=tq;
time1=time1+tq;
}
else if(p[i].bt!=0)
{
time1+=p[i].bt;
p[i].bt=0;
}
else
continue;
if(p[i].bt==0)
{
full=full-1;
tat[i]=time1;
}
}
}
for(i=0;i<n;i++)
{
p[i].ct=tat[i];
wt[i]=tat[i]-p[i].time;
}
printf("---------------------------------- \n");
printf("PN\tBt\tCt\tTat\tWt\n");
printf("---------------------------------- \n");
for(i=0;i<n;i++)
{
printf("%2s\t%2d\t%2d\t%2d\t%2d\n",p[i].pn,p[i].time,p[i].ct,tat[i],wt[i]);
avgwt+=wt[i];
}
printf("----------------------------------\n");
avgwt=avgwt/n;
printf(" Average waiting time = %.2f\n",avgwt);
printf("-----------------------------------\n");
OUTPUT:
Enter number of processes: 5
PN Bt Ct Tat Wt
--------------------------------------
1 10 28 28 18
2 5 10 10 5
3 15 43 43 28
4 3 18 18 15
5 20 53 53 33
--------------------------------------
Average waiting time = 19.80
--------------------------------------
(d)PRIORITY SCHEDULING
Aim: Write a C program to implement the various process scheduling mechanisms such
as Priority Scheduling.
Description:
One is internal priority, second is external priority. The cpu is allocated to the process with the
highest priority. Equal priority processes are scheduled in the FCFS order. Priorities are
generally some fixed range of numbers such as 0 to 409. The low numbers represent high
priority.
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 5: Set the waiting of the first process as ‘0’ and its burst time as its turn around time
(e) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-
1)
(f) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for
process(n)
Step 7: Calculate
(g) Average waiting time = Total waiting Time / Number of process
#include<stdio.h>
int main()
{
int i,j,n,bt[10],p[10],compt[10], wt[10],tat[10],temp1,temp2;
float sumwt=0.0,sumtat=0.0,avgwt,avgtat;
printf("Enter number of processes: "); scanf("%d",&n);
printf("Enter the burst time of %d process\n", n);
for(i=0;i<n;i++)
scanf("%d",&bt[i]);
printf("Enter the priority of %d process\n", n);
for(i=0;i<n;i++)
scanf("%d",&p[i]);
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(p[i]>p[j])
{
temp1=bt[i];
bt[i]=bt[j];
bt[j]=temp1;
temp2=p[i];
p[i]=p[j];
p[j]=temp2;
}
compt[0]=bt[0]; wt[0]=0;
for(i=1;i<n;i++) compt[i]=bt[i]
+compt[i-1]; for(i=0;i<n;i++)
{
tat[i]=compt[i];
wt[i]=tat[i]-bt[i];
sumtat+=tat[i];
sumwt+=wt[i];
}
avgwt=sumwt/n; avgtat=sumtat/n;
printf("------------------------------\n");
printf("Bt\tCt\tTat\tWt\n");
printf("------------------------------\n");
for(i=0;i<n;i++)
{
printf("%2d\t%2d\t%2d\t%2d\n",bt[i],compt[i],tat[i],wt[i]);
}
printf("------------------------------\n");
printf(" Avgwt = %.2f\tAvgtat = %.2f\n",avgwt,avgtat);
printf(“------ \n");
}
OUTPUT :
Enter number of processes: 4
Enter the burst time of 4 process
6535
Enter the priority of 4 process
4263
------------------------------------
Bt Ct Tat Wt
-----------------------------------
5 5 5 0
5 10 10 5
6 16 16 10
3 19 19 16
------------------------------------
Avgwt = 7.75 Avgtat = 12.50
2.Write programs using the I/O system calls of UNIX/LINUX operating system
(open, read, write, close, fcntl, seek, stat, opendir, readdir)
Program:
Aim: Programs to use I/O system calls of UNIX/LINUX operating system
Read from a text file:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("abc.txt","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
OUTPUT:
cse501@vignan:~/OSprograms> vi 2read.c
cse501@vignan:~/OSprograms> gcc -o op2read 2read.c
Error! opening filecse501@vignan:~/OSprograms> vi abc.txt
12345
cse501@vignan:~/OSprograms> ./op2read
Value of n=12345
Program to Open a File, Write in it, And Close the File
# include <stdio.h>
# include <string.h>
int main( )
{
// Declare the file pointer
FILE *filePointer ;
// Get the data to be written in file
char dataToBeWritten[50]
= "GeeksforGeeks-A Computer Science Portal for Geeks";
// Open the existing file abc.c using fopen()
// in write mode using "w" attribute
filePointer = fopen("abc.c", "w") ;
// Check if this filePointer is null
// which maybe if the file does not exist
if ( filePointer == NULL )
{
printf( "abc.c file failed to open." ) ;
}
else
{
printf("The file is now opened.\n") ;
// Write the dataToBeWritten into the file
if ( strlen ( dataToBeWritten ) > 0 )
{
// writing in the file using fputs()
fputs(dataToBeWritten, filePointer) ;
fputs("\n", filePointer) ;
}
// Closing the file using fclose()
fclose(filePointer) ;
printf("Data successfully written in file abc.c\n");
printf("The file is now closed.") ;
}
return 0;
}
OUTPUT:
cse501@vignan:~/OSprograms> vi 2write.c
cse501@vignan:~/OSprograms> gcc -o op2write 2write.c
cse501@vignan:~/OSprograms> ./op2write
The file is now opened.
Data successfully written in file abc.c
Program to use lseek system call.
#include <unistd.h>
#include<stdio.h>
#include <fcntl.h>
#include <sys/types.h>
int main()
{
int file=0;
if((file=open("abc1.txt",O_RDONLY)) < -1)
return 1;
char buffer[19];
if(read(file,buffer,19) != 19) return 1;
printf("%s\n",buffer);
if(lseek(file,10,SEEK_SET) < 0) return 1;
if(read(file,buffer,19) != 19) return 1;
printf("%s\n",buffer);
return 0;
}
OUTPUT:
cse501@vignan:~/OSprograms> vi abc1.txt
cse501@vignan:~/OSprograms> vi 2lseek.c
cse501@vignan:~/OSprograms> ./op2lseek
Hi vmtw Ghatkesar K
}
OUTPUT:
cse501@vignan:~/OSprograms> vi 2stat.c
cse501@vignan:~/OSprograms> gcc -o op2stat 2stat.c
cse501@vignan:~/OSprograms> ./op2stat
Enter source file path: abc1.txt
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
int main(int c, char *v[])
{
DIR *myDirectory;
myDirectory = opendir(v[1]);
if (c == 2)
{
if (myDirectory)
{
puts("OK the folder is opened.");
/*
** closedir
*/
if (closedir(myDirectory) == 0)
puts("The directory is now closed.");
else
puts("The directory can not be closed.");
}
else if (errno == ENOENT)
puts("This directory does not exist.");
else if (errno == ENOTDIR)
puts("This file is not a directory.");
else if (errno == EACCES)
puts("You do not have the right to open this folder.");
else
puts("That's a new error, check the manual.");
}
else
puts("Sorry we need exactly 2 arguments.");
return (0);
}
OUTPUT:
All files and subdirectories of current directory
if (c == 2) {
myDirectory = opendir(v[1]);
if (myDirectory) {
puts("OK the directory is opened, let's see its files:");
while ((myFile = readdir(myDirectory)))
printf("%s\n", myFile->d_name);
/*
** closedir
*/
if (closedir(myDirectory) == 0)
puts("The directory is now closed.");
else
puts("The directory can not be closed.");
} else if (errno == ENOENT)
puts("This directory does not exist.");
else if (errno == ENOTDIR)
puts("This file is not a directory.");
else if (errno == EACCES)
puts("You do not have the right to open this folder.");
else
puts("That's a new error, check the manual.");
} else
puts("Sorry we need exactly 2 arguments.");
return (0);
}
3.Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and
Prevention.
Description:
Deadlock: A process request the resources, the resources are not available at that time, so the
process enter into the waiting state. The requesting resources are held by another waiting
process,both are in waiting state, this situation is said to be Deadlock.
(iii) No Preemption: No Preemption means resources are not released in the middle of the
work, they released only after the process has completed its task.
(iv) Circular Wait: If process P1 is waiting for a resource R1, it is held by P2, process P2 is
waiting for R2, R2 held by P3, P3 is waiting for R4, R4 is held by P2, P2 waiting for resource
R3, it is held by P1.
Deadlock Avoidance: It is one of the method of dynamically escaping from the deadlocks. In
this scheme, if a process request for resources, the avoidance algorithm checks before the
allocation of resources about the state of system. If the state is safe, the system allocate the
resources to the requesting process otherwise (unsafe) do not allocate the resources. So taking
care before the allocation said to be deadlock avoidance.
Banker’s Algorithm: It is the deadlock avoidance algorithm, the name was chosen because the
bank never allocates more than the available cash.
Available: A vector of length ‘m’ indicates the number of available resources of each type. If
available[j]=k, there are ‘k’ instances of resource types Rj available.
Allocation: An nxm matrix defines the number of resources of each type currently allocated to
each process. If allocation[i,j]=k, then process Pi is currently allocated ‘k’ instances of resources
type Rj.
Max: An nxm matrix defines the maximum demand of each process. If max[i,j]=k, then Pi may
request at most ‘k’ instances of resource type Rj.
Need: An nxm matrix indicates the remaining resources need of each process. If need[I,j]=k,
then Pi may need ‘k’ more instances of resource type Rj to complete this task. There fore,
Need[i,j]=Max[i,j]-Allocation[I,j]
Safety Algorithm:
1. Work and Finish be the vector of length m and n respectively, Work=Available and
Finish[i] =False.
2. Find an i such that both
Finish[i] =False
Need<=Work
If no such I exists go to step 4.
3. work=work+Allocation, Finish[i] =True;
4. if Finish[1]=True for all I, then the system is in safe state.
Resource request algorithm
Let Request i be request vector for the process Pi, If request i=[j]=k, then process Pi
wants k instances of resource type Rj.
1. if Request<=Need I go to step 2. Otherwise raise an error condition.
2. if Request<=Available go to step 3. Otherwise Pi must since the resources are available.
3. Have the system pretend to have allocated the requested resources to process Pi by
modifying the state as follows;
Available=Available-Request I;
Allocation I =Allocation +Request I;
Need i=Need i-Request I;
If the resulting resource allocation state is safe, the transaction is completed and process Pi is
allocated its resources. However, if the state is unsafe, the Pi must wait for Request i and the old
resource-allocation state is restored.
int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}
if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}
return (0);
}
OUTPUT:
Following is the SAFE Sequence
#include<stdio.h>
main()
char job[10][10];
int ind=1,i,j,q,n,t;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%s%d",&job[i],&time[i]);
for(i=0;i<n;i++)
temp[i]=time[i];
tem[i]=i;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(temp[i]>temp[j])
t=temp[i];
temp[i]=temp[j];
temp[j]=t; t=tem[i];
tem[i]=tem[j];
tem[j]=t;
for(i=0;i<n;i++)
{
q=tem[i];
if(time[q]<=avail)
safe[ind]=tem[i];
avail=avail-tem[q];
printf("%s",job[safe[ind]]);
ind++;
else
for(i=1;i<ind; i++)
printf("%s %d\n",job[safe[i]],time[safe[i]]);
getch();
OUTPUT:
Enter no of jobs:4
4.A C program that implements a producer-consumer system with two processes using
Semaphores using UNIX/LINUX system calls.
Program:
#include<stdio.h>
int main()
{
int buffer[10], bufsize, in, out, produce, consume,choice=0; in = 0;
out = 0;
bufsize = 10;
while(choice !=3){
printf(“\n1. Produce \t 2. Consume \t3. Exit”);
scanf(“%d”,&choice);
switch(choice)
{
case 1: if((in+1)%bufsize==out)
printf(“\nBuffer is Full”);
else
{
printf(“\nEnter the value: “);
scanf(“%d”, &produce);
buffer[in] = produce;
in = (in+1)%bufsize;
break;
case 2:if(in == out)
printf(“\nBuffer is Empty”);
else
{
consume = buffer[out];
printf(“\nThe consumed value is %d”, consume);
out = (out+1)%bufsize;
}
break;
}}}
OUTPUT
Buffer is Empty
1. Produce 2. Consume 3. Exit
if((r1=read(fd,msgbuf,40))>0)
{
printf("%d",r1);
printf("Iam server:%s",msgbuf);
}
named.c
#include<fcntl.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<string.h>
#define MSG 63
main()
{
int fd,j,nwrite;
char msgbuf[MSG];
char s[10]="anusha1";/*you may take any string here*/
if((fd=open("fif1",O_WRONLY))<0)
perror("FIFO OPEN FAI;ED");
strcpy(msgbuf,s);
if((nwrite=write(fd,msgbuf,40))<=0)
printf("msg write failed");
else
printf("message is written:%s",msgbuf);
exit(0);
}
OUTPUT:
(iii)Message Queues
int main()
{
key_t key;
int msgid;
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// structure for message queue
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;
int main()
{
key_t key;
int msgid;
// ftok to generate unique key
key = ftok("progfile", 65);
// msgget creates a message queue
// and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);
// msgrcv to receive message
msgrcv(msgid, &message, sizeof(message), 1, 0);
// display the message
printf("Data Received is : %s \n",
message.mesg_text);
// to destroy the message queue
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
OUTPUT:
cse501@vignan:~/OSprograms> vi 5cmsgqw.c
cse501@vignan:~/OSprograms> gcc -o op5cmsgqw 5cmsgqw.c
cse501@vignan:~/OSprograms> vi 5cmsgqr.c
cse501@vignan:~/OSprograms> gcc -o op5cmsgqr 5cmsgqr.c
cse501@vignan:~/OSprograms> ./op5cmsgqw
Write Data : hello
Data send is : hello
cse501@vignan:~/OSprograms> ./op5cmsgqr
Data Received is : hello
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
printf(“Write Data : ");
scanf(“%s”,str);
printf("Data written in memory: %s\n",str);
//detach from shared memory
shmdt(str);
return 0;
}
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
printf("Data read from memory: %s\n",str);
//detach from shared memory
shmdt(str);
// destroy the shared memory
shmctl(shmid,IPC_RMID,NULL);
return 0;
}
OUTPUT:
cse501@vignan:~/OSprograms> vi 5dshmread.c
cse501@vignan:~/OSprograms> vi 5dshmwrite.c
cse501@vignan:~/OSprograms> gcc -o op5dshmwrite 5dshmwrite.c
cse501@vignan:~/OSprograms> gcc -o op5dshmread 5dshmread.c
cse501@vignan:~/OSprograms> ./op5dshmwrite
Write Data : Hi
Data written in memory: Hi
cse501@vignan:~/OSprograms> ./op5dshmread
Data read from memory: Hi
In this scheme the operating system maintains a data structure that is page table, it is used for
mapping purpose. The page table specifies the some useful information, it tells which frames are
there and so on. The page table consisting of two fields, one is the page number and other one is
frame number. Every address generated by the CPU divided into two parts, one is page number
and second is page offset or displacement. The pages are loaded into available free frames in the
physical memory.
#include<stdio.h>
int main()
{
int memsize=15;
int pagesize,nofpage;
int p[100];
int frameno,offset;
int logadd,phyadd;
int i;
int choice=0;
printf("\nYour memsize is %d ",memsize);
printf("\nEnter page size:");
scanf("%d",&pagesize);
nofpage=memsize/pagesize;
for(i=0;i<nofpage;i++)
{
printf("\nEnter the frame of page%d:",i+1);
scanf("%d",&p[i]);
}
do
{
printf("\nEnter a logical address:");
scanf("%d",&logadd);
frameno=logadd/pagesize;
offset=logadd%pagesize;
phyadd=(p[frameno]*pagesize)+offset;
printf("\nPhysical address is:%d",phyadd);
printf("\nDo you want to continue(1/0)?:");
scanf("%d",&choice);
}while(choice==1);}
OUTPUT:
cse501@vignan:~/OSprograms> vi 6apaging.c
cse501@vignan:~/OSprograms> gcc -o op6a 6apaging.c
cse501@vignan:~/OSprograms> ./op6a
Your memsize is 15
Enter page size:5
Enter the frame of page1:2
Enter the frame of page2:4
Enter the frame of page3:7
Enter a logical address:3
Physical address is:13
Do you want to continue(1/0)?:1
Enter a logical address:1
Physical address is:11
Do you want to continue(1/0)?:0
b) Segmentation
#include<stdio.h>
#define MAX 50
int main()
{
int segment[MAX][2],i,n,f,off,sno;
printf("\nEnter the no of segments in memory");
scanf("%d",&n);
for(i=0;i<n;i++)
{
segment[i][0]=-1;
segment[i][1]=-1;
}