Advertisement
Tobiahao

S01_SEMAFORY_06

Dec 17th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.45 KB | None | 0 0
  1. /*
  2. Zademonstruj działanie operacji SEM_UNDO.
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <sys/ipc.h>
  9. #include <sys/types.h>
  10. #include <sys/sem.h>
  11. #include <sys/wait.h>
  12.  
  13. void sem_down(int semid)
  14. {
  15.     struct sembuf down_operation;
  16.  
  17.     down_operation.sem_num = 0;
  18.     down_operation.sem_op = -1;
  19.     down_operation.sem_flg = SEM_UNDO;
  20.  
  21.     if(semop(semid, &down_operation, 1) == -1){
  22.         perror("semop");
  23.         exit(EXIT_FAILURE);
  24.     }
  25. }
  26.  
  27. int main(void)
  28. {
  29.     int semid;
  30.     pid_t pid;
  31.  
  32.     if((semid = semget(IPC_PRIVATE, 1, 0775 | IPC_CREAT | IPC_EXCL)) == -1){
  33.         perror("semget");
  34.         return EXIT_FAILURE;
  35.     }      
  36.  
  37.     if(semctl(semid, 0, SETVAL, 1) == -1){
  38.         perror("semctl");
  39.         return EXIT_FAILURE;
  40.     }
  41.     printf("Wartosc semafora ustawiona na 1\n");
  42.  
  43.     pid = fork();
  44.     if(pid == -1){
  45.         perror("fork");
  46.         return EXIT_FAILURE;
  47.     }
  48.     else if(pid == 0){
  49.         sem_down(semid);
  50.         int buffer;
  51.         if((buffer = semctl(semid, 0, GETVAL)) == -1){
  52.             perror("semctl");
  53.             return EXIT_FAILURE;
  54.         }
  55.         printf("Potomek: wartosc semafora po opuszczeniu semafora: %d\n", buffer);
  56.     }
  57.     else{
  58.         wait(0);
  59.         int buffer;
  60.         if((buffer = semctl(semid, 0, GETVAL)) == -1){
  61.             perror("semctl");
  62.             return EXIT_FAILURE;
  63.         }
  64.         printf("Rodzic: wartosc semafora po wykonaniu kodu potomka: %d\n", buffer);
  65.         printf("Rodzic: Po wykonaniu kodu potomka, automatyczna operacja V - zwiekszenie wartosci semafora, dzieki fladze SEM_UNDO\n");
  66.  
  67.     }
  68.  
  69.     return EXIT_SUCCESS;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement