我对共享内存有点麻烦,如果有人能指出我正确的方向,可以使用一些指导。
// Allocate Shared Memory
key_t key = 56789;
int shmid;
char* shm_address;
int* value;
// Reserve the memory
if (shmid = shmget(key, sizeof(int), IPC_CREAT | 0777) < 0)
{
perror("shmget was unsuccessful");
exit(1);
}
else
{
printf("\nMemory created successfully:%d\n", shmid);
}
// Attach to memory address
if ( (shm_address = shmat(shmid, NULL, 0)) == (char *)-1 )
{
perror("shmat was unsuccessful");
exit(1);
}
else
{
printf ("shared memory attached at address %p\n", shm_address);
}
然后我做了一些流程管理,调用shmdt(shm_address)
,最后用shmctl
进行清理。但我从未达到过代码的那部分。
我得到这个作为输出:
Memory created successfully:0
shmat was unsuccessful: Permission denied
我只是不明白为什么shmat
无法附加?当我在执行后调用ipcs命令时,我的内存已分配,所以我非常确信shmget
正在运行。有人能指出我正确的方向吗?感谢。
答案 0 :(得分:3)
优先顺序错误:
if (shmid = shmget(key, sizeof(int), IPC_CREAT | 0777) < 0)
这会将shmget(key, sizeof(int), IPC_CREAT | 0777) < 0
(即0或1)分配给shmid
。你想要
if ((shmid = shmget(key, sizeof(int), IPC_CREAT | 0777)) < 0)