Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //For a given N value (5<N<=15) create N processes.
- //The main process creates a new subprocess. This subprocess will create another subprocess,
- //and so on until N processes are created.
- //Each process will discuss with his child using a pipe channel.
- //The main process (the initial one) will generate a random number between 1000 and 10000 and will start the game.
- //The game will start after all the processes are created.
- //Each process will subtract a random value (between 10 and 20) and sends the new number to his child.
- //The child will perform the same operation and send the number further.
- //The game ends when the number reaches the last child. This process will only print the received number.
- #include<unistd.h>
- #include<stdio.h>
- #include<stdlib.h>
- #include<time.h>
- #include<errno.h>
- #include<sys/types.h>
- #include<sys/wait.h>
- int main(){
- int pp[15][2], N, rNumber, a, f, k, j;
- k = 0;
- printf("n=");
- srand(time(0)); //random generator
- scanf("%d", &N);
- pipe(pp[k]); //
- rNumber = rand() % 9000 + 1000;
- write(pp[k][1], &rNumber, sizeof(int));
- printf("The generated number is: %d\n", rNumber);
- f = fork();
- int i;
- for (i=0; i<N; i++){
- if( f < 0 ) {
- perror("fork error");
- exit(1);
- }
- if( f == 0 ) { //we are in the "child" process
- if( i != N-1 ){ //I checked if I didn't reach the last process
- read(pp[k][0], &rNumber, sizeof(int));
- k++;
- pipe(pp[k]);
- srand(time(0));
- a = rand() % 10 + 10;
- printf("I'm an intermediate process and I decrease with the value: %d\n", a);
- rNumber = rNumber - a;
- write(pp[k][1], &rNumber, sizeof(int));
- sleep(1);
- f = fork();
- if (f != 0){
- wait(0);
- exit(0);
- }
- }
- else{ //last process
- read(pp[k][0], &rNumber, sizeof(int));
- printf("I'm the last process and the final result is: %d\n", rNumber);
- for (j=0; j<k; j++){
- close(pp[k][0]);
- close(pp[k][1]);
- wait(0);
- exit(0);
- }
- }
- }
- }
- wait(0);
- exit(0);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement