cornsea

使用shm_open来操作共享内存

shm_open最主要的操作也是默认的操作就是在/dev/shm/下面,建立一个文件。

文件名字是用户自己输入的。

 

要点一定要用ftruncate把文件大小于设置为共享内存大小。

服务端:

#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;
}

客户端:

#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;
}
~                                                                                                                                                                           
~                                         

posted on 2010-05-13 22:51  cornsea  阅读(21032)  评论(0编辑  收藏  举报

导航