1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>
int main (int argc, char * argv[])
{
int i,in,out,j,score;
int score_d = 0;
int score_g = 0;
in election = 1;
int * score = (int*) malloc (sizeof(int)*atoi(argv[1]));
int * status = (int*) malloc (sizeof(int)*atoi(argv[1]));
int * droite = (int*) malloc (2*sizeof(int)*atoi(argv[1]));
int * gauche = (int*) malloc (2*sizeof(int)*atoi(argv[1]));
time_t t;
for (i = 0 ; i < atoi(argv[1]) ; i++)
{
pipe(&droite[2*i]);
pipe(&gauche[2*(i+atoi(argv[1]-1)]);
time(&t);
srand(t*getpid()*(i+1));
score[i] = (int)rand()*10.0/RAND_MAX;
status[i] = 1;
}
in_droite = droite[((2*i)-2)%(2*atoi(argv[1]))];
out_droite = droite[((2*i)+1)%(2*atoi(argv[1]))];
in_gauche = gauche[((2*i)+2)%(2*atoi(argv[1]))];
out_gauche = gauche[((2*i)-1)%(2*atoi(argv[1]))];
if(argc == 2)
exit(0);
while(election == 1)
{
for(i = 1 ; i < atoi(argv[1]) ; i++)
{
if(fork() == 0)
{
if(j == 0)
{
score = score[i];
printf("Score associe au processus numero %d : %d\n",i,score);
}
else
printf("Score associe au processus numero %d : %d\n",i,buf);
in_droite = droite[((2*i)-2)%(2*atoi(argv[1]))];
out_droite = droite[((2*i)+1)%(2*atoi(argv[1]))];
in_gauche = gauche[((2*i)+2)%(2*atoi(argv[1]))];
out_gauche = gauche[((2*i)-1)%(2*atoi(argv[1]))];
//------- Cas d'echec ------//
//Reception
read(in_droite,&score_d,sizeof(int));
printf ("Fils numero %d recupere à droite : %d\n",i,score_d);
read(in_gauche,&score_g,sizeof(int));
printf ("Fils numero %d recupere à gauche : %d\n",i,buf);
//Evaluation
if(score_d < score_g)
score = score_g;
else
score = score_d;
//Envoi
printf ("Fils numero %d envoie à droite : %d\n",i,score);
write(out_droite,&score,sizeof(int));
printf ("Fils numero %d envoie à gauche : %d\n",i,score);
write(out_gauche,&score,sizeof(int));
exit(0);
}
}
if(j == 0)
{
score = score[0];
score_d = score_g = score;
}
printf("Pere envoie : %d\n",score);
write(out_droite,&score,sizeof(int));
write(out_gauche,&score,sizeof(int));
read(in_droite,&score_d,sizeof(int));
printf("Pere recupere : %d\n",score_g);
read(in_gauche,&score_g,sizeof(int));
printf("Pere recupere : %d\n",score_d);
printf("---------------------------------\n");
}
exit(0);
} |
Partager