0% found this document useful (0 votes)
241 views46 pages

Write C Programs To Simulate The Following CPU Scheduling Algorithms

Uploaded by

shaikilyas0579
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
241 views46 pages

Write C Programs To Simulate The Following CPU Scheduling Algorithms

Uploaded by

shaikilyas0579
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Write C programs to simulate the following CPU Scheduling algorithms

a) FCFS b) SJF c) Round Robin d) priority

1(a) FCFS SCHEDULING

Aim: Write a C program to implement the various process scheduling mechanisms such
Algorithm for FCFS 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: 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
Waiting time for process(n)= waiting time of process (n-1) + Burst time of process (n-1)
Turn around time for Process(n)= waiting time of Process(n)+ Burst time for process(n)
Step 6: Calculate
Average waiting time = Total waiting Time / Number of process
Average Turnaround time = Total Turnaround Time / Number of process

Step 7: Stop the process


/* 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
Ex. No: 1(b) SJF SCHEDULING

Aim: Write a C program to implement the various process scheduling mechanisms such as SJF
Scheduling .

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
Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-1)
Turn around time for Process(n)= waiting time of Process(n)+ Burst time for process(n)
Step 6: Calculate
Average waiting time = Total waiting Time / Number of process
Average Turnaround time = Total Turnaround Time / Number of process
Step 7: Stop the process
/* 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
1(c) ROUND ROBIN SCHEDULING

Aim: Write a C program to implement the various process scheduling mechanisms such as 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

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)

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
Average waiting time = Total waiting Time / Number of process
Average Turnaround time = Total Turnaround Time / Number of process

Step 8: Stop the process


/* 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(d) PRIORITY SCHEDULING

Aim: Write a C program to implement the various process scheduling mechanisms such as 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


Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-1)
Turn around time for Process(n)= waiting time of Process(n)+ Burst time for process(n)

Step 7: Calculate
Average waiting time = Total waiting Time / Number of process
Average Turnaround time = Total Turnaround Time / Number of process

Step 8: Stop the process


/* 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
2. Write programs using the I/O system calls of UNIX/LINUX operating system
(open, read, write, close, fcntl, seek, stat, opendir, readdir)

2.1 C program to illustrate open system call

#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
extern int errno;
int main()
{
// if file does not have in directory
// then file foo.txt is created.
int fd = open("foo.txt", O_RDONLY | O_CREAT);

printf("fd = %d/n", fd);

if (fd ==-1)
{
// print which type of error have in a code
printf("Error Number % d\n", errno);

// print program detail "Success or failure"


perror("Program");
}
return 0;
}

Output :

Fd =3
2.2 C program to illustrate read system Call

#include<stdio.h>
#include <fcntl.h>
int main()
{
int fd, sz;
char *c = (char *) calloc(100, sizeof(char));

fd = open("foo.txt", O_RDONLY);
if (fd < 0) { perror("r1"); exit(1); }

sz = read(fd, c, 10);
printf("called read(% d, c, 10). returned that"
" %d bytes were read.\n", fd, sz);
c[sz] = '\0';
printf("Those bytes are as follows: % s\n", c);
}

Output :

Welcome to
// C program to illustrate read system Call

#include<stdio.h>
#include<fcntl.h>

int main()
{
char c;
int fd1 = Open("foobar.txt", O_RDONLY, 0);
int fd2 = Open("foobar.txt", O_RDONLY, 0);
Read(fd1, &c, 1);
Read(fd2, &c, 1);
printf("c = % c\n", c);
exit(0);
}

Output :
C= w
2.4 C program to illustrate close system Call

#include<stdio.h>
#include <fcntl.h>
int main()
{
int fd1 = open("foo.txt", O_RDONLY);
if (fd1 < 0)
{
perror("c1");
exit(1);
}
printf("opened the fd = % d\n", fd1);

// Using close system Call


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

Output :

Closed the fd
3. Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and
Prevention.

BANKER’S ALGORITHM

AIM: To implement deadlock avoidance & Prevention by using Banker’s Algorithm. Deadlock
avoidance & Dead Lock Prevention

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
Work and Finish be the vector of length m and n respectively, Work=Available and Finish[i]
=False.
Find an i such that both
Finish[i] =False
Need<=Work
If no such I exists go to step 4.
work=work+Allocation, Finish[i] =True;
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.
if Request<=Need I go to step 2. Otherwise raise an error condition.
if Request<=Available go to step 3. Otherwise Pi must since the resources are available.
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:

Start the program.


Get the values of resources and processes.
Get the avail value.
After allocation find the need value.
Check whether its possible to allocate.
If it is possible then the system is in safe state.
Else system is not in safety state.
If the new request comes then check that the system is in safety.
or not if we allow the request.
stop the 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: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: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 OCCURED
4. Write a C program to implement the Producer – Consumer problem using semaphores
using UNIX/LINUX system calls.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

/*
use the pthread flag with gcc to compile this code
~$ gcc -pthread producer_consumer.c -o producer_consumer
*/

pthread_t *producers;
pthread_t *consumers;
sem_t buf_mutex,empty_count,fill_count;
int *buf,buf_pos=-1,prod_count,con_count,buf_len;
int produce(pthread_t self){
int i = 0;
int p = 1 + rand()%40;
while(!pthread_equal(*(producers+i),self) && i < prod_count){
i++;
}
printf("Producer %d produced %d \n",i+1,p);
return p;
}

void consume(int p,pthread_t self){


int i = 0;
while(!pthread_equal(*(consumers+i),self) && i < con_count){
i++;
}
printf("Buffer:");
for(i=0;i<=buf_pos;++i)
printf("%d ",*(buf+i));
printf("\nConsumer %d consumed %d \nCurrent buffer len: %d\n",i+1,p,buf_pos);
}

void* producer(void *args){

while(1){
int p = produce(pthread_self());
sem_wait(&empty_count);
sem_wait(&buf_mutex);
++buf_pos; // critical section
*(buf + buf_pos) = p;
sem_post(&buf_mutex);
sem_post(&fill_count);
sleep(1 + rand()%3);
}
return NULL;
}

void* consumer(void *args){


int c;
while(1){
sem_wait(&fill_count);
sem_wait(&buf_mutex);
c = *(buf+buf_pos);
consume(c,pthread_self());
--buf_pos;
sem_post(&buf_mutex);
sem_post(&empty_count);
sleep(1+rand()%5);
}
return NULL;
}

int main(void){

int i,err;
srand(time(NULL));
sem_init(&buf_mutex,0,1);
sem_init(&fill_count,0,0);
printf("Enter the number of Producers:");
scanf("%d",&prod_count);
producers = (pthread_t*) malloc(prod_count*sizeof(pthread_t));
printf("Enter the number of Consumers:");
scanf("%d",&con_count);
consumers = (pthread_t*) malloc(con_count*sizeof(pthread_t));
printf("Enter buffer capacity:");
scanf("%d",&buf_len);
buf = (int*) malloc(buf_len*sizeof(int));
sem_init(&empty_count,0,buf_len);
for(i=0;i<prod_count;i++){
err = pthread_create(producers+i,NULL,&producer,NULL);
if(err != 0){
printf("Error creating producer %d: %s\n",i+1,strerror(err));
}else{
printf("Successfully created producer %d\n",i+1);
}
}
for(i=0;i<con_count;i++){
err = pthread_create(consumers+i,NULL,&consumer,NULL);
if(err != 0){
printf("Error creating consumer %d: %s\n",i+1,strerror(err));
}else{
printf("Successfully created consumer %d\n",i+1);
}
}
for(i=0;i<prod_count;i++){
pthread_join(*(producers+i),NULL);
}
for(i=0;i<con_count;i++){
pthread_join(*(consumers+i),NULL);
}
return 0;
}
5. Write C programs to illustrate the following IPC mechanisms

a) Pipes
#include<stdio.h>
#include<unistd.h>
int main()
{
int pipefds[2];
int returnstatus;
int pid;
char writemessages[2][20]={"Hi","Hello"};
char readmessage[20];
returnstatus=pipe(pipefds);
if(returnstatus==-1){
printf("Unable to create pipe\n");
return 1;
}
pid=fork();
//Child process
if(pid==0){
read(pipefds[0],readmessage,sizeof(readmessage));
printf("Child Process-Reading from pipe-Message 1 is %s\n",readmessage);
read(pipefds[0],readmessage,sizeof(readmessage));
printf("Child Process-Reading from pipe-Message 2 is %s\n",readmessage);
}else{//Parent process
printf("Parent Process-Writing to pipe-Message 1 is %s",writemessages[1],
sizeof(writemessages[1]));
}
return 0;
}
Execution Steps:

Compilation

gcc pipewithprocesses.c –o pipewithprocesses

Execution
Parent Process - Writing to pipe - Message 1 is Hi
Parent Process - Writing to pipe - Message 2 is Hello
Child Process - Reading from pipe – Message 1 is Hi
Child Process - Reading from pipe – Message 2 is Hello

b) FIFO

/* 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;
}
Compilation and Execution Steps
gcc -o test fifoserver.c
./test
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

/* Filename: fifoclient.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;
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;
}

Compilation and Execution Steps


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

/* Filename: msgq_send.c */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define PERMS 0644


struct my_msgbuf {
long mtype;
char mtext[200];
};

int main(void) {
struct my_msgbuf buf;
int msqid;
int len;
key_t key;
system("touch msgq.txt");

if ((key = ftok("msgq.txt", 'B')) == -1) {


perror("ftok");
exit(1);
}

if ((msqid = msgget(key, PERMS | IPC_CREAT)) == -1) {


perror("msgget");
exit(1);
}
printf("message queue: ready to send messages.\n");
printf("Enter lines of text, ^D to quit:\n");
buf.mtype = 1; /* we don't really care in this case */

while(fgets(buf.mtext, sizeof buf.mtext, stdin) != NULL) {


len = strlen(buf.mtext);
/* remove newline at end, if it exists */
if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0';
if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '\0' */
perror("msgsnd");
}
strcpy(buf.mtext, "end");
len = strlen(buf.mtext);
if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '\0' */
perror("msgsnd");

if (msgctl(msqid, IPC_RMID, NULL) == -1) {


perror("msgctl");
exit(1);
}
printf("message queue: done sending messages.\n");
return 0;
}

Compilation and Execution Steps


message queue: ready to send messages.
Enter lines of text, ^D to quit:
this is line 1
this is line 2
message queue: done sending messages.

/* Filename: msgq_recv.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define PERMS 0644


struct my_msgbuf {
long mtype;
char mtext[200];
};

int main(void) {
struct my_msgbuf buf;
int msqid;
int toend;
key_t key;

if ((key = ftok("msgq.txt", 'B')) == -1) {


perror("ftok");
exit(1);
}

if ((msqid = msgget(key, PERMS)) == -1) { /* connect to the queue */


perror("msgget");
exit(1);
}
printf("message queue: ready to receive messages.\n");

for(;;) { /* normally receiving never ends but just to make conclusion


/* this program ends wuth string of end */
if (msgrcv(msqid, &buf, sizeof(buf.mtext), 0, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("recvd: \"%s\"\n", buf.mtext);
toend = strcmp(buf.mtext,"end");
if (toend == 0)
break;
}
printf("message queue: done receiving messages.\n");
system("rm msgq.txt");
return 0;
}

Compilation and Execution Steps


message queue: ready to receive messages.
recvd: "this is line 1"
recvd: "this is line 2"
recvd: "end"
message queue: done receiving messages.

d) Shaerd Memory

/* Filename: shm_write.c */
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>

#define BUF_SIZE 1024


#define SHM_KEY 0x1234

struct shmseg {
int cnt;
int complete;
char buf[BUF_SIZE];
};
int fill_buffer(char * bufptr, int size);

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


int shmid, numtimes;
struct shmseg *shmp;
char *bufptr;
int spaceavailable;
shmid = shmget(SHM_KEY, sizeof(struct shmseg), 0644|IPC_CREAT);
if (shmid == -1) {
perror("Shared memory");
return 1;
}

// Attach to the segment to get a pointer to it.


shmp = shmat(shmid, NULL, 0);
if (shmp == (void *) -1) {
perror("Shared memory attach");
return 1;
}

/* Transfer blocks of data from buffer to shared memory */


bufptr = shmp->buf;
spaceavailable = BUF_SIZE;
for (numtimes = 0; numtimes < 5; numtimes++) {
shmp->cnt = fill_buffer(bufptr, spaceavailable);
shmp->complete = 0;
printf("Writing Process: Shared Memory Write: Wrote %d bytes\n", shmp->cnt);
bufptr = shmp->buf;
spaceavailable = BUF_SIZE;
sleep(3);
}
printf("Writing Process: Wrote %d times\n", numtimes);
shmp->complete = 1;

if (shmdt(shmp) == -1) {
perror("shmdt");
return 1;
}

if (shmctl(shmid, IPC_RMID, 0) == -1) {


perror("shmctl");
return 1;
}
printf("Writing Process: Complete\n");
return 0;
}

int fill_buffer(char * bufptr, int size) {


static char ch = 'A';
int filled_count;

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


memset(bufptr, ch, size - 1);
bufptr[size-1] = '\0';
if (ch > 122)
ch = 65;
if ( (ch >= 65) && (ch <= 122) ) {
if ( (ch >= 91) && (ch <= 96) ) {
ch = 65;
}
}
filled_count = strlen(bufptr);

//printf("buffer count is: %d\n", filled_count);


//printf("buffer filled is:%s\n", bufptr);
ch++;
return filled_count;
}

Compilation and Execution Steps


Writing Process: Shared Memory Write: Wrote 1023 bytes
Writing Process: Shared Memory Write: Wrote 1023 bytes
Writing Process: Shared Memory Write: Wrote 1023 bytes
Writing Process: Shared Memory Write: Wrote 1023 bytes
Writing Process: Shared Memory Write: Wrote 1023 bytes
Writing Process: Wrote 5 times
Writing Process: Complete

/* Filename: shm_read.c */
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>

#define BUF_SIZE 1024


#define SHM_KEY 0x1234

struct shmseg {
int cnt;
int complete;
char buf[BUF_SIZE];
};

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


int shmid;
struct shmseg *shmp;
shmid = shmget(SHM_KEY, sizeof(struct shmseg), 0644|IPC_CREAT);
if (shmid == -1) {
perror("Shared memory");
return 1;
}

// Attach to the segment to get a pointer to it.


shmp = shmat(shmid, NULL, 0);
if (shmp == (void *) -1) {
perror("Shared memory attach");
return 1;
}

/* Transfer blocks of data from shared memory to stdout*/


while (shmp->complete != 1) {
printf("segment contains : \n\"%s\"\n", shmp->buf);
if (shmp->cnt == -1) {
perror("read");
return 1;
}
printf("Reading Process: Shared Memory: Read %d bytes\n", shmp->cnt);
sleep(3);
}
printf("Reading Process: Reading Done, Detaching Shared Memory\n");
if (shmdt(shmp) == -1) {
perror("shmdt");
return 1;
}
printf("Reading Process: Complete\n");
return 0;
}

Compilation and Execution Steps


segment contains :
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEE
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"
Reading Process: Shared Memory: Read 1023 bytes
Reading Process: Reading Done, Detaching Shared Memory
Reading Process: Complete
6. Write C programs to simulate the following memory management techniques

a) Paging b) Segmentation

PAGING

Aim: To implement the Memory management policy- Paging.


Algorithm:
Step 1: Read all the necessary input from the keyboard.
Step 2: Pages - Logical memory is broken into fixed - sized blocks.
Step 3: Frames – Physical memory is broken into fixed – sized blocks.
Step 4: Calculate the physical address using the following
Physical address = ( Frame number * Frame size ) + offset
Step 5: Display the physical address.
Step 6: Stop the process.

/* Memory Allocation with Paging Technique */

#include <stdio.h>
#include <conio.h>
struct pstruct
{
int fno;
int pbit;
}ptable[10];

int pmsize,lmsize,psize,frame,page,ftable[20],frameno;

void info()
{
printf("\n\nMEMORY MANAGEMENT USING PAGING\n\n");
printf("\n\nEnter the Size of Physical memory: ");
scanf("%d",&pmsize);
printf("\n\nEnter the size of Logical memory: ");
scanf("%d",&lmsize);
printf("\n\nEnter the partition size: ");
scanf("%d",&psize);
frame = (int) pmsize/psize;
page = (int) lmsize/psize;
printf("\nThe physical memory is divided into %d no.of frames\n",frame);
printf("\nThe Logical memory is divided into %d no.of pages",page);
}

void assign()
{
int i;
for (i=0;i<page;i++)
{
ptable[i].fno = -1;
ptable[i].pbit= -1;
}
for(i=0; i<frame;i++)
ftable[i] = 32555;
for (i=0;i<page;i++)
{
printf("\n\nEnter the Frame number where page %d must be placed: ",i);
scanf("%d",&frameno);
ftable[frameno] = i;
if(ptable[i].pbit == -1)
{
ptable[i].fno = frameno;
ptable[i].pbit = 1;
}
}
getch();
// clrscr();
printf("\n\nPAGE TABLE\n\n");
printf("PageAddress FrameNo. PresenceBit\n\n");
for (i=0;i<page;i++)
printf("%d\t\t%d\t\t%d\n",i,ptable[i].fno,ptable[i].pbit);
printf("\n\n\n\tFRAME TABLE\n\n");
printf("FrameAddress PageNo\n\n");
for(i=0;i<frame;i++)
printf("%d\t\t%d\n",i,ftable[i]);
}
void cphyaddr()
{
int laddr,paddr,disp,phyaddr,baddr;
getch();
// clrscr();
printf("\n\n\n\tProcess to create the Physical Address\n\n");
printf("\nEnter the Base Address: ");
scanf("%d",&baddr);
printf("\nEnter theLogical Address: ");
scanf("%d",&laddr);

paddr = laddr / psize;


disp = laddr % psize;
if(ptable[paddr].pbit == 1 )
phyaddr = baddr + (ptable[paddr].fno*psize) + disp;
printf("\nThe Physical Address where the instruction present: %d",phyaddr);
}
void main()
{
clrscr();
info();
assign();
cphyaddr();
getch();
}

OUTPUT:

MEMORY MANAGEMENT USING PAGING


Enter the Size of Physical memory: 16
Enter the size of Logical memory: 8
Enter the partition size: 2
The physical memory is divided into 8 no.of frames
The Logical memory is divided into 4 no.of pages
Enter the Frame number where page 0 must be placed: 5
Enter the Frame number where page 1 must be placed: 6
Enter the Frame number where page 2 must be placed: 7
Enter the Frame number where page 3 must be placed: 2
PAGE TABLE
PageAddress FrameNo. PresenceBit
0 5 1
1 6 1
2 7 1
3 2 1
FRAME TABLE
FrameAddress PageNo

0 32555
1 32555
2 3
3 32555
4 32555
5 0
6 1
7 2
Process to create the Physical Address
Enter the Base Address: 1000
Enter theLogical Address: 3

The Physical Address where the instruction present: 1013


SEGMENTATION

AIM:
To implement the memory management policy-segmentation.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the number of segments.
Step 3: get the base address and length for each segment.
Step 4: Get the logical address.
Step 5: check whether the segment number is within the limit, if not display the error
message.
Step 6: Check whether the byte reference is within the limit, if not display the error
message.
Step 7: Calculate the physical memory and display it.
Step 8: Stop the program.
/*MEMORY SEGMENT TABLE*/
#include <stdio.h>
#include <conio.h>
#include <math.h>
int sost;
void gstinfo();
void ptladdr();

struct segtab
{
int sno;
int baddr;
int limit;
int val[10];
}st[10];

void gstinfo()
{
int i,j;
printf("\n\tEnter the size of the segment table: ");
scanf("%d",&sost);

for(i=1;i<=sost;i++)
{
printf("\n\tEnter the information about segment: %d",i);
st[i].sno = i;
printf("\n\tEnter the base Address: ");
scanf("%d",&st[i].baddr);
printf("\n\tEnter the Limit: ");
scanf("%d",&st[i].limit);
for(j=0;j<st[i].limit;j++)
{
printf("Enter the %d address Value: ",(st[i].baddr + j));
scanf("%d",&st[i].val[j]);
}
}
}
void ptladdr()
{
int i,swd,d=0,n,s,disp,paddr;
clrscr();
printf("\n\n\t\t\t SEGMENT TABLE \n\n");
printf("\n\t SEG.NO\tBASE ADDRESS\t LIMIT \n\n");
for(i=1;i<=sost;i++)
printf("\t\t%d \t\t%d\t\t%d\n\n",st[i].sno,st[i].baddr,st[i].limit);
printf("\n\nEnter the logical Address: ");
scanf("%d",&swd);
n=swd;
while (n != 0)
{
n=n/10;
d++;
}

s = swd/pow(10,d-1);
disp = swd%(int)pow(10,d-1);

if(s<=sost)
{
if(disp < st[s].limit)
{
paddr = st[s].baddr + disp;
printf("\n\t\tLogical Address is: %d",swd);
printf("\n\t\tMapped Physical address is: %d",paddr);
printf("\n\tThe value is: %d",( st[s].val[disp] ) );
}
else
printf("\n\t\tLimit of segment %d is high\n\n",s);
}

else
printf("\n\t\tInvalid Segment Address \n");
}
void main()
{
char ch;
clrscr();
gstinfo();
do
{
ptladdr();
printf("\n\t Do U want to Continue(Y/N)");
flushall();
scanf("%c",&ch);
}while (ch == 'Y' || ch == 'y' );

getch();
}
OUTPUT:

Enter the size of the segment table: 3

Enter the information about segment: 1


Enter the base Address: 4
Enter the Limit: 5
Enter the 4 address Value: 11
Enter the 5 address Value: 12
Enter the 6 address Value: 13
Enter the 7 address Value: 14
Enter the 8 address Value: 15

Enter the information about segment: 2


Enter the base Address: 5

Enter the Limit: 4


Enter the 5 address Value: 21
Enter the 6 address Value: 31
Enter the 7 address Value: 41
Enter the 8 address Value: 51

Enter the information about segment: 3


Enter the base Address: 3

Enter the Limit: 4


Enter the 3 address Value: 31
Enter the 4 address Value: 41
Enter the 5 address Value: 41
Enter the 6 address Value: 51

SEGMENT TABLE

SEG.NO BASE ADDRESS LIMIT


1 4 5
2 5 4
3 3 4

Enter the logical Address: 3


Logical Address is: 3
Mapped Physical address is: 3
The value is: 31
Do U want to Continue(Y/N)
SEGMENT TABLE

SEG.NO BASE ADDRESS LIMIT


1 4 5
2 5 4
3 3 4
Enter the logical Address: 1
Logical Address is: 1
Mapped Physical address is: 4
The value is: 11
Do U want to Continue(Y/N)

You might also like