Tobiahao

S01_SEMAFORY_01a

Dec 17th, 2017
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.29 KB | None | 0 0
  1. /*
  2. Napisz dwa programy. Pierwszy stworzy semafor i zainicjuje go war- tością dodatnią, a następnie poczeka, aż drugi program ustawi wartość tego semafor na zero i dopiero wtedy zakończy się.
  3. */
  4.  
  5. // Program pierwszy
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <sys/ipc.h>
  10. #include <sys/types.h>
  11. #include <sys/sem.h>
  12. #include <unistd.h>
  13.  
  14. #define FTOK_PATH "/tmp"
  15. #define FTOK_ID 712
  16. #define ERROR_MESSAGE_SIZE 20
  17.  
  18. void sem_up_and_wait(int semset_id)
  19. {
  20.     struct sembuf up_operation = {0, 1, 0};
  21.     struct sembuf wait_operation = {0, 0, 0};
  22.  
  23.     printf("Program 1: Semafor ustawiony, czekanie na wyzerowanie...\n");
  24.  
  25.     if(semop(semset_id, &up_operation, 1) == -1){
  26.         perror("up_semop");
  27.         exit(EXIT_FAILURE);
  28.     }
  29.    
  30.     if(semop(semset_id, &wait_operation, 1) == -1){
  31.         perror("wait_semop");
  32.         exit(EXIT_FAILURE);
  33.     }
  34.     printf("Program 1: Semafor zostal wyzerowany!\n");
  35. }
  36.  
  37. int main(void)
  38. {
  39.     key_t key;
  40.     int semset_id;
  41.    
  42.     if((key = ftok(FTOK_PATH, FTOK_ID)) == -1){
  43.         perror("ftok");
  44.         return EXIT_FAILURE;
  45.     }
  46.  
  47.     if((semset_id = semget(key, 1, 0775|IPC_CREAT|IPC_EXCL)) == -1){
  48.         perror("semget");
  49.         return EXIT_FAILURE;
  50.     }
  51.  
  52.     sem_up_and_wait(semset_id);
  53.  
  54.     if(semctl(semset_id, 0, IPC_RMID) == -1){
  55.         perror("semctl");
  56.         return EXIT_FAILURE;
  57.     }
  58.  
  59.     return EXIT_SUCCESS;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment