Linux系统编程之mmap实现无血缘关系进程通信
在两个进程里面进行实验
//08_mmap_w.c
#include<stdio.h>
#include<unistd.h>
#include<sys/typrs.h>
#include<sys/stat.h>
#include<sys/mman.h>
#include<fcntl.h>
#include<sys/wait.h>
typedef struct _Student{
int sid;
char name[20];
}student;
int main(int argc,char *argv[])
{
if(argc != 2)
{
printf("./a.out filename\n");
return -1;
}
//1.打开文件
int fd=open(argv[1],O_RDWR|O_CREAT|O_TRUNC,0666);
in length=sizeof(student);
ftruncate(fd,length);
//2、映射
strudent *stu=mmap(NULL,length,PORT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(stu ==MAP_FAILED)
{
perror("mmap err");
return-1;
}
//3、修改内存数据
int num=1;
while(1)
{
stu->sid=num++;
sprintf(stu->name,"xiaoming%03d",num++);
sleep(1);//相当于每隔一秒修改一次映射区的内容
}
//4、释放映射区和关闭文件描述符
munmap(fd,length);
close(fd);
return 0;
}
//08_maap_r.c
#include<stdio.h>
#include<unistd.h>
#include<sys/typrs.h>
#include<sys/stat.h>
#include<sys/mman.h>
#include<fcntl.h>
#include<sys/wait.h>
typedef struct _Student{
int sid;
char name[20];
}student;
int main()
{
//1、打开文件
int fd=open(argn[1],O_RDWR);//必须先执行写
//2、创建映射区
int length=sizeof(student);
student*stu=mmap(NULL,length,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(stu==MAP_FAILED)
{
perror("mmap err");
return -1;
}
//3、读数据
while(1)
{
printf("sid=%d,name=%s\n",stu->sid,stu->name);
sleep(1);
}
//4、释放映射区并且关闭文件描述符
munmap(fd,length);
close(fd);
return 0;
}
读进程的实验结果:
分析如何实现的?
两个进程的映射区都是同一个文件的映射
这也就解释了匿名映射没有办法实现无血缘关系的映射