-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared_memory.cpp
51 lines (43 loc) · 1.06 KB
/
shared_memory.cpp
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024 /* make it a 1K shared memory segment */
key_t key;
int shmid;
char *data;
int mode;
void attach_memory(){
/* make the key: */
if ((key = ftok("/tmp/chess_shared_memory.txt", 'R')) == -1) /*Here the file must exist */
{
perror("ftok");
exit(1);
}
/* create the segment: */
if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
perror("shmget");
exit(1);
}
/* attach to the segment to get a pointer to it: */
data = (char*)shmat(shmid, (void *)0, 0);
if (data == (char *)(-1)) {
perror("shmat");
exit(1);
}
///* read or modify the segment, based on the command line: */
//if (argc == 2) {
// printf("writing to segment: \"%s\"\n", argv[1]);
// strncpy(data, argv[1], SHM_SIZE);
//} else
// printf("segment contains: \"%s\"\n", data);
}
void detach_memory(){
/* detach from the segment: */
if (shmdt(data) == -1) {
perror("shmdt");
exit(1);
}
}