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;
}