Advertisement
Guest User

Untitled

a guest
Nov 14th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/sem.h>
  5. #include <sys/shm.h>
  6. #include <string.h>
  7. #include <unistd.h>
  8. #include <wait.h>
  9. #include <sys/ipc.h>
  10.  
  11. void up_and_wait(int mux)
  12. {
  13. struct sembuf up = {0, 1, 0};
  14. struct sembuf wait = {0, 0, 0};
  15.  
  16. if(semop(mux, &up, 1) < 0)
  17. perror("semop up");
  18. if(semop(mux, &wait, 1) < 0)
  19. perror("semop wait");
  20. }
  21.  
  22. void down (int mux)
  23. {
  24. struct sembuf down = {0, -1, 0};
  25.  
  26. if(semop(mux, &down, 1) < 0)
  27. perror("semop down");
  28. }
  29.  
  30. void writer(int mux, int shmid)
  31. {
  32. char *str = shmat(shmid, NULL, 0);
  33. if(str == (void*)-1)
  34. perror("writer shmat");
  35.  
  36. down(mux);
  37. strncpy(str, "Systemy Operacyjne 1", 50);
  38.  
  39. if(shmdt(str) < 0)
  40. perror("writer strdt");
  41. exit(0);
  42. }
  43.  
  44. void reader(int mux, int shmid)
  45. {
  46. char *str = shmat(shmid, NULL, 0);
  47. if(str == (void*)-1)
  48. perror("reader shmat");
  49.  
  50. up_and_wait(mux);
  51. printf("Odczytana wiadomosc: %s\n", str);
  52.  
  53. if(shmdt(str) < 0)
  54. perror("reader strdt");
  55. if(wait(NULL) < 0)
  56. perror("wait");
  57. }
  58.  
  59. int main(void)
  60. {
  61. int mux = semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT | IPC_EXCL);
  62. if(mux < 0)
  63. perror("semget");
  64.  
  65. int shmid = shmget(IPC_PRIVATE, 4096, 0600 | IPC_CREAT | IPC_EXCL);
  66. if(shmid < 0)
  67. perror("shmget");
  68.  
  69. int pid = fork();
  70.  
  71. if(pid < 0)
  72. perror("fork");
  73. if(pid == 0)
  74. writer(mux, shmid);
  75. else
  76. reader(mux, shmid);
  77.  
  78. if(shmctl(shmid, IPC_RMID, NULL) < 0)
  79. perror("shmctl");
  80. if(semctl(mux, 0, IPC_RMID, NULL) < 0)
  81. perror("semctl");
  82.  
  83. return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement