C PROGRAM THAT IMPLEMENTS A DINING PHILOSOPHER PROBLEM
#include<stdio.h>
#include<stdlib.h>
#include<semaphore.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#define N 5
#define LEFT (i+4)%N
#include<stdlib.h>
#include<semaphore.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#define N 5
#define LEFT (i+4)%N
#define RIGHT (i+1)%N
#define THINKING 0
#define HUNGRY 1
#define EATING 2
sem_t spoon;
sem_t phil[N];
int state[N];
int phil_num[N]={0,1,2,3,4};
int fd[N][2];// file descriptors for pipes
pid_t pid, pids[N];// process ids
int i;int num;
void philosopher(int i);
void test(int i);
void take_spoon(int i);
void put_spoon(int i);
char buffer[100];
int main(void)
{
for(i=0;i<N;++i)
{
#define HUNGRY 1
#define EATING 2
sem_t spoon;
sem_t phil[N];
int state[N];
int phil_num[N]={0,1,2,3,4};
int fd[N][2];// file descriptors for pipes
pid_t pid, pids[N];// process ids
int i;int num;
void philosopher(int i);
void test(int i);
void take_spoon(int i);
void put_spoon(int i);
char buffer[100];
int main(void)
{
for(i=0;i<N;++i)
{
pipe(fd[i]);
pids[i]= fork();
pids[i]= fork();
printf("i=%d\n",i);
printf("pids[i]=%d\n",pids[i]);
if(pids[i]==0)
{// child
if(pids[i]==0)
{// child
dup2(fd[i][1],1);
close(fd[i][0]);
close(fd[i][1]);
philosopher(i);
exit(0);
}
else
if(pids[i]>0)
{
// parent
}
else
if(pids[i]>0)
{
// parent
dup2(fd[i][0],0);
close(fd[i][0]);
close(fd[i][1]);
}
}// wait for child processes to end
for(i=0;i<N;++i)
waitpid(pids[i],NULL,0);
return 0;
}
void philosopher(int i)
{
while(1)
{
}
}// wait for child processes to end
for(i=0;i<N;++i)
waitpid(pids[i],NULL,0);
return 0;
}
void philosopher(int i)
{
while(1)
{
sleep(1);
take_spoon(i);
sleep(2);
put_spoon(i);
sleep(1);
}
}
void take_spoon(int i)
{
}
}
void take_spoon(int i)
{
sem_wait(&spoon);
state[i]= HUNGRY;
printf("philosopher %d is hungry\n",i+1);
test(i);
sem_post(&spoon);
sem_wait(&phil[i]);
}
void put_spoon(int i)
{
}
void put_spoon(int i)
{
sem_wait(&spoon);
state[i]= THINKING;
printf("philosopher %d puts down spoon %d and %d hin\n",i+1,LEFT+1,i+1);
printf("philosopher %d thinks\n",i+1);
test(LEFT);
test(RIGHT);
sem_post(&spoon);
}
void test(int i)
{
if( state[i]== HUNGRY && state[LEFT]!= EATING && state[RIGHT]!= EATING)
{
}
void test(int i)
{
if( state[i]== HUNGRY && state[LEFT]!= EATING && state[RIGHT]!= EATING)
{
state[i]= EATING;
printf("philosopher %d takes spoon %d and %d\n",i+1,LEFT+1,i+1);
printf("philosopher %d eats\n",i+1);
sem_post(&phil[i]);
}
}
}
}
output:-
0 comments:
Post a Comment