命名MMAP没有磁盘io
我想使用POSIX标准MMAP,就好像SHMAT具有ID一样,它们共享相同的共享内存。 使用MAP_ANON时,MMAP似乎通常使用FD = -1,在这种情况下,据说从子过程继承时是有效的。
我想确保在产卵方法中采取相同的行为。然后,我可以使用命名的共享内存,但我希望它根本没有磁盘io。
我认为MAP_ANON是必不可少的,因为我想始终保证RAM的速度,而不会在磁盘上留下任何文件,以免发生意外关闭。
那么在map_anon | map_shared时提供fd!= -1是合理的吗?
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>
int main (int argc, char *argv[])
{
struct stat sb;
char *p;
int fd;
fd = shm_open("test", O_RDWR | O_CREAT, 0600);
if (fd == -1) {
perror("open");
return 1;
}
size_t len = 128;
if (ftruncate(fd, len) == -1) {
perror("ftruncate");
return 1;
}
p = (char*)mmap(0, len, PROT_WRITE|PROT_READ, MAP_ANON|MAP_SHARED, fd, 0);
if (p == MAP_FAILED){
perror("mmap");
return 1;
}
if (close(fd)==-1) {
perror("close");
return 1;
}
for (int i = 0; i < len; i++) {
putchar(p[i]);
}
if (munmap(p, len) == -1) {
perror("munmap");
return 1;
}
if(shm_unlink("test")) {
perror("unlink");
return 1;
}
fprintf(stderr,"\n");
return 0;
}
I wanted to use the POSIX standard mmap as if shmat had an id, they share the same shared memory.
mmap seems to normally use fd=-1 when using MAP_ANON, and in this case it is said to be valid when inheriting from a child process.
I wanted to ensure the same behavior in the spawn method. Then I can use named shared memory, but I wish it didn't do DISK IO at all.
I think MAP_ANON is essential because I want to always guarantee the speed of RAM without leaving any files on the DISK in case of an unexpected shutdown.
So is it reasonable to provide fd!=-1 while being MAP_ANON|MAP_SHARED?
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>
int main (int argc, char *argv[])
{
struct stat sb;
char *p;
int fd;
fd = shm_open("test", O_RDWR | O_CREAT, 0600);
if (fd == -1) {
perror("open");
return 1;
}
size_t len = 128;
if (ftruncate(fd, len) == -1) {
perror("ftruncate");
return 1;
}
p = (char*)mmap(0, len, PROT_WRITE|PROT_READ, MAP_ANON|MAP_SHARED, fd, 0);
if (p == MAP_FAILED){
perror("mmap");
return 1;
}
if (close(fd)==-1) {
perror("close");
return 1;
}
for (int i = 0; i < len; i++) {
putchar(p[i]);
}
if (munmap(p, len) == -1) {
perror("munmap");
return 1;
}
if(shm_unlink("test")) {
perror("unlink");
return 1;
}
fprintf(stderr,"\n");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论