创建共享内存段

时间:2015-03-24 16:30:56

标签: c

我在C中有这个结构:

struct first {
struct list *buf;   
struct pointers *ptr;  
};

创建共享内存段的功能:

void * create_shared_memory(char *name, int size){

int *ptr;
int ret;


int fd = shm_open (name, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);

   if (fd == -1) { 
         perror ("shm_open error!");
     exit (1);
 }

ret = ftruncate (fd, sizeof (size));

   if (ret == -1) {
         perror ("ftruncate error!");
     exit (2);
 }

ptr = mmap(0, sizeof (size), PROT_READ | PROT_WRITE,  MAP_SHARED, fd, 0);

   if (ptr == MAP_FAILED) {
         perror ("shm-mmap error!");
     exit (3);
 }

}

以及为该结构创建共享内存段的函数:

void shared_memory_structure(){

   create_shared_memory("struct", sizeof(struct first));

}

但是我收到错误。我发现问题是结构中的指针没有指向我刚刚创建的共享内存段。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

首先试用这段代码。这是一个取自http://blog.csdn.net/liuzhanchen1987/article/details/7455208的演示代码,该代码位于中文

#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

typedef struct{
    char name[4];
    int age;
}people;

int
main(int argc, char** argv)
{
    int i;
    people *p_map;
    char temp;
    p_map=(people*)mmap(NULL,sizeof(people)*10,PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS,-1,0);
    if(fork() == 0)
    {
        sleep(2);
        for(i = 0;i<5;i++)
            printf("child read: the %d people's age is %d\n",i+1,(*(p_map+i)).age);
        (*p_map).age = 100;
        munmap(p_map,sizeof(people)*10);
        exit();
    }
    temp = 'a';
    for(i = 0;i<5;i++)
    {
        temp += 1;
        memcpy((*(p_map+i)).name, &temp,2);
        (*(p_map+i)).age=20+i;
    }
    sleep(5);
    printf( "parent read: the first people,s age is %d\n",(*p_map).age );
    printf("umap\n");
    munmap( p_map,sizeof(people)*10 );
    printf( "umap ok\n" );
    return 0;
}

预期结果:

child read: the 1 people's age is 20
child read: the 2 people's age is 21
child read: the 3 people's age is 22
child read: the 4 people's age is 23
child read: the 5 people's age is 24
parent read: the first people,s age is 100
umap
umap ok

其中

mmap(NULL,size,PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS,-1,0);

全部在分叉之前你需要做什么(及其返回值检查代码),它的返回值将是分配的页面起始地址(如果它有效)。

如果所有进程都是分叉的。使用mmap分配匿名页面非常方便,此外,在收集进程后没有任何副作用。

如果您使用shm_open,那么在某个地方会有一个共享内存对象被创建,即使在收集完所有进程后,它也会在您的系统中保留副作用。但是,当你计划让两个不相关的过程互相交流时,这是必要的。