comm.h
1 #pragma once
2
3 #include <sys/ipc.h>
4 #include <sys/shm.h>
5 #include <sys/types.h>
6
7 #define _PATH_NAME_ "/tmp"
8 #define _PROJ_ID_ 0x666
9
10 int create_shm(int size);
11 int get_shm();
12 int destroy_shm(int shm_id);
13 void* at(int shm_id);
14 int dt(void *addr);
comm.c
#include "comm.h"
2 #include <stdio.h>
3
4 static int comm_shm(int size, int flag)
5 {
6 key_t key = ftok(_PATH_NAME_, _PROJ_ID_);
7 if (key < 0)
8 {
9 perror("ftok");
10 return -2;
11 }
12
13 return shmget(key, size, flag);
14 }
15
16 int create_shm(int size)
17 {
18 int flag = IPC_CREAT | IPC_EXCL | 0644;
19 return comm_shm(size, flag);
20 }
21
22
23 int get_shm()
24 {
25 int flag = IPC_CREAT;
26 return comm_shm(0, flag);
27 }
28
29 int destroy_shm(int shm_id)
30 {
31 return shmctl(shm_id, IPC_RMID, NULL);
32 }
33
34 void* at(int shm_id)
35 {
36 return shmat(shm_id, NULL, 0);
37 }
int dt(void* addr)
40 {
41 return shmdt(addr);
42 }
server.c 往共享内存中写数据
1 #include <stdio.h>
2 #include <unistd.h>
3 #include "comm.h"
4
5
6 int main()
7 {
8 int shm_id = create_shm(4096);
9 char *addr = (char *)at(shm_id);
10
11 int i = 0;
12 while (1)
13 {
14 addr[i] = 'A';
15 addr[i + 1] = 0;
16
17 ++i;
18 i %= 4096;
19 sleep(1);
20 }
21
22 dt(addr);
23 destroy_shm(shm_id);
24
25 return 0;
26 }
client.c 从共享内存里面读数据
#include <stdio.h>
2 #include <unistd.h>
3 #include "comm.h"
4
5
6 int main()
7 {
8 int shm_id = get_shm();
9 char *addr = (char *)at(shm_id);
10
11 int i = 0;
12 while (1)
13 {
14 printf("%s\n", addr);
15 sleep(1);
16 }
17
18 dt(addr);
19
20 return 0;
21 }