-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32c.c
More file actions
66 lines (60 loc) · 1.81 KB
/
32c.c
File metadata and controls
66 lines (60 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
============================================================================
Name : 32c
Author : Piyush Singh
Description : Write a program to implement semaphore to protect any critical section.
a. rewrite the ticket number creation program using semaphore
b. protect shared memory from concurrent write access
c. protect multiple pseudo resources ( may be two) using counting semaphore
d. remove the created semaphore
Date: 26th Sep, 2025.
============================================================================
*/
// POSIX Counting Semaphore with fork() (macOS-compatible)
// <stdio.h> → printf(), perror()
// <stdlib.h> → exit()
// <semaphore.h> → sem_open(), sem_wait(), sem_post(), sem_close(), sem_unlink()
// <fcntl.h> → O_CREAT, O_EXCL
// <unistd.h> → fork(), sleep()
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
sem_t *resource_sem = sem_open("/resource_sem", O_CREAT | O_EXCL, 0666, 2);
if (resource_sem == SEM_FAILED)
{
perror("❌ sem_open failed");
exit(1);
}
pid_t pid = fork();
if (pid == 0)
{
sem_wait(resource_sem);
printf("👶 Child acquired resource\n");
sleep(2);
sem_post(resource_sem);
printf("👶 Child released resource\n");
}
else
{
sem_wait(resource_sem);
printf("👨 Parent acquired resource\n");
sleep(2);
sem_post(resource_sem);
printf("👨 Parent released resource\n");
}
sem_close(resource_sem);
sem_unlink("/resource_sem");
return 0;
}
/*
Output:
╰─ ./32c ─╯
👨 Parent acquired resource
👶 Child acquired resource
👨 Parent released resource
👶 Child released resource
*/