【问题标题】:I am receiving "shmat: permission denied" when attempting to attach to shared memory. Why?尝试附加到共享内存时,我收到“shmat:权限被拒绝”。为什么?
【发布时间】:2018-02-18 20:00:53
【问题描述】:

我在共享内存方面遇到了一点麻烦,如果有人能指出我正确的方向,我可以提供一些指导。

// 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 正在工作。谁能指出我正确的方向?谢谢。

【问题讨论】:

    标签: c linux shared-memory


    【解决方案1】:

    优先级错误:

    if (shmid = shmget(key, sizeof(int), IPC_CREAT | 0777) < 0)
    

    这会将shmget(key, sizeof(int), IPC_CREAT | 0777) &lt; 0(即0 或1)分配给shmid。你想要的

    if ((shmid = shmget(key, sizeof(int), IPC_CREAT | 0777)) < 0)
    

    【讨论】:

    • 谢谢你,这让我很感动。但我仍然收到同样的错误,虽然输出现在已更改为:内存创建成功:501904483 shmat:权限被拒绝
    • @NathanDarcy 如果你ipcrm 段并重新运行你的程序会发生什么?
    • 我调用命令ipcrm -m [seg_id],下一次调用ipcs显示内存不再列出。当我重新运行程序时,我得到了相同的结果。
    • @NathanDarcy 嗯,这很奇怪。您将不得不发布minimal reproducible example
    • 我很困惑。我将我的确切代码移动到一个新位置,它第一次运行完美。也许我以某种方式搞砸了原始目录的权限?不管怎样,谢谢你的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多