gpt4 book ai didi

c - Linux C : Accessing shared memory fails with `Invalid Argument` even though it was just created

转载 作者:行者123 更新时间:2023-12-03 09:58:33 24 4
gpt4 key购买 nike

我的这个函数负责创建一个共享内存段。如您所见,我检查 EEXIST如果这个键已经有一个共享内存。由于我使用相同的 key 定期执行程序,因此该共享内存在第一次程序执行后存在。

作为测试,之后我尝试通过 shmat() 直接访问共享内存。 .但无论出于何种原因,它都失败了。这是控制台的输出:

Shared memory with Key 4661 already exists, continue...
Failed to obtain `Shared Memory`: Invalid argument

这是功能:
#define SHM_KEY 0x1235
int create_shrd_memory(uint64_t size) {
const int shmid = shmget(SHM_KEY, size, IPC_CREAT | IPC_EXCL);
if(shmid == -1) {
if(errno == EEXIST) {
printf("Shared memory with Key %d already exists, continue...\n", SHM_KEY);
char *shdmem = shmat(SHM_KEY, NULL, 0);
if(shdmem == -1) {
fprintf(stderr, "Failed to obtain `Shared Memory`: %s\n", strerror(errno));
}
shmdt(shdmem);
return SHM_KEY;
} else {
fprintf(stderr, "Failed to obtain Shared Memory: %s\n", strerror(errno));
perror("shmget");
exit(1);
}
}

return shmid;
}

如果我忘记调用 shmdt(),你知道会发生什么吗? ?这会导致这个错误吗?

最佳答案

shmat第一个参数是 shmget 的返回值,您正在混合 key 和 ID。

你的代码应该是这样的:

int create_shrd_memory(uint64_t size) {
int shmid = shmget(SHM_KEY, size, IPC_CREAT | IPC_EXCL);
if(shmid == -1) {
if(errno == EEXIST) {
printf("Shared memory with Key %d already exists, continue...\n", SHM_KEY);

shmid = shmget(SHM_KEY, size, 0);

char *shdmem = shmat(shmid, NULL, 0);
if(shdmem == -1) {
fprintf(stderr, "Failed to obtain `Shared Memory`: %s\n", strerror(errno));
}
shmdt(shdmem);
return SHM_KEY;
} else {
fprintf(stderr, "Failed to obtain Shared Memory: %s\n", strerror(errno));
perror("shmget");
exit(1);
}
}

return shmid;
}

关于c - Linux C : Accessing shared memory fails with `Invalid Argument` even though it was just created,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60504242/

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