Tobiahao

S01_SEMAFORY_02

Dec 17th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.67 KB | None | 0 0
  1. /*
  2. Napisz program, który stworzy zbiór dziesięciu semaforów, o wartości początkowej równej jeden, a następnie stworzy dziesięć procesów potom- nych, które wstępnie zostaną uśpione na sekundę, a następnie ustawią wartość odpowiadającego im semafora na zero. Proces rodzicielski może się zakończyć dopiero wtedy, kiedy ostatni semafor ze zbioru osiągnie wartość zero.
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <sys/ipc.h>
  8. #include <sys/types.h>
  9. #include <sys/sem.h>
  10. #include <sys/wait.h>
  11. #include <unistd.h>
  12.  
  13. #define NUMBER 10
  14.  
  15. void down_operation(int semid, u_short sem_num)
  16. {
  17.     struct sembuf down_operation = {sem_num, -1, 0};
  18.  
  19.     if(semop(semid, &down_operation, 1) == -1){
  20.         perror("semop");
  21.         exit(EXIT_FAILURE);
  22.     }
  23.     printf("Wartosc semafora nr %d zostala ustawiona na 0\n", (int)sem_num);
  24. }
  25.  
  26. int main()
  27. {
  28.     pid_t pids[NUMBER];
  29.     int semid;
  30.  
  31.     if((semid = semget(IPC_PRIVATE, NUMBER, 0775|IPC_CREAT|IPC_EXCL)) == -1){
  32.         perror("semget");
  33.         return EXIT_FAILURE;
  34.     }
  35.  
  36.     for(int i = 0; i < NUMBER; i++){
  37.         if(semctl(semid, i, SETVAL, 1) == -1){
  38.             perror("semctl");
  39.             exit(EXIT_FAILURE);
  40.         }
  41.     }
  42.  
  43.     for(int i = 0; i < NUMBER; i++){
  44.         pids[i] = fork();
  45.         if(pids[i] == -1){
  46.             perror("fork");
  47.             return EXIT_FAILURE;
  48.         }
  49.         else if(pids[i] == 0){
  50.             printf("Potomek nr %d: czekam 1s...\n", i);
  51.             sleep(1);
  52.             down_operation(semid, i);
  53.         }
  54.         else{
  55.             wait(0);
  56.             if(i == NUMBER-1){
  57.                 if(semctl(semid, 0, IPC_RMID) == -1){
  58.                     perror("semctl");
  59.                     return EXIT_FAILURE;
  60.                 }
  61.                 printf("Wartosc ostatniego semafora rowna 0, konczenie programu\n");
  62.             }  
  63.             return EXIT_SUCCESS;
  64.         }
  65.     }
  66.    
  67.     return EXIT_SUCCESS;
  68. }
Add Comment
Please, Sign In to add comment