Advertisement
Guest User

Untitled

a guest
Apr 30th, 2016
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. //For a given N value (5<N<=15) create N processes.
  2. //The main process creates a new subprocess. This subprocess will create another subprocess,
  3. //and so on until N processes are created.
  4. //Each process will discuss with his child using a pipe channel.
  5. //The main process (the initial one) will generate a random number between 1000 and 10000 and will start the game.
  6. //The game will start after all the processes are created.
  7. //Each process will subtract a random value (between 10 and 20) and sends the new number to his child.
  8. //The child will perform the same operation and send the number further.
  9. //The game ends when the number reaches the last child. This process will only print the received number.
  10.  
  11. #include<unistd.h>
  12. #include<stdio.h>
  13. #include<stdlib.h>
  14. #include<time.h>
  15. #include<errno.h>
  16. #include<sys/types.h>
  17. #include<sys/wait.h>
  18.  
  19. int main(){
  20.  
  21. int pp[15][2], N, rNumber, a, f, k, j;
  22. k = 0;
  23.  
  24. printf("n=");
  25. srand(time(0)); //random generator
  26. scanf("%d", &N);
  27.  
  28. pipe(pp[k]); //
  29.  
  30. rNumber = rand() % 9000 + 1000;
  31. write(pp[k][1], &rNumber, sizeof(int));
  32. printf("The generated number is: %d\n", rNumber);
  33. f = fork();
  34. int i;
  35. for (i=0; i<N; i++){
  36. if( f < 0 ) {
  37. perror("fork error");
  38. exit(1);
  39. }
  40. if( f == 0 ) { //we are in the "child" process
  41. if( i != N-1 ){ //I checked if I didn't reach the last process
  42. read(pp[k][0], &rNumber, sizeof(int));
  43. k++;
  44. pipe(pp[k]);
  45. srand(time(0));
  46. a = rand() % 10 + 10;
  47. printf("I'm an intermediate process and I decrease with the value: %d\n", a);
  48. rNumber = rNumber - a;
  49. write(pp[k][1], &rNumber, sizeof(int));
  50. sleep(1);
  51. f = fork();
  52. if (f != 0){
  53. wait(0);
  54. exit(0);
  55. }
  56. }
  57. else{ //last process
  58. read(pp[k][0], &rNumber, sizeof(int));
  59. printf("I'm the last process and the final result is: %d\n", rNumber);
  60. for (j=0; j<k; j++){
  61. close(pp[k][0]);
  62. close(pp[k][1]);
  63. wait(0);
  64. exit(0);
  65. }
  66. }
  67. }
  68.  
  69. }
  70. wait(0);
  71. exit(0);
  72. return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement