You are on page 1of 49

OPERATING SYSTEMS

LAB MANUAL
INDEX
EXPNO NAME OF THE EXPERIMENT Page number

1 a) FCFS(First Come First Served) 1-4

b) SJF(Shortest Job First) 5-8


c) Priority Scheduling 9-11
d) RR( Round Robin) Scheduling 12-15
Open,Read,Write,Close,Fcntl,Seek,Stat,
2 a) 16-18

b) Opendir,Readdir 19-21
Banker’s Algorithm for Dead Lock Avoidance
3 25-27
And Dead Lock Prevention
Producer –Consumer Problem Using Semaphore
4 28-30

5 a) 38-40
IPC- Mechanisms using Pipes
b) FIFO’s 41-44
c) Message queues 45-48
d) Shared Memory
Paging Memory Management Technique
6 a) 49-52
Segmentation Memory Management Technique
b) 53-57
1.EXPERIMENT NO: 1.
2. NAME OF THE EXPERIMENT: Write C programs to simulate the following
CPU Scheduling algorithms
a) FCFS b) SJF c) Round Robin d) priority

AIM:
a)To write a program to implement the FCFS (First Come First Serve) CPU
scheduling Algorithm

ALGORITHM :
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst
time
Step 4: Set the waiting of the first process as ‘0’ and its burst time as its turn around time
Step 5: for each process in the Ready Q calculate
(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
(a) Average waiting time = Total waiting Time / Number of process
(b) Average Turnaround time = Total Turnaround Time / Number of process
Step 7: Stop the process
PROGRAM: /* FCFS SCHEDULING ALGORITHM */
#include<stdio.h>
void main()
{
int i,n,sum,wt,tat,twt,ttat;
int t[10];
float awt,atat;
clrscr();

printf("Enter number of processors:\n");


scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter the Burst Time of the process %d",i+1);
scanf("\n %d",&t[i]);
}
printf("\n\n FIRST COME FIRST SERVE SCHEDULING ALGORITHM \n");
printf("\n Process ID \t Waiting Time \t Turn Around Time \n");
printf("1 \t\t 0 \t\t %d \n",t[0]);
sum=0;
twt=0;
ttat=t[0];
for(i=1;i<n;i++)
{
sum+=t[i-1];
wt=sum;
tat=sum+t[i];
twt=twt+wt;
ttat=ttat+tat;
printf("\n %d \t\t %d \t\t %d",i+1,wt,tat);
printf("\n\n");
}
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\n Average Waiting Time %4.2f",awt);
printf("\n Average Turnaround Time %4.2f",atat);
getch();
}
OUTPUT:

Enter number of processors:


3

Enter the Burst Time of the process 1: 2

Enter the Burst Time of the process 2: 5

Enter the Burst Time of the process 3: 4

FIRST COME FIRST SERVE SCHEDULING ALGORITHM

Process ID Waiting Time Turn Around Time


1 0 2

2 2 7

3 7 11

Average Waiting Time 3.00


Average Turnaround Time 6.67
b) Shortest Job First:
Algorithm for SJF
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst
time
Step 4: Start the Ready Q according the shortest Burst time by sorting according to
lowest to
highest burst time.
Step 5: Set the waiting time of the first process as ‘0’ and its turnaround time as its burst
time.
Step 6: For each process in the ready queue, calculate
(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
(c) Average waiting time = Total waiting Time / Number of process
(d) Average Turnaround time = Total Turnaround Time / Number of process
Step 7: Stop the process
PROGRAM: /* SJF SCHEDULING ALGORITHM */

#include<stdio.h>
void main()
{
int i,j,k,n,sum,wt[10],tt[10],twt,ttat;
int t[10],p[10];
float awt,atat;
clrscr();

printf("Enter number of process\n");


scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("\n Enter the Burst Time of Process %d",i);
scanf("\n %d",&t[i]);
}

for(i=0;i<n;i++)
p[i]=i;
for(i=0;i<n;i++)
{
for(k=i+1;k<n;k++)
{
if(t[i]>t[k])
{
int temp;
temp=t[i];
t[i]=t[k];
t[k]=temp;

temp=p[i];
p[i]=p[k];
p[k]=temp;
}
}
printf("\n\n SHORTEST JOB FIRST SCHEDULING ALGORITHM");
printf("\n PROCESS ID \t BURST TIME \t WAITING TIME \t TURNAROUND
TIME \n\n");
wt[0]=0;
for(i=0;i<n;i++)
{
sum=0;
for(k=0;k<i;k++)
{
wt[i]=sum+t[k];
sum=wt[i];
}
}
for(i=0;i<n;i++)
{
tt[i]=t[i]+wt[i];
}
for(i=0;i<n;i++)
{
printf("%5d \t\t5%d \t\t %5d \t\t %5d \n\n",p[i],t[i],wt[i],tt[i]);
}
twt=0;
ttat=t[0];
for(i=1;i<n;i++)
{
twt=twt+wt[i];
ttat=ttat+tt[i];
}
awt=(float)twt/n;
atat=(float)ttat/n;

printf("\n AVERAGE WAITING TIME %4.2f",awt);


printf("\n AVERAGE TURN AROUND TIME %4.2f",atat);
getch();
}
}
OUTPUT:

Enter number of process


3

Enter the Burst Time of Process 04

Enter the Burst Time of Process 13

Enter the Burst Time of Process 25

SHORTEST JOB FIRST SCHEDULING ALGORITHM


PROCESS ID BURST TIME WAITING TIME TURNAROUND TIME

1 3 0 3

0 4 3 7

2 5 7 12

AVERAGE WAITING TIME 3.33


AVERAGE TURN AROUND TIME 7.33
C).Priority Scheduling

Algorithm for Priority Scheduling:

Step 1: Start the process


Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst
time
Step 4: Sort the ready queue according to the priority number.
Step 5: Set the waiting of the first process as ‘0’ and its burst time as its turn around time
Step 6: For each process in the Ready Q calculate
(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
(e) Average waiting time = Total waiting Time / Number of process
(f) Average Turnaround time = Total Turnaround Time / Number of process
Step 8: Stop the process
PROGRAM: /* PRIORITY SCHEDULING */

#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,n,tat[10],wt[10],bt[10],pid[10],pr[10],t,twt=0,ttat=0;
float awt,atat;
clrscr();
printf("\n-----------PRIORITY SCHEDULING--------------\n");
printf("Enter the No of Process: ");
scanf("%d", &n);
for (i=0;i<n;i++)
{
pid[i] = i;
printf("Enter the Burst time of Pid %d : ",i);
scanf("%d",&bt[i]);
printf("Enter the Priority of Pid %d : ",i);
scanf ("%d",&pr[i]);
}
// Sorting start
for (i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if (pr[i] > pr[j] )
{
t = pr[i];
pr[i] = pr[j];
pr[j] = t;

t = bt[i];
bt[i] = bt[j];
bt[j] = t;

t = pid[i];
pid[i] = pid[j];
pid[j] = t;
}
}
// Sorting finished

tat[0] = bt[0];
wt[0] = 0;

for (i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = wt[i] + bt[i];
}

printf("\n---------------------------------------------------------------\n");
printf("Pid\t Priority\tBurst time\t WaitingTime\tTurnArroundTime\n");
printf("\n--------------------------------------------------------------\n");
for(i=0;i<n;i++)
{
printf("\n%d\t\t%d\t%d\t\t%d\t\t%d",pid[i],pr[i],bt[i],wt[i],tat[i]);
}
for(i=0;i<n;i++)
{
ttat = ttat+tat[i];
twt = twt + wt[i];
}
awt = (float)twt / n;
atat = (float)ttat / n;
printf("\n\nAvg.Waiting Time: %f\nAvg.Turn Around Time: %f\n",awt,atat);
getch();
}
OUTPUT:

-----------PRIORITY SCHEDULING--------------

Enter the No of Process: 4


Enter the Burst time of Pid 0 : 2
Enter the Priority of Pid 0 : 3
Enter the Burst time of Pid 1 : 6
Enter the Priority of Pid 1 : 2
Enter the Burst time of Pid 2 : 4
Enter the Priority of Pid 2 : 1
Enter the Burst time of Pid 3 : 5
Enter the Priority of Pid 3 : 7

----------------------------------------------------------------------------------------
Pid Priority Burst time WaitingTime TurnArroundTime

----------------------------------------------------------------------------------------

2 1 4 0 4
1 2 6 4 10
0 3 2 10 12
3 7 5 12 17

Avg.Waiting Time: 6.500000


Avg.Turn Around Time: 10.750000
D).Round Robin Scheduling.

Algorithm for RR

Step 1: Start the process


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

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

void main()
{
int ts,pid[10],need[10],wt[10],tat[10],i,j,n,n1;
int bt[10],flag[10],ttat=0,twt=0;
float awt,atat;
clrscr();

printf("\t\t ROUND ROBIN SCHEDULING \n");


printf("Enter the number of Processors \n");
scanf("%d",&n);

n1=n;
printf("\n Enter the Timeslice \n");
scanf("%d",&ts);
for(i=1;i<=n;i++)
{
printf("\n Enter the process ID %d",i);
scanf("%d",&pid[i]);
printf("\n Enter the Burst Time for the process");
scanf("%d",&bt[i]);
need[i]=bt[i];
}
for(i=1;i<=n;i++)
{
flag[i]=1;
wt[i]=0;
}
while(n!=0)
{
for(i=1;i<=n;i++)
{
if(need[i]>=ts)
{
for(j=1;j<=n;j++)
{
if((i!=j)&&(flag[i]==1)&&(need[j]!=0))
wt[j]+=ts;
}
need[i]-=ts;
if(need[i]==0)
{
flag[i]=0;
n--;
}
}
else
{
for(j=1;j<=n;j++)
{
if((i!=j)&&(flag[i]==1)&&(need[j]!=0))
wt[j]+=need[i];
}
need[i]=0;
n--;
flag[i]=0;
}
}
}
for(i=1;i<=n1;i++)
{
tat[i]=wt[i]+bt[i];
twt=twt+wt[i];
ttat=ttat+tat[i];
}
awt=(float)twt/n1;
atat=(float)ttat/n1;

printf("\n\n ROUND ROBIN SCHEDULING ALGORITHM \n\n");


printf("\n\n Process \t Process ID \t BurstTime \t Waiting Time \t TurnaroundTime \n ");
for(i=1;i<=n1;i++)
{
printf("\n %5d \t %5d \t\t %5d \t\t %5d \t\t %5d \n", i,pid[i],bt[i],wt[i],tat[i]);
}

printf("\n The average Waiting Time=4.2f",awt);


printf("\n The average Turn around Time=4.2f",atat);
getch();
}
OUTPUT:

ROUND ROBIN SCHEDULING


Enter the number of Processors
4

Enter the Timeslice


5

Enter the process ID 1 5

Enter the Burst Time for the process 10

Enter the process ID 2 6

Enter the Burst Time for the process 15

Enter the process ID 3 7

Enter the Burst Time for the process 20

Enter the process ID 4 8

Enter the Burst Time for the process 25

ROUND ROBIN SCHEDULING ALGORITHM

Process Process ID BurstTime Waiting Time TurnaroundTime

1 5 10 15 25

2 6 15 25 40

3 7 20 25 45

4 8 25 20 45

The average Waiting Time=4.2f


The average Turn around Time=4.2f
1.EXPERMENT.2
2.NAME OF THE EXPERMENT: Write programs using the I/O system calls of
UNIX/LINUX operating system
(open, read, write, close, fcntl, seek, stat, opendir, readdir)

(a)Open:

AIM:
Using the I/O system calls of UNIX/LINUX operating system Open();

ALGORITHM:
1. Start the program
2. Declare the necessary variables
3. Open file1.dat to read or write access
4. Create file1.dat if it doesn’t exist
5. Return error if file already exist
6. Permit read or write access to the file
7. Stop the program.

PROGRAM:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
int main()
{
int fd;
fd=creat("file1.dat",S_IREAD|S_IWRITE);
if(fd==-1)
printf("Error in opening file1.dat\n");
else
{
}
printf("\nfile1.dat opened for read/write access\n");
printf("\nfile1.dat is currently empty");
close(fd);
}
OUTPUT:
file1.dat opened for read/write access.
RESULT:
Thus the program for open system call has been executed successfully.
b) Using the I/O system calls of UNIX/LINUX operating system Read();

ALGORITHM:
1.Get the data from the user.
2.Open a file.
3.Read from the file.
4.Close the file.

PROGRAM:
#include<stdio.h>
int main()
{
char str[100];
FILE *fp;
fp=fopen("file1.dat","r");
while(!feof(fp))
{
fscanf(fp,"%s",str);
printf(" %s ",str);
}
fclose(fp);
}

OUTPUT:
$ vi read1.c
$gcc read1.c
$ ./a.out
hai this is a program to read the content of the file.

RESULT:
Thus C program to write data into a file was executed successfully
c) Using the I/O system calls of UNIX/LINUX operating system write();

Write :

ALGORITHM:
Step1.Get the data from the user.
Step2.Open a file.
Step3.Write the data from the file.
Step4.Get the data and update the file.

PROGRAM:
#include<stdio.h>
int main()
{
char str[100];
FILE *fp;
printf("Enter the string");
gets(str);
fp=fopen("file1.dat","w+");
while(!feof(fp))
{
fscanf(fp,"%s",str);
}
fprintf(fp,"%s",str);
}

OUTPUT:
$ gcc write.c
$ ./a.out
Enter the string: os lab
$vi file1.dat
os lab

RESULT:
Thus C program to write data into a file was executed successfully
(d) Using the I/O system calls of UNIX/LINUX operating system Exec();

AIM:
ALGORITHM:
1. Start the program
2. Declare the necessary variables
3. Use the prototype execv (filename,argv) to transform
an executable binary file into process
4. Repeat this until all executed files are displayed
5. Stop the program.

PROGRAM:
#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);
}
}

Output:

total 440
-rwxrwxr-x 1 skec25 skec25 5210 Apr 16 06:25 a.out
-rw-rw-r-- 1 skec25 skec25 775 Apr 9 08:36 bestfit.c
-rw-rw-r—1 skec25 skec25 1669 Apr 10 09:19 correctpipe.c
-rw-rw-r-- 1 skec25 skec25 977 Apr 16 06:15 correctprio.c
-rw------- 1 skec25 skec25 13 Apr 10 08:14 datafile.dat
-rw------- 1 skec25 skec25 13 Apr 10 08:15 example.dat
-rw-rw-r-- 1 skec25 skec25 166 Apr 16 06:25 exec.c
-rw-rw-r-- 1 skec25 skec25 490 Apr 10 09:43exit.c

Parent Process
Result: Thus the program for exec system call has been executed successfully.
(e) Using the I/O system calls of UNIX/LINUX operating system stat();

AIM :
To Execute a Unix Command in a ‘C’ program using stat() system call.
ALGORITHM:
1. Start the program
2. Declare the variables for the structure stat
3. Allocate the size for the file by using malloc function
4. Get the input of the file whose statistics want to be founded
5. Repeat the above step until statistics of the files are listed
6. Stop the program.

PROGRAM:
#include<stdio.h>
#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("nu,mber of links:%d\n",nfile->st_nlink);
}
OUTPUT:
enter name of file whose stsistics has to stat.c
user id 621
block size :4096
last access time 1145148485
time of last modification 1145148485
porduction mode 33204
size of file 654
nu,mber of links:1
Result:
Thus the program for stat system call has been executed successfully.
f). Using the I/O system calls of UNIX/LINUX operating system
Open(), read(),write,close(), stat( ), fcntl and seek()
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
main( )
{
int fd[2];

char buf1[25]= ”just a test\n”;


char buf2[50];

fd[0]=open(“file1”, O_RDWR);
fd[1]=open(“file2”, O_RDWR);
write(fd[0], buf1, strlen(buf1));
printf(“\n Enter the text now….”);
gets(buf1);

write(fd[0], buf1, strlen(buf1));


lseek(fd[0], SEEK_SET, 0);
read(fd[0], buf2, sizeof(buf1));
write(fd[1], buf2, sizeof(buf2));
close(fd[0]);

close(fd[1]);
printf(“\n”);
return0;
}

OUTPUT:
Enter the text now….progress
Cat file1 Just a test progress

Cat file2 Just a test progress


g).Using the I/O system calls of UNIX/LINUX operating system
Opendir,Readdir:

ALGORITHM:
1. Start the program
2. Declare the variable to the structure dirent (defines the file system-independent
directory)
and also for DIR
3. Specify the directory path to be displayed using the opendir system call
4. Check for the existence of the directory and read the contents of the directory using
readdir system call (returns a pointer to the next active directory entry)
5. Repeat the above step until all the files in the directory are listed
6. Stop the program

PROGRAM:
#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);
}
}
Output:
closedir(dirp);
Enter directory name
oslab
openreaddir.c
a.out
..vidhya.c
vidhya.

1.EXPERMENT NO. 3
2.NAME OF THE EXPERMENT:
Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and
Prevention

AIM:
Banker’s Algorithm:

When a new process enters a system, it must declare the maximum number of
instances of each resource type it needed. This number may exceed the total number of
resources in the system. When the user request a set of resources, the system must
determine whether the allocation of each resources will leave the system in safe state. If it
will the resources are allocation; otherwise the process must wait until some other
process release the resources.

Data structures
 n-Number of process, m-number of resource types.
 Available: Available[j]=k, k – instance of resource type Rj is available.
 Max: If max[i, j]=k, Pi may request at most k instances resource Rj.
 Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj
 Need: If Need[I, j]=k, Pi may need k more instances of resource type Rj,
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.
ALGORITHM:
1. Start the program.
2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety.
9. or not if we allow the request.
10. stop the program.

PROGRAM: /* BANKER’S ALGORITHM */


#include<stdio.h>
#include<conio.h>
struct da
{
int max[10],a1[10],need[10],before[10],after[10];
}p[10];
void main()
{
int i,j,k,l,r,n,tot[10],av[10],cn=0,cz=0,temp=0,c=0;
clrscr();
printf("\n ENTER THE NO. OF PROCESSES:");
scanf("%d",&n);
printf("\n ENTER THE NO. OF RESOURCES:");
scanf("%d",&r);
for(i=0;i<n;i++)
{
printf("PROCESS %d \n",i+1);
for(j=0;j<r;j++)
{
printf("MAXIMUM VALUE FOR RESOURCE %d:",j+1);
scanf("%d",&p[i].max[j]);
}
for(j=0;j<r;j++)
{
printf("ALLOCATED FROM RESOURCE %d:",j+1);
scanf("%d",&p[i].a1[j]);
p[i].need[j]=p[i].max[j]-p[i].a1[j];
}
}
for(i=0;i<r;i++)
{
printf("ENTER TOTAL VALUE OF RESOURCE %d:",i+1);
scanf("%d",&tot[i]);
}
for(i=0;i<r;i++)
{
for(j=0;j<n;j++)
temp=temp+p[j].a1[i];
av[i]=tot[i]-temp;
temp=0;
}
printf("\n\t RESOURCES ALLOCATED NEEDED TOTAL AVAIL");
for(i=0;i<n;i++)
{
printf("\n P%d \t",i+1);
for(j=0;j<r;j++)
printf("%d",p[i].max[j]);
printf("\t");
for(j=0;j<r;j++)
printf("%d",p[i].a1[j]);
printf("\t");
for(j=0;j<r;j++)
printf("%d",p[i].need[j]);
printf("\t");
for(j=0;j<r;j++)
{
if(i==0)
printf("%d",tot[j]);
}
printf(" ");
for(j=0;j<r;j++)
{
if(i==0)
printf("%d",av[j]);
}
}
printf("\n\n\t AVAIL BEFORE\T AVAIL AFTER ");
for(l=0;l<n;l++)
{
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
if(p[i].need[j] >av[j])
cn++;
if(p[i].max[j]==0)
cz++;
}
if(cn==0 && cz!=r)
{
for(j=0;j<r;j++)
{
p[i].before[j]=av[j]-p[i].need[j];
p[i].after[j]=p[i].before[j]+p[i].max[j];
av[j]=p[i].after[j];
p[i].max[j]=0;
}
printf("\n P %d \t",i+1);
for(j=0;j<r;j++)
printf("%d",p[i].before[j]);
printf("\t");
for(j=0;j<r;j++)
printf("%d",p[i].after[j]);
cn=0;
cz=0;
c++;
break;
}
else
{
cn=0;cz=0;
}
}
}
if(c==n)
printf("\n THE ABOVE SEQUENCE IS A SAFE SEQUENCE");
else
printf("\n DEADLOCK OCCURED");
getch();
}

OUTPUT:

//TEST CASE 1:

ENTER THE NO. OF PROCESSES:4

ENTER THE NO. OF RESOURCES:3


PROCESS 1
MAXIMUM VALUE FOR RESOURCE 1:3
MAXIMUM VALUE FOR RESOURCE 2:2
MAXIMUM VALUE FOR RESOURCE 3:2
ALLOCATED FROM RESOURCE 1:1
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:0
PROCESS 2
MAXIMUM VALUE FOR RESOURCE 1:6
MAXIMUM VALUE FOR RESOURCE 2:1
MAXIMUM VALUE FOR RESOURCE 3:3
ALLOCATED FROM RESOURCE 1:5
ALLOCATED FROM RESOURCE 2:1
ALLOCATED FROM RESOURCE 3:1
PROCESS 3
MAXIMUM VALUE FOR RESOURCE 1:3MAXIMUM VALUE FOR RESOURCE
2:1
MAXIMUM VALUE FOR RESOURCE 3:4
ALLOCATED FROM RESOURCE 1:2
ALLOCATED FROM RESOURCE 2:1
ALLOCATED FROM RESOURCE 3:1
PROCESS 4
MAXIMUM VALUE FOR RESOURCE 1:4
MAXIMUM VALUE FOR RESOURCE 2:2
MAXIMUM VALUE FOR RESOURCE 3:2
ALLOCATED FROM RESOURCE 1:0
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:2
ENTER TOTAL VALUE OF RESOURCE 1:9
ENTER TOTAL VALUE OF RESOURCE 2:3
ENTER TOTAL VALUE OF RESOURCE 3:6

RESOURCES ALLOCATED NEEDED TOTAL AVAIL


P1 322 100 222 936 112
P2 613 511 102
P3 314 211 103
P4 422 002 420

AVAIL BEFORE AVAIL AFTER


P2 010 623
P1 401 723
P3 620 934
P4 514 936

THE ABOVE SEQUENCE IS A SAFE SEQUENCE

//TEST CASE:2

ENTER THE NO. OF PROCESSES:4

ENTER THE NO. OF RESOURCES:3


PROCESS 1
MAXIMUM VALUE FOR RESOURCE 1:3
MAXIMUM VALUE FOR RESOURCE 2:2
MAXIMUM VALUE FOR RESOURCE 3:2
ALLOCATED FROM RESOURCE 1:1
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:1
PROCESS 2
MAXIMUM VALUE FOR RESOURCE 1:6
MAXIMUM VALUE FOR RESOURCE 2:1
MAXIMUM VALUE FOR RESOURCE 3:3
ALLOCATED FROM RESOURCE 1:5
ALLOCATED FROM RESOURCE 2:1
ALLOCATED FROM RESOURCE 3:1
PROCESS 3
MAXIMUM VALUE FOR RESOURCE 1:3
MAXIMUM VALUE FOR RESOURCE 2:1
MAXIMUM VALUE FOR RESOURCE 3:4
ALLOCATED FROM RESOURCE 1:2
ALLOCATED FROM RESOURCE 2:1
ALLOCATED FROM RESOURCE 3:2
PROCESS 4
MAXIMUM VALUE FOR RESOURCE 1:4
MAXIMUM VALUE FOR RESOURCE 2:2
MAXIMUM VALUE FOR RESOURCE 3:2
ALLOCATED FROM RESOURCE 1:0
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:2
ENTER TOTAL VALUE OF RESOURCE 1:9
ENTER TOTAL VALUE OF RESOURCE 2:3
ENTER TOTAL VALUE OF RESOURCE 3:6

RESOURCES ALLOCATED NEEDED TOTAL AVAIL


P1 322 101 221 936 110
P2 613 511 102
P3 314 212 102
P4 422 002 420

AVAIL BEFORE AVAIL AFTER


DEADLOCK OCCURRED

1.EXPERMENT NO .4

2.NAME OF THE EXPERMENT: Write a C program to implement the


Producer – Consumer problem using semaphores using UNIX/LINUX system calls

ALGORITHM:

Step 1: The Semaphore mutex, full & empty are initialized.


Step 2: In the case of producer process
i) Produce an item in to temporary variable.
ii) If there is empty space in the buffer check the mutex value for enter into the critical
section.
iii) If the mutex value is 0, allow the producer to add value in the temporary variable to
the buffer.

Step 3: In the case of consumer process


i) It should wait if the buffer is empty
ii) If there is any item in the buffer check for mutex value, if the mutex==0, remove item
from buffer
iii) Signal the mutex value and reduce the empty value by 1.
iv) Consume the item.

Step 4: Print the result

PROGRAM :
#include<stdio.h>
void 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 \t 3. Exit”);
printf(“\nEnter your choice: ”);
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:
1. Produce 2. Consume 3. Exit
Enter your choice: 2

Buffer is Empty
1. Produce 2. Consume 3. Exit
Enter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. Exit
Enter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. Exit
Enter your choice: 3

1.EXPERMENT NO.5
2.NAME OF THE EXPOERMENT: Write C programs to illustrate the following
IPC mechanisms
a) Pipes b) FIFOs c) Message Queues d) Shared Memory

(a)PIPES:
AIM:
To implement the interprocess communication using pipes.
ALGORITHM:
1. Start the program
2. Create the child process using fork()
3. Create the pipe structure using pipe()
4. Now close the read end of the parent process using close()
5. Write the data in the pip[e using write()
6. Now close the write end of child process using close()
7. Read the data in the pipe using read()
8. Display the string
9. Stop the program.

PROGRAM:
#include<stdio.h>
int main()
{
int fd[2],child;
char a[10];
printf("\n enter the string to enter into the pipe:");
scanf("%s",a);
pipe(fd);
child=fork();
if(!child)
{ close(fd[10]);
write(fd[1],a,5);
wait(0);
}
else
{
close(fd[1]);
read(fd[0],a,5);
printf("\n the string retrived from pipe is %s\n",a);
}
return 0;
}

OUTPUT:
enter the string to enter into the pipe:computer
the string retrived from pipe is computer
RESULT:
Thus the program has been executed and the output is verified successfully.

B)FIFOs:(First In First Out):


ALGORITHEM:
Step 1 − Create two processes, one is fifoserver and another one is fifoclient.
Step 2 − Server process performs the following −
 Creates a named pipe (using system call mknod()) with name “MYFIFO”, if not
created.
 Opens the named pipe for read only purposes.
 Here, created FIFO with permissions of read and write for Owner. Read for
Group and no permissions for Others.
 Waits infinitely for message from the Client.
 If the message received from the client is not “end”, prints the message. If the
message is “end”, closes the fifo and ends the process.
Step 3 − Client process performs the following −
 Opens the named pipe for write only purposes.
 Accepts the string from the user.
 Checks, if the user enters “end” or other than “end”. Either way, it sends a
message to the server. However, if the string is “end”, this closes the FIFO and
also ends the process.
 Repeats infinitely until the user enters string “end”.
/* FILENAME: FIFOSERVER.C */

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

#define FIFO_FILE "MYFIFO"


int main() {
int fd;
char readbuf[80];
char end[10];
int to_end;
int read_bytes;

/* Create the FIFO if it does not exist */


mknod(FIFO_FILE, S_IFIFO|0640, 0);
strcpy(end, "end");
while(1) {
fd = open(FIFO_FILE, O_RDONLY);
read_bytes = read(fd, readbuf, sizeof(readbuf));
readbuf[read_bytes] = '\0';

printf("Received string: \"%s\" and length is %d\n",


readbuf, (int)strlen(readbuf));
to_end = strcmp(readbuf, end);
if (to_end == 0) {
close(fd);
break;
}
}
return 0;
}
OUTPUT:

Received string: "this is string 1" and length is 16


Received string: "fifo test" and length is 9
Received string: "fifo client and server" and length is 22
Received string: "end" and length is 3

PROGRAM : FIFO CLIENT.C FILE


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

#define FIFO_FILE "MYFIFO"


int main() {
int fd;
int end_process;
int stringlen;
char readbuf[80];
char end_str[5];
printf("FIFO_CLIENT: Send messages, infinitely, to end enter \"end\"\n");
fd = open(FIFO_FILE, O_CREAT|O_WRONLY);
strcpy(end_str, "end");

while (1) {
printf("Enter string: ");
fgets(readbuf, sizeof(readbuf), stdin);
stringlen = strlen(readbuf);
readbuf[stringlen - 1] = '\0';
end_process = strcmp(readbuf, end_str);

//printf("end_process is %d\n", end_process);


if (end_process != 0) {
write(fd, readbuf, strlen(readbuf));
printf("Sent string: \"%s\" and string length is %d\n", readbuf, (int)strlen(readbuf));
} else {
write(fd, readbuf, strlen(readbuf));
printf("Sent string: \"%s\" and string length is %d\n", readbuf, (int)strlen(readbuf));
close(fd);
break;
}
}
return 0;
}

OUTPUT:

FIFO_CLIENT: Send messages, infinitely, to end enter "end"


Enter string: this is string 1
Sent string: "this is string 1" and string length is 16
Enter string: fifo test
Sent string: "fifo test" and string length is 9
Enter string: fifo client and server
Sent string: "fifo client and server" and string length is 22
Enter string: end
Sent string: "end" and string length is 3
(C)MESSAGE QUEUE:
AIM:
To implement the interprocess communication using message passing.

ALGORITHM:
1. Start the program
2. Create two files msgsend and msgrecv.c
3. Msgsend creates a message queue with a basic key and message flag msgflg =
IPC_CREAT | 0666 -- create queue and make it read and appendable by all, and sends
one message to the queue.
4. Msgrecv reads the message from the queue

5. A message of type (sbuf.mtype) 1 is sent to the queue with the message ``Did you get
this?''
6. The Message queue is opened with msgget (message flag 0666) and the same key as
message_send.c
7. A message of the same type 1 is received from the queue with the message ``Did you
get
this?'' stored in rbuf.mtext.
8. Stop the program.

PROGRAM:
Msgsend:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#define MSGSZ 128
typedef struct msgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;
main()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
message_buf sbuf;
size_t buf_length;
key = 1234;
(void) fprintf(stderr, "\nmsgget: Calling msgget(%#lx,\
%#o)\n",
key, msgflg);
if ((msqid = msgget(key, msgflg )) < 0) {
perror("msgget");
exit(1);
}
else
(void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid);
sbuf.mtype = 1;
(void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid);
(void) strcpy(sbuf.mtext, "Did you get this?");
(void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid);
buf_length = strlen(sbuf.mtext) + 1 ;
if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) {
printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buf_length);
perror("msgsnd");
exit(1);
}
else
printf("Message: \"%s\" Sent\n", sbuf.mtext);
exit(0);
}

Msgrecv:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#define MSGSZ 128
typedef struct msgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;
main()
{
int msqid; key_t
key; message_buf
rbuf;
key = 1234;
if ((msqid = msgget(key, 0666)) < 0) {
perror("msgget");
exit(1);
}
if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) {

perror("msgrcv");
exit(1);
}
printf("%s\n", rbuf.mtext);
eixit(0);
}

OUTPUT:
“Did you get this?”
RESULT:
Thus the program has been executed successfully and the output is verified.

(D)SHARED MEMORY:
AIM:
To implement the interprocess communication using shared memory.

ALGORITHM:
1. Start the program
2. Declare the necessary variables
3. shmat() and shmdt() are used to attach and detach shared memory segments. They are
prototypes as follows:
void *shmat(int shmid, const void *shmaddr, int shmflg);
int shmdt(const void *shmaddr);
4. shmat() returns a pointer, shmaddr, to the head of the shared segment associated with a
valid
shmid. shmdt() detaches the shared memory segment located at the address indicated by
shmaddr
5. Shared1.c simply creates the string and shared memory portion.
6. Shared2.c attaches itself to the created shared memory portion and uses the string
(printf)
7. Stop the program.

PROGRAM:
Shared1.c:
#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;
key = 5678;
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit(1);
}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}

Shared2.c
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHMSZ 27
main()
{
int shmid;
key_t key;
char *shm, *s;
key = 5678;
if ((shmid = shmget(key, SHMSZ, 0666)) < 0) {
perror("shmget");
exit(1);
}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
for (s = shm; *s != NULL; s++)
putchar(*s);
putchar('\n');
*shm = '*';
exit(0);
}
OUTPUT:
Abcdefghijklmnopqrstuvwxyz
RESULT:
Thus the program has been executed successfully and the output is verified.

1.EXPERMENT NO:6
2NAME OF THE EXPERMENT:write a C program to simulate the following
memory management techniques.
A) Paging,. B) segmentation.

A) PAGING

ALGORITHM:
Step1 : Start the program.
Step2 : Read the base address, page size, number of pages and memory unit.
Step3 : If the memory limit is less than the base address display the memory
limit is less than limit.
Step4 : Create the page table with the number of pages and page address.
Step5 : Read the page number and displacement value.
Step6 : If the page number and displacement value is valid, add the displacement
value with the address corresponding to the page number and display the
result.
Step7 : Display the page is not found or displacement should be less than page
size.
Step8 : Stop the program.

PROGRAM:
#include<stdio.h>
#include<unistd.h>
void main()
{
int b[20],n,i,pa,p,a,d;
printf(“\nProgram for paging”);
scanf(“%d”,&n);
printf(“\nEnter the base address:”);
for(i=0;i<n;i++)
{
scanf(“%d”,&b[i]);
}
printf(“\nEnter the logical address:”);
scanf(“%d”,&p);
for(i=0;i<n;i++)
{
if(i==p)
{
pa=b[i]+d;
a=b[i];
printf(“\n\tPageNo.\t BaseAdd. PhysicalAdd. \n\t %d \t %d \t %d \t “,pa,a,p);
}
printf(“\nInvalid page”);
}

Sample Input 1:
Program for paging
Enter the number of pages:2
Enter the base address:
100
150
Enter the Logical address:50
Enter the page number:1
Sample Output 1:
PageNo. BaseAdd. PhysicalAdd.
1 150 200

Sample Input 2:
Program for paging
Enter the number of pages:1
Enter the base address:
100
Enter the Logical address:2
Enter the page number:2
Sample Output 2:
Invalid page

B) SEGMENTATION
ALGORITHM:
Step1 : Start the program.
Step2 : Read the base address, number of segments, size of each segment, memory
limit.
Step3 : If memory address is less than the base address display “invalid memory
limit”.
Step4 : Create the segment table with the segment number and segment address and
display it.
Step5 : Read the segment number and displacement.
Step6 : If the segment number and displacement is valid compute the real address and
display the same.
Step7 : Stop the program.

PROGRAM:
#include<stdio.h>
#include<unistd.h>
void main()
{
int b[20],l[20],n,i,pa,s,a,d;
printf(“\nProgram for segmentation”);
printf(“\nEnter the number of segments:”);
scanf(“%d”,&n);
printf(“\nEnter the base address and limit register:”);
for(i=0;i<n;i++)
{
scanf(“%d”,&b[i]);
scanf(“%d”,&l[i])
}
printf(“\nEnter the logical address:”);
scanf(“%d”,&d);
for(i=0;i<n;i++)
{
if(i==s)
{
if(d<l[i])
{
pa=b[i]+d;
a=b[i]
printf(“(“\n\tPageNo.\t BaseAdd. PhysicalAdd. \n\t %d \t %d \t
%d \t ”,s,a,pa);
exit(0);
}
else
{
printf(“\nPage size exceeds”);
exit(0);
}
}
}
printf(“\nInvalid segment”);
}
Sample Input 1:
Program for segmentation
Enter the number of segments:3
Enter the base address and limit register:
100 50
150 20
130 34
Enter the Logical address:25
Enter the segment number:1
Sample Output 1:
PageNo. BaseAdd. PhysicalAdd.
2 130 155
Sample Input 2:
Program for segmentation
Enter the number of segments:2
Enter the Logical address and limit register:
100 50
150 20
Enter the logical address:25
Enter the segment number:1
Sample Output 2:
page size exceeds

You might also like