/*************************************************************************
> File Name: mmap_test_01.c
> Author: xuchen_allen
> Mail: [email protected]
> Created Time: 2019年02月01日 星期五 20时54分37秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/mman.h>
#include<fcntl.h>
#include<sys/wait.h>
//父子进程间的通信:
#define SIZE sizeof(long)
int main()
{
int *area;
pid_t pid;
char *buf[2048];
//利用文件test来创建存储映射区:
int fd = open("test",O_RDWR);//注意打开文件的权限;
if(fd<0){
perror("open fail");
exit(1);
}
area =(int *) mmap(NULL,4,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(area == MAP_FAILED){
perror("mmap fail");
exit(1);
}
close(fd);
//存储映射区创建完毕;
int *temp=area;
pid=fork();
if(pid<0){
perror("fork fail");
exit(1);
}
/*
else if(pid > 0){
sleep(1);
printf("parent\t*temp=%d\n",*temp);
wait(NULL);
munmap(area,4);
}
else
{
*temp=10;
printf("child\t*temp=%d\n",*temp);
}
*/
else if(pid>0){
*temp=10;
printf("parent\t %d\n",*temp);
wait(NULL);
printf("parent\t %d\n",*temp);
munmap(area,4);
}
else{
printf("child\t%d\n",*temp);
*temp=20;
printf("%d\n",*temp);
}
exit(0);
}
分别放了两个测试,一是子传父,一个是父传子再传父。
代码比较简单,好理解。