Tobiahao

S01_PAMIEC_DZIELONA_04b

Dec 19th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. /*
  2. Napisz dwa programy, które b ę d ą komunikować się poprzez pamięć dzielon ą .
  3. W trakcie dzia ł ania programów (np. po dwóch wys ł anych i odebranych komunikatach) niech program b ę d ą cy w ł a ś cicielem pami ę ci zamieni jej prawa dost ę pu, tak, aby tylko on móg ł z niej korzysta ć . Poka ż co si ę wtedy stanie.
  4.    */
  5.  
  6. // Program drugi
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <sys/ipc.h>
  11. #include <sys/types.h>
  12. #include <sys/sem.h>
  13. #include <sys/shm.h>
  14. #include <unistd.h>
  15.  
  16. #define FTOK_PATH "/tmp"
  17. #define FTOK_ID 0x712
  18.  
  19. void error_handler(const char *msg)
  20. {
  21.     perror(msg);
  22.     exit(EXIT_FAILURE);
  23. }
  24.  
  25. void mux_up(int mux)
  26. {
  27.     struct sembuf up_operation = {0, 1, 0};
  28.     if(semop(mux, &up_operation, 1) == -1)
  29.         error_handler("semop_up");
  30. }
  31.  
  32. void mux_down(int mux)
  33. {
  34.     struct sembuf down_operation = {0, -1, 0};
  35.     if(semop(mux, &down_operation, 1) == -1)
  36.         error_handler("semop_down");
  37. }
  38.  
  39. int main(void)
  40. {
  41.     int shmid, mux;
  42.     int *shared_memory;
  43.     key_t key;
  44.     int buffer;
  45.  
  46.     if((key = ftok(FTOK_PATH, FTOK_ID)) == -1)
  47.         error_handler("ftok");
  48.  
  49.     if((mux = semget(key, 1, 0660 | IPC_CREAT)) == -1)
  50.         error_handler("semget");
  51.  
  52.     if((shmid = shmget(key, SHMLBA, 0660 | IPC_CREAT)) == -1)
  53.         error_handler("semctl");
  54.  
  55.     for(int i = 0; i <= 5; i++){   
  56.         mux_down(mux);
  57.         if((shared_memory = (int *)shmat(shmid, NULL, 0)) == (void *)-1)
  58.             error_handler("shmat");
  59.         buffer = shared_memory[i];
  60.         printf("Odczytano z pamieci dzielonej liczbe: %d\n", buffer);
  61.     }
  62.  
  63.     if(shmdt(shared_memory) == -1)
  64.         error_handler("shmdt");
  65.     if(shmctl(shmid, IPC_RMID, NULL) == -1)
  66.         error_handler("shmctl");
  67.  
  68.     if(semctl(mux, 0, IPC_RMID, NULL) == -1)
  69.         error_handler("semctl");
  70.  
  71.  
  72.     return EXIT_SUCCESS;
  73. }
Add Comment
Please, Sign In to add comment