Guest User

Untitled

a guest
Jun 23rd, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/ipc.h>
  5. #include <sys/shm.h>
  6. #include <unistd.h>
  7.  
  8. #define SHMKEY ((key_t) 7890)
  9.  
  10. #define MYSEED 1234
  11.  
  12. typedef struct
  13. {
  14. int value;
  15. } shared_mem;
  16.  
  17. shared_mem *counter; //shared variable
  18.  
  19. int read_val(){
  20. return counter->value;
  21. }
  22.  
  23. void write_val(int new_val){
  24.  
  25. counter->value = new_val;
  26. }
  27.  
  28. void sayHello(int id, int max){
  29.  
  30. int i=0;
  31. int temp=0;
  32.  
  33. for(i=0;i<max;i++){
  34.  
  35. temp = read_val();
  36. temp = temp + 1;
  37. write_val(temp);
  38.  
  39. }
  40. if(id == 0)
  41. printf ("\nThe child's count was %d\n",read_val());
  42. else
  43. printf ("\nThe father's count was %d\n",read_val());
  44.  
  45. }
  46.  
  47.  
  48. int main(int argc, char *argv[])
  49. {
  50.  
  51. int shmid; //shared memory Id
  52.  
  53.  
  54. int child1=0;
  55. int max=1000;
  56. int finished,status;
  57. int val;
  58.  
  59. max = atoi(argv[1]); //obtaining the seed from the parameters, and turning it into a numeric value
  60.  
  61. char *shmadd;
  62. shmadd = (char *) 0;
  63.  
  64. if ((shmid = shmget (SHMKEY, sizeof(int), IPC_CREAT | 0666)) < 0)
  65. {
  66. perror ("shmget");
  67. val=1; //exit (1);
  68. }
  69.  
  70. if ((counter = (shared_mem *) shmat (shmid, shmadd, 0)) == (shared_mem *) -1)
  71. {
  72. perror ("shmat");
  73. val=0; //exit (0);
  74. }
  75.  
  76. counter->value = 0;
  77.  
  78. if ((child1 = fork()) == 0){
  79. sayHello(child1,max);
  80. }
  81.  
  82. if (child1 != 0){
  83. sayHello(child1,max);
  84.  
  85. printf ("The child's id is %d \n",child1);
  86.  
  87. finished = wait(&status); //Waiting for a child to finish and for getting its ID
  88.  
  89.  
  90. if(finished == child1){ //is child1?
  91. printf ("The child just finished with counter in %d\n",read_val());
  92. }
  93.  
  94. if ((shmctl (shmid, IPC_RMID, (struct shmid_ds *) 0)) == -1)
  95. {
  96. perror ("shmctl");
  97. val=-1; //exit (-1);
  98. }
  99. printf ("\t\t End of simulation.\n");
  100.  
  101. }
  102.  
  103. return val;
  104. }
Add Comment
Please, Sign In to add comment