标题: 共享内存的几个问题 [打印本页] 作者: longtem 时间: 2009-05-25 22:54 标题: 共享内存的几个问题 如果共享内存已经存在,则获取到shmid之后,直接挂载就行,不必指定大小。比如:
if ((key = ftok(PROGRAM_KEY_PATH, PROGRAM_ID_A)) == -1)
{
perror("Fail while getting the key");
return -1;
}
if ((shmid = shmget(key, 0, 0)) == -1) /*get the id */
{
perror("Fail while getting the shm id");
return -1;
}
if ((shm = shmat(shmid, NULL, 0)) == (void *) -1) /*attaching the shm */
{
perror("Fail while attaching the shared memory");
return -1;
}
如果一块共享内存里有另外一块共享内存的指针,如果程序不挂载,也不能通过这个指针进行访问。如果:
struct a
{
int x;
int y;
};
struct b
{
int m;
int n;
struct a* ptr;
}
如果存在b的共享内存,并且也存在一块a的内存,并且b的里面ptr设置为b的地址。这个时候如果只挂载b,也不能访问a。这个时候ptr跟一个不同的4字节的变量没什么区别。