共享内存有多个进程

时间:2014-05-07 18:54:42

标签: c shared-memory

我在共享内存中遇到的问题是: 该项目是定义端口数量,让这些端口相互连接, 我必须通过ubuntu中的一个通信方法(管道,共享内存,消息队列等)来实现这些端口,所以我决定将它们实现为共享内存,其中段数等于端口数。

我的问题是,当我使用相同的密钥和相同的ID使用不同的进程来附加共享内存时,shmat()函数返回指向同一共享内存的不同指针! 所以每个进程都有自己的共享内存! ......为什么会这样?感谢

int ringget(key_t key, int size, ring_t* info)
{
int shm_ID = shmget(key, sizeof(struct info)*size, IPC_CREAT | 0777);
if(shm_ID == -1)
{
    return -1;
}
info->shm_ID = shm_ID;
int msgID = msgget(key+1, IPC_CREAT | 0666);
info->msgID = msgID;
info->shm_size = size;
return 0;
}

int ringat(ring_t* info, int port)
{
if((port-1) >= 0 && (port-1) <= info->shm_ID)
{
    int y;
    int id = info->shm_ID;
    printf("the shared memory ID is [%i]\n", id);
    struct info* i;
    i = (struct info*) shmat(id, NULL, 0);
    i->port = 55;
    printf("the base address is [%p]\n", i);
    struct info * ptr = i;
    for(y = 0; y<info->shm_size; y++)
    {
        (ptr+y)->PID = 0;
        (ptr+y)->port = 0;
    }
    info->ptr = i+port-1;
    (info->ptr)->port = port;
    (info->ptr)->PID = getpid();
        printf("The port is [%i] and the PID is [%i] and the pointer address is [%p]\n",                 (info->ptr)->port, (info->ptr)->PID,(info->ptr));
    printf("DONE\n");
    return 0;
}
else
{
    printf("out of range\n");
    return -1;
}
 }

1 个答案:

答案 0 :(得分:0)

这是完全正常的。在具有受保护内存的现代操作系统上,每个进程都具有独立的虚拟地址空间。期望共享内存段将映射到每个进程中的不同虚拟地址。共享内存段仍由每个进程的相同物理页支持。

相关问题