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
|
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <signal.h>
#include "/usr/include/linux/limits.h"
void decremente (int a,int n)
{
int pid,reason;
int tubes[n][2];
int resultat;
int termine=0;
int new_value=a;
int cpt=0;
int lec,ecr;
for (int j=0;j<n;j++){
if(pipe(tubes[j]) == -1){
perror("pipe");
exit(1);
}
}
write(tubes[0][1],&a,sizeof(int));
for(int i=0;i<n;i++){
switch(pid=fork()){
case -1:
perror("fork");
exit(1);
break;
case 0:
lec=tubes[i][0];
ecr=tubes[(i+1)%n][1];
if(read(lec,&new_value,sizeof(int)) == -1){
perror("read");
exit(1);
}
printf("Valeur :%d\n",new_value);
close(lec);
if( new_value == 0 ){
exit(1);
}
new_value--;
if(new_value == 0){
exit(i);
} else {
if(write(ecr,&new_value,sizeof(int)) == -1){
perror("write");
exit(1);
}
}
close (ecr);
break;
default:
if(termine == 0){
if( wait(&reason) == -1)
perror("wait");
resultat = WEXITSTATUS(reason);
termine =1;
}
break;
}
}
if(termine == 1){
for(cpt=0;cpt<n-1;cpt++){
if(wait(&reason) == -1){
perror("wait");
exit(1);
}
}
}
fprintf(stdout, "RESULTAT : %d\n",resultat);
}
int main (int argc, char**argv)
{
if(argc != 3){
perror("Usage : ./exec <a> <n>");
exit(1);
}
decremente(atoi(argv[1]),atoi(argv[2]));
return 0;
} |