gpt4 book ai didi

c - shmat 返回 errno=13(EACCES) 的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 07:24:24 25 4
gpt4 key购买 nike

我只想测试 shmget() 和 shmat() ,但似乎有问题。 :(

shmget() 运行良好,但 shmat() 导致段错误。

这是代码:

#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <errno.h>

int main(void)
{
key_t key=98;/* yes, just 98 for test */
int shid;
char *str=NULL;
shid = shmget(key, 4096, IPC_CREAT);
printf("shid:%d\n",shid);
str=(char*)shmat(shid,NULL,0);
printf("str:%d\n",(int)str);
printf("errno:%d\n", errno);
str[0] = 'h';
str[1] = '\0';

return 0;
}

这是输出:

shid:28246036
str:-1
errno:13
zsh: segmentation fault ./t1

谢谢:D

最佳答案

您必须在一开始就定义_SVID_SOURCE_XOPEN_SOURCE

#define _SVID_SOURCE
#include <stdlib.h>
#include <sys/ipc.h>
...

使用 ftok() 创建 key

key_t key= ftok("demo.c", 'R');

它返回 errno 13 因为你没有设置 PERMS:

shid = shmget(key, 4096, IPC_CREAT);

必须是

shid = shmget(key, 4096, 0777 | IPC_CREAT);

关于c - shmat 返回 errno=13(EACCES) 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19463957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com