shm_open函数实例及说明

来源:互联网 发布:2017网络直播平台排名 编辑:程序博客网 时间:2024/05/21 18:11
使用shm_open来操作共享内存
shm_open最主要的操作也是默认的操作就是在/dev/shm/下面,建立一个文件。
文件名字是用户自己输入的。
要点一定要用ftruncate把文件大小于设置为共享内存大小。

服务端:

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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
char buf[10];
char *ptr;
int main()
{
int fd;
fd = shm_open("region", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd<0) {
printf("error open region\n");
return 0;
}
ftruncate(fd, 10);
ptr = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) {
printf("error map\n");
return 0;
}
*ptr = 0x12;
return 0;
}

客户端:

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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
char buf[10];
char *ptr;
int main()
{
int fd;
fd = shm_open("region", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd<0) {
printf("error open region\n");
return 0;
}
ftruncate(fd, 10);
ptr = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) {
printf("error map\n");
return 0;
}
while (*ptr != 0x12);
printf("ptr : %d\n", *ptr);
return 0;
}
原创粉丝点击