ivorakitin

IPC SystemV Semaphores

Dec 17th, 2025 (edited)
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/ipc.h>
  4. #include <sys/sem.h>
  5. #include <sys/types.h>
  6. #include <unistd.h>
  7. #include <sys/wait.h>
  8.  
  9. /* Required for semctl */
  10. union semun
  11. {
  12.     int val;
  13.     struct semid_ds *buf;
  14.     unsigned short *array;
  15. };
  16.  
  17. void semaphore_wait(int semid)
  18. {
  19.     struct sembuf sb = {0, -1, 0}; // P operation
  20.     semop(semid, &sb, 1);
  21. }
  22.  
  23. void semaphore_signal(int semid)
  24. {
  25.     struct sembuf sb = {0, +1, 0}; // V operation
  26.     semop(semid, &sb, 1);
  27. }
  28.  
  29. int main()
  30. {
  31.     key_t key = ftok(".", 65);
  32.     int semid = semget(key, 1, 0666 | IPC_CREAT);
  33.  
  34.     union semun sem_union;
  35.     sem_union.val = 1;             // Initialize semaphore to 1
  36.     semctl(semid, 0, SETVAL, sem_union);
  37.     pid_t pid = fork();
  38.     if (pid == 0)
  39.     {
  40.         /* Child process */
  41.         sleep(1);
  42.         printf("Child: waiting for semaphore...\n");
  43.         semaphore_wait(semid);
  44.         printf("Child: entered critical section\n");
  45.         semaphore_signal(semid);
  46.         printf("Child: leaving critical section\n");
  47.         exit(0);
  48.     }
  49.     else if (pid > 0)
  50.     {
  51.         /* Parent process */
  52.         printf("Parent: entering critical section\n");
  53.         semaphore_wait(semid);
  54.         sleep(3);
  55.         printf("Parent: leaving critical section\n");
  56.         semaphore_signal(semid);
  57.         wait(NULL);
  58.  
  59.         /* Remove semaphore */
  60.         semctl(semid, 0, IPC_RMID);
  61.     }
  62.  
  63.     return 0;
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment