Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/ipc.h>
- #include <sys/sem.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <sys/wait.h>
- /* Required for semctl */
- union semun
- {
- int val;
- struct semid_ds *buf;
- unsigned short *array;
- };
- void semaphore_wait(int semid)
- {
- struct sembuf sb = {0, -1, 0}; // P operation
- semop(semid, &sb, 1);
- }
- void semaphore_signal(int semid)
- {
- struct sembuf sb = {0, +1, 0}; // V operation
- semop(semid, &sb, 1);
- }
- int main()
- {
- key_t key = ftok(".", 65);
- int semid = semget(key, 1, 0666 | IPC_CREAT);
- union semun sem_union;
- sem_union.val = 1; // Initialize semaphore to 1
- semctl(semid, 0, SETVAL, sem_union);
- pid_t pid = fork();
- if (pid == 0)
- {
- /* Child process */
- sleep(1);
- printf("Child: waiting for semaphore...\n");
- semaphore_wait(semid);
- printf("Child: entered critical section\n");
- semaphore_signal(semid);
- printf("Child: leaving critical section\n");
- exit(0);
- }
- else if (pid > 0)
- {
- /* Parent process */
- printf("Parent: entering critical section\n");
- semaphore_wait(semid);
- sleep(3);
- printf("Parent: leaving critical section\n");
- semaphore_signal(semid);
- wait(NULL);
- /* Remove semaphore */
- semctl(semid, 0, IPC_RMID);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment