Advertisement
Guest User

Untitled

a guest
Jan 20th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. #include <stdio.h> /* printf() */
  2. #include <stdlib.h> /* exit(), malloc(), free() */
  3. #include <sys/types.h> /* key_t, sem_t, pid_t */
  4. #include <sys/shm.h> /* shmat(), IPC_RMID */
  5. #include <errno.h> /* errno, ECHILD */
  6. #include <semaphore.h> /* sem_open(), sem_destroy(), sem_wait().. */
  7. #include <fcntl.h> /* O_CREAT, O_EXEC */
  8. #include <unistd.h>
  9. #include <sys/wait.h>
  10. #include <sys/shm.h>
  11.  
  12.  
  13. typedef sem_t Semaphore;
  14.  
  15.  
  16. /* semaphores are usually declared global variables */
  17. /* synch semaphore */
  18. Semaphore *LP1;
  19. Semaphore *LP2;
  20.  
  21. int main ()
  22. {
  23. int i; /* loop variables */
  24. pid_t pid; /* fork pid */
  25. int child_status;
  26.  
  27. /* Declaring Shared memory variables */
  28. key_t shmkey;
  29. int shmid;
  30. int *x;
  31.  
  32. /* Initializing a shared variable in shared memory */
  33. shmkey = ftok ("/dev/null", 5);
  34. shmid = shmget(shmkey, sizeof (int), 0644 | IPC_CREAT);
  35.  
  36. /* initialize semaphores for shared processes */
  37. LP1 = sem_open ("LefterisP1", O_CREAT | O_EXCL, 0644, 0/*Initial value */);
  38. LP2 = sem_open ("LefterisP2", O_CREAT | O_EXCL, 0644, 0/*Initial value */);
  39.  
  40. /* fork child processes */
  41. for (i=0; i<1; i++)
  42. {
  43. pid = fork ();
  44.  
  45. if (pid == 0)
  46. {
  47. break;
  48. }
  49. }
  50.  
  51. /* 1st child */
  52. if (pid == 0)
  53. {
  54.  
  55. sem_wait(LP2);
  56. printf("I timi tou x prin tin diergasia 1: %d\n", *x);
  57. *x = *x * 2;
  58. printf("I timi tou x meta tin diergasia 1: %d\n", *x);
  59. wait(NULL);
  60.  
  61. }
  62. /* 2nd child */
  63. else if (pid != 0 && pid == 0)
  64. {
  65.  
  66. printf("I timi tou x prin tin diergasia 2: %d\n", *x);
  67. *x = *x * (*x);
  68. printf("I timi tou x meta tin diergasia 2:%d\n", *x);
  69. sem_post(LP1);
  70. wait(NULL);
  71.  
  72. }
  73. else
  74. {
  75. sem_wait(LP1);
  76. printf("I timi prin tin diergasia 3:%d\n", *x);
  77. *x = *x + 3;
  78. printf("I timi meta tin diergasia 3:%d\n", *x);
  79. sem_post(LP2);
  80.  
  81.  
  82. printf(" Parent unlinks the semaphores\n Bye\n");
  83.  
  84. /* unlink prevents the semaphore existing forever */
  85. /* if a crash occurs during the execution */
  86. sem_unlink ("LefterisP1");
  87. sem_close(LP1);
  88. sem_unlink ("LefterisP2");
  89. sem_close(LP2);
  90. }
  91. exit (0);
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement