-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32b.c
More file actions
68 lines (62 loc) · 1.88 KB
/
32b.c
File metadata and controls
68 lines (62 loc) · 1.88 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
67
68
/*
============================================================================
Name : 32b
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 Semaphore for Shared Memory 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()
// <string.h> → strcpy()
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
sem_t *shared_sem = sem_open("/shared_sem", O_CREAT | O_EXCL, 0666, 1);
if (shared_sem == SEM_FAILED)
{
perror("❌ sem_open failed");
exit(1);
}
pid_t pid = fork();
if (pid == 0)
{
sem_wait(shared_sem);
char buffer[100];
strcpy(buffer, "👶 Child writing to shared memory...");
printf("✅ %s\n", buffer);
sleep(2);
sem_post(shared_sem);
}
else
{
sem_wait(shared_sem);
char buffer[100];
strcpy(buffer, "👨 Parent writing to shared memory...");
printf("✅ %s\n", buffer);
sleep(2);
sem_post(shared_sem);
}
sem_close(shared_sem);
sem_unlink("/shared_sem");
return 0;
}
/*
Output:
╰─ ./32b ─╯
✅ 👨 Parent writing to shared memory...
✅ 👶 Child writing to shared memory...
*/