-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipc.c
More file actions
91 lines (79 loc) · 2.52 KB
/
ipc.c
File metadata and controls
91 lines (79 loc) · 2.52 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include "ipc.h"
// cooperating proccesses require interprocess communication (IPC) mechanisms that will allow them to exchange data and inform
// A shared memory region resides in the address space of the proccess creating the shared memory segment,other proccesses attach to that address space.
// ===== SEMAPHORE FUNCTIONS =====
// Wait (lock) operation — blocks if semaphore value = 0
void semaphore_wait(int semid) {
struct sembuf op = {0, -1, 0};
// Prepare an operation that will decrement semaphore #0 in this set, and block if it can’t.
// operation: decrement
if (semop(semid, &op, 1) == -1)
// semid,pointer to el 1,no. of operations
{
perror("Semaphore wait failed");
exit(1);
}
}
// Signal (unlock) operation — increments semaphore value
void semaphore_signal(int semid) {
struct sembuf op = {0, 1, 0};
if (semop(semid, &op, 1) == -1) {
perror("Semaphore signal failed");
exit(1);
}
}
// ===== SHARED MEMORY FUNCTIONS =====
// Create shared memory (or get existing one)
int create_shared_memory() {
int shmid = shmget(SHM_KEY, sizeof(struct shared_data), 0666 | IPC_CREAT);
// Create (if needed) or open a shared memory segment with this key, give it read+write permission for everyone.
if (shmid == -1) {
perror("Shared memory creation failed");
exit(1);
}
return shmid;
}
// Attach shared memory to process
struct shared_data* attach_shared_memory(int shmid) {
struct shared_data *data = (struct shared_data*) shmat(shmid, NULL, 0);
if (data == (void*) -1) {
perror("Shared memory attach failed");
exit(1);
}
return data;
}
// Detach shared memory
void detach_shared_memory(struct shared_data *data) {
if (shmdt(data) == -1) {
perror("Shared memory detach failed");
exit(1);
}
}
// Delete shared memory
void destroy_shared_memory(int shmid) {
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("Shared memory destroy failed");
exit(1);
}
}
// Create semaphore
int create_semaphore() {
int semid = semget(SEM_KEY, 1, 0666 | IPC_CREAT);
if (semid == -1) {
perror("Semaphore creation failed");
exit(1);
}
// Initialize to 1 (free)
if (semctl(semid, 0, SETVAL, 1) == -1) {
perror("Semaphore init failed");
exit(1);
}
return semid;
}
// Delete semaphore
void destroy_semaphore(int semid) {
if (semctl(semid, 0, IPC_RMID) == -1) {
perror("Semaphore destroy failed");
exit(1);
}
}