This repository has been archived by the owner on Jun 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.c
55 lines (45 loc) · 1.45 KB
/
server.c
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
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#define SHM_KEY 716023
#define SHM_FILE "/tmp/i_love_aries"
int main() {
int id;
/************************* TODO 1 *************************/
// Create a shared memory section
int shmid = shmget(SHM_KEY, sizeof(int), 0666 | IPC_CREAT | IPC_EXCL);
if (shmid < 0) {
perror("Failed to create shared memory");
exit(-1);
}
/************************* TODO 1 *************************/
/************************* TODO 2 *************************/
// Attach the memory section
// the return value is a pointer to the shared memory section
int *ptr = (int *)shmat(shmid, (void *)0, 0);
/************************* TODO 2 *************************/
ptr[0] = 0;
printf("\033[1;32m[server] The value is %d\033[0m\n", ptr[0]);
while (1) {
int cmd;
printf("\n");
printf("1: Show the value\n");
printf("2: Modify the value\n");
printf("3: Exit\n");
printf("Enter commands: ");
scanf("%d", &cmd);
if (cmd == 1)
printf("\033[1;32m[server] The value is %d\033[0m\n", ptr[0]);
else if (cmd == 2) {
printf("Input new value: ");
scanf("%d", &ptr[0]);
} else
break;
}
// detach from shared memory
shmdt(ptr);
// destroy the shared memory
shmctl(shmid, IPC_RMID, NULL);
}