The wheel. The main process (A) will create a subprocess (B) that will create another subprocess (C). Then the main process (A) will send the generate a random number (between 1000 and 2000) to process B. The process B will subtract 10 units and will send the number to process C. C will subtract 20 units and will send the number to A. The A process will subtract 30 units and will send the number to B, again. And so on, until the values is less than zero. In this moment the game will stop. The winner is the process that established the negative number.
The communication between all the processes are done using pipe channels.
My solution was:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
int pass(char* id, int in, int out, int x)
{
int n;
read(in, &n, sizeof(int));
printf("%s %d\n", id, n);
n=n-x;
printf("x= %d\n", x);
write(out, &n, sizeof(int));
return n;
}
void closeall(int* a, int* b, int* c)
{
close(a[0]);
close(a[1]);
close(b[0]);
close(b[1]);
close(c[0]);
close(c[1]);
}
int main()
{
int a2b[2], b2c[2], c2a[2], n, x;
pipe(a2b);
pipe(b2c);
pipe(c2a);
srand(time(NULL));
n=rand() % 1001 + 1000;
x=0;
write(c2a[1], &n, sizeof(int));
if (fork() == 0){
while (pass("grandfather ", c2a[0], a2b[1], x) > 0){
x=x+10;}
exit(0);
}
if (fork() == 0){
while (pass("father ", a2b[0], b2c[1], x) > 0){
x=x+10;}
exit(0);
}
if (fork() == 0){
while (pass("child ", b2c[0], c2a[1], x) > 0){
x=x+10;}
exit(0);
}
closeall(a2b, b2c,c2a);
wait(0);
wait(0);
wait(0);
return 0;
}
After running the program the result was
grandfather 1420
x= 0
father 1420
x= 0
child 1420
x= 0
grandfather 1420
x= 10
father 1410
x= 10
child 1400
x= 10
grandfather 1390
x= 20
father 1370
x= 20
child 1350
x= 20
grandfather 1330
x= 30
father 1300
x= 30
child 1270
x= 30
grandfather 1240
x= 40
father 1200
x= 40
child 1160
x= 40
grandfather 1120
x= 50
father 1070
x= 50
child 1020
x= 50
grandfather 970
x= 60
father 910
x= 60
child 850
x= 60
grandfather 790
x= 70
father 720
x= 70
child 650
x= 70
grandfather 580
x= 80
father 500
x= 80
child 420
x= 80
grandfather 340
x= 90
father 250
x= 90
child 160
x= 90
grandfather 70
x= 100
father -30
x= 100
child -130
x= 100
Can someone help me improve the source code in order to obtain the correct result? As seen before, the subtracted value of x is the same for three times, and it doesn't stop after the first negative number.
Aucun commentaire:
Enregistrer un commentaire