我在尝试附加到共享内存时收到 "shmat: permission denied"。为什么?
I am receiving "shmat: permission denied" when attempting to attach to shared memory. Why?
我在共享内存方面遇到了一些麻烦,如果有人能为我指明正确的方向,我可以使用一些指导。
// 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
正在工作。谁能指出我正确的方向?谢谢。
优先顺序错误:
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)
我在共享内存方面遇到了一些麻烦,如果有人能为我指明正确的方向,我可以使用一些指导。
// 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
正在工作。谁能指出我正确的方向?谢谢。
优先顺序错误:
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)