Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Pokaż w jaki sposób może dojść do zakleszczenia (ang. deadlock) proce- sów synchronizowanych przy pomocy semaforów.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/ipc.h>
- #include <sys/types.h>
- #include <sys/sem.h>
- #include <signal.h>
- int semid;
- void child_sigint_handler(int signum)
- {
- exit(EXIT_SUCCESS);
- }
- void parent_sigint_handler(int signum)
- {
- if(semctl(semid, 0, IPC_RMID) == -1){
- perror("semctl");
- exit(EXIT_FAILURE);
- }
- printf("\nUsuwanie semafora i konczenie procesow\n");
- exit(EXIT_SUCCESS);
- }
- void sem_down()
- {
- struct sembuf down_operation = {0, -1, 0};
- if(semop(semid, &down_operation, 1) == -1){
- perror("down_semop");
- exit(EXIT_FAILURE);
- }
- }
- int main(void)
- {
- pid_t pid;
- if((semid = semget(IPC_PRIVATE, 1, 0775 | IPC_CREAT | IPC_EXCL)) == -1){
- perror("semget");
- return EXIT_FAILURE;
- }
- if(semctl(semid, 0, SETVAL, 0) == -1){
- perror("setval_semop");
- return EXIT_FAILURE;
- }
- printf("Semafor podniesiony!\n");
- pid = fork();
- if(pid == -1){
- perror("fork");
- return EXIT_FAILURE;
- }
- else if(pid == 0){
- if(signal(SIGINT, child_sigint_handler) == SIG_ERR){
- perror("child_signal");
- return EXIT_FAILURE;
- }
- sem_down();
- }
- else{
- if(signal(SIGINT, parent_sigint_handler) == SIG_ERR){
- perror("parent_signal");
- return EXIT_FAILURE;
- }
- sleep(1);
- printf("Semafor opuszczony w dwoch procesach, nastepuje zakleszczenie, nacisnij CTRL + C, aby zakonczyc program!\n");
- sem_down();
- }
- return EXIT_FAILURE;
- }
Add Comment
Please, Sign In to add comment