根据http://man7.org/linux/man-pages/man3/shm_open.3.html,它表示
After a successful shm_unlink(), attempts to shm_open() an object with the same name fail (unless O_CREAT was
specified, in which case a new, distinct object is created).
S,我尝试过这个。我正在使用以下示例,该示例在执行shm_unlink之后创建了新的共享内存对象,正如他们所说的,我使用了O_CREAT。
但是当我运行此问题时,它给我带来了与错误有关的信息bus error
。
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
int main(void) {
// Open shared memory
int fd = shm_open("TEST", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
ftruncate(fd, sizeof(int));
// Map shared memory
int *shm = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd,0);
close(fd);
// Access shared memory
*shm = 0;
// Unmap shared memory
munmap(shm, sizeof(int));
if(shm_unlink("TEST")){
printf("************success****************");
}
fd = shm_open("TEST", O_CREAT |O_RDWR, S_IRUSR | S_IWUSR);
int *shm2 = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd,0);
*shm2 = 0;
return 0;
}
在执行shm_unlink之后,再次创建具有相同名称的共享内存的正确过程是什么?
第二次尝试访问错误的共享内存(应该是shm2,而不是shm),并且不要忘记截断。
同样不相关,但是shm_unlink成功返回0。
#include <sys/mman.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(void) {
// Open shared memory
int fd = shm_open("TEST", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
ftruncate(fd, sizeof(int));
// Map shared memory
int *shm = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd,0);
close(fd);
// Access shared memory
*shm = 0;
// Unmap shared memory
munmap(shm, sizeof(int));
if(!shm_unlink("TEST")){
printf("************success****************");
}
fd = shm_open("TEST", O_CREAT |O_RDWR, S_IRUSR | S_IWUSR);
int *shm2 = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd,0);
ftruncate(fd, sizeof(int));
*shm2 = 0;
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句