Tobiahao

S01_SEMAFORY_05

Dec 17th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | None | 0 0
  1. /*
  2. Pokaż w jaki sposób może dojść do zakleszczenia (ang. deadlock) proce- sów synchronizowanych przy pomocy semaforów.
  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 <signal.h>
  12.  
  13. int semid;
  14.  
  15. void child_sigint_handler(int signum)
  16. {
  17.     exit(EXIT_SUCCESS);
  18. }
  19.  
  20. void parent_sigint_handler(int signum)
  21. {
  22.     if(semctl(semid, 0, IPC_RMID) == -1){
  23.         perror("semctl");
  24.         exit(EXIT_FAILURE);
  25.     }
  26.     printf("\nUsuwanie semafora i konczenie procesow\n");
  27.     exit(EXIT_SUCCESS);
  28. }
  29.  
  30. void sem_down()
  31. {
  32.     struct sembuf down_operation = {0, -1, 0};
  33.  
  34.     if(semop(semid, &down_operation, 1) == -1){
  35.         perror("down_semop");
  36.         exit(EXIT_FAILURE);
  37.     }
  38. }
  39.  
  40. int main(void)
  41. {
  42.     pid_t pid;
  43.  
  44.     if((semid = semget(IPC_PRIVATE, 1, 0775 | IPC_CREAT | IPC_EXCL)) == -1){
  45.         perror("semget");
  46.         return EXIT_FAILURE;
  47.     }
  48.  
  49.     if(semctl(semid, 0, SETVAL, 0) == -1){
  50.         perror("setval_semop");
  51.         return EXIT_FAILURE;
  52.     }
  53.     printf("Semafor podniesiony!\n");
  54.  
  55.     pid = fork();
  56.     if(pid == -1){
  57.         perror("fork");
  58.         return EXIT_FAILURE;
  59.     }
  60.     else if(pid == 0){
  61.         if(signal(SIGINT, child_sigint_handler) == SIG_ERR){
  62.             perror("child_signal");
  63.             return EXIT_FAILURE;
  64.         }
  65.         sem_down();
  66.     }
  67.     else{
  68.         if(signal(SIGINT, parent_sigint_handler) == SIG_ERR){
  69.             perror("parent_signal");
  70.             return EXIT_FAILURE;
  71.         }
  72.  
  73.         sleep(1);
  74.         printf("Semafor opuszczony w dwoch procesach, nastepuje zakleszczenie, nacisnij CTRL + C, aby zakonczyc program!\n");
  75.         sem_down();
  76.     }
  77.  
  78.     return EXIT_FAILURE;
  79. }
Add Comment
Please, Sign In to add comment