注意:实际问题在于使用 fork() 函数。所以找到了解决方案。
//create shared memoery
int shmfd;
void *shared_memory = (void *)0;
shmfd = shm_open("/shm2_rev_to_upp", O_RDWR | O_CREAT | O_EXCL, 0666); //reverse to upper
if (shmfd == -1) {
perror("shm_open");
exit(1);
}
if(ftruncate(shmfd, sizeof(struct shared_use_st)) == -1){
perror("ftruncate");
exit(1);
}
shared_memory = mmap(NULL, sizeof(struct shared_use_st), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
if(shared_memory == MAP_FAILED){
perror("mmap");
exit(1);
}
//some code here
munmap(shared_memory, sizeof(struct shared_use_st));
shm_unlink("/shm2_rev_to_upp");
close(shmfd);
我在运行时遇到了这个错误
shm_open: File exists
然后 shm_open() 返回 -1
为什么会这样?!!
请注意,我运行程序的头几次,错误没有出现!!
我该如何解决这个问题?!
最佳答案
手册页解释了各种错误代码:
EEXIST
: Both O_CREAT and O_EXCL were specified to shm_open() and the shared memory object specified by name already exists.
关于linux - Unix:共享内存。 shm_open() 返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53094658/