Guest User

Untitled

a guest
Jan 13th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5.  
  6. #define NPROCS 7 /*Number of processes to be created*/
  7. #define MSGLEN 9 /*Length of messages sent to each process*/
  8.  
  9. int main(){
  10.  
  11. int fd[NPROCS][2], i, myID = 0, parent, rng, j, num;
  12. char msg[MSGLEN];
  13.  
  14.  
  15. for(i = 0; i < NPROCS; i++){ /*Create pipes*/
  16. if(pipe(fd[i]) == -1){
  17. perror("Piping error");
  18. exit(-1);
  19. }
  20. }
  21.  
  22. for(i = 1; i < NPROCS; i++){ /*Create processes*/
  23. switch(parent = fork()){
  24. case -1:
  25. perror("Forking error");
  26. exit(-1);
  27. case 0:
  28. myID = i;
  29.  
  30. }
  31. if(parent){
  32. break;
  33. }
  34. }
  35.  
  36. /*COMMON CODE*/
  37.  
  38. close(fd[myID][1]); /*Close current process's write end to pipe*/
  39.  
  40.  
  41. for(i = 0; i < NPROCS; i++){ /*Close all read ends from other processes*/
  42. if(i != myID){
  43. close(fd[i][0]);
  44. }
  45. }
  46.  
  47. sprintf(msg, "process%d", myID);
  48.  
  49. int count = 0;
  50.  
  51. srand(71913173*myID);
  52. rng = RAND_MAX/NPROCS; /*Generate random numbers, write to 13 random processes*/
  53. rng *= NPROCS;
  54. for(i = 0; i < 13; i++){
  55. do{
  56. num = rand();
  57. j = num % NPROCS;
  58. } while(num >= rng || myID==j);
  59. count++;
  60. printf("myID: %d, j: %d, count: %d\n", myID, j, count);
  61. if(write(fd[j][1], msg, MSGLEN) != MSGLEN){
  62. perror("Write error");
  63. exit(-1);
  64. }
  65. }
  66.  
  67. for(i = 0; i < NPROCS; i++){ /*Close all write ends*/
  68. if(i != myID){
  69. close(fd[i][1]);
  70. }
  71. }
  72.  
  73. msg[MSGLEN] = '\0';
  74. while(read(fd[myID][0], msg, MSGLEN) == MSGLEN){
  75. printf("process%d has received a message from %s\n", myID, msg);
  76. }
  77.  
  78.  
  79.  
  80.  
  81.  
  82. close(fd[myID][0]);
  83. exit(0);
  84. }
Add Comment
Please, Sign In to add comment