mmap內存共享範例 linux

mmap1,cpp 與mmap2.cpp 是兩個獨立的文件,分別是讀的進程和寫的進程

並且實現了進程間的通信

mmap1

#include<iostream>
#include<unistd.h>
#include<cstdlib>
#include<cstdio>
#include<fcntl.h>
#include<sys/mman.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<cstring>
const char *FILENAME = "hello";
const int SIZE = 100;
void sys_err(const char *str)
{
perror(str);
exit(-1);
}
int  main()
{
int fd = open(FILENAME,O_RDWR|O_CREAT,0664);
if(fd == -1)
{
sys_err("open");
}
lseek(fd,SIZE-1,SEEK_SET);
write(fd,"\0",1);
char *mem;
mem = static_cast<char *>(mmap(NULL,SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0));
if(mem == MAP_FAILED)
{
sys_err("mmap");
}
int n = 0;
char buf[SIZE];
while(1)
{
sprintf(buf,"this is :%d\n",n++);
memcpy(mem,buf,sizeof(buf));
sleep(1);
}
close(fd);
munmap(mem,SIZE);




return 0;
}



mmap2

#include<iostream>
#include<unistd.h>
#include<cstdlib>
#include<cstdio>
#include<fcntl.h>
#include<sys/mman.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<cstring>
const char *FILENAME = "hello";
const int SIZE = 100;
void sys_err(const char *str)
{
perror(str);
exit(-1);
}
int  main()
{


int fd = open(FILENAME,O_RDONLY);
if(fd == -1)
{
sys_err("open");
}
char *mem;
mem = static_cast<char *>(mmap(NULL,SIZE,PROT_READ,MAP_SHARED,fd,0));
if(mem == MAP_FAILED)
{
sys_err("mmap");
}
int n = 0;
while(1)
{
std::cout<<mem<<std::endl;
sleep(1);
}
close(fd);
munmap(mem,SIZE);




return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章