Tobiahao

S01_SEMAFORY_03

Dec 17th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.89 KB | None | 0 0
  1. /*
  2. Zmodyfikuj zadanie drugie tak, aby tworzony był jeden semafor o war- tości początkowej zero, a procesy potomne zwiększały go ojeden, w określonym porządku. Proces pierwszy bezwarunkowo zwiększy wartość semafora, proces drugi będzie czekał aż semafor będzie miał wartość dwa i zwiększy ją do trzech, itd. Wartość końcowa semafora powinna wynosić pięć.
  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_up(int semid)
  14. {
  15.     struct sembuf up_operation = {0, 1, 0};
  16.     if(semop(semid, &up_operation, 1) == -1){
  17.         perror("semop");
  18.         exit(EXIT_FAILURE);
  19.     }
  20. }
  21.  
  22. int main(void)
  23. {
  24.     int semid;
  25.     pid_t pid; 
  26.    
  27.     if((semid = semget(IPC_PRIVATE, 1, 0775|IPC_CREAT|IPC_EXCL)) == -1){
  28.         perror("semget");
  29.         return EXIT_FAILURE;
  30.     }
  31.  
  32.     if(semctl(semid, 0, SETVAL, 0) == -1){
  33.         perror("setval_semctl");
  34.         return EXIT_FAILURE;
  35.     }
  36.  
  37.     printf("Stworzono semafor o wartosci poczatkowej 0\n");
  38.  
  39.     for(int i = 0; i < 5; i++){
  40.         pid = fork();
  41.         if(pid == -1){
  42.             perror("fork");
  43.             return EXIT_FAILURE;
  44.         }
  45.         else if(pid == 0){
  46.             usleep(100000);
  47.             sem_up(semid);
  48.             int sem_value_buffer;
  49.             if((sem_value_buffer = semctl(semid, 0, GETVAL)) == -1){
  50.                 perror("child_getval_semctl");
  51.                 return EXIT_FAILURE;
  52.             }
  53.             printf("Proces nr %d: Zwiekszona wartosc: %d\n", i+1, sem_value_buffer);
  54.         }
  55.         else{
  56.             wait(0);
  57.             int sem_value_buffer;
  58.             if(i == 4){
  59.                 if((sem_value_buffer = semctl(semid, 0, GETVAL)) == -1){
  60.                     perror("parent_getval_semctl");
  61.                     return EXIT_FAILURE;
  62.                 }
  63.                 if(sem_value_buffer == 5){
  64.                     if(semctl(semid, 0, IPC_RMID) == -1){
  65.                         perror("rmid_semctl");
  66.                         return EXIT_FAILURE;
  67.                     }
  68.                     printf("Rodzic: Wartosc semafora rowna 5, usuwanie semafora...\n");
  69.                 }
  70.             }
  71.             return EXIT_SUCCESS;
  72.         }
  73.     }
  74.  
  75.     return EXIT_SUCCESS;
  76. }
Add Comment
Please, Sign In to add comment