今天在学mmap(2)将文件映射到内存空间的时候,我想到了一个用法,就是将文件当做内存的转储,然后在让另一个进程共享这个文件,以此方法来实现进程间共享内存的功能。
进程1的程序代码
#include<stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
int fd;
fd=open(argv[1],O_RDWR); //打开共享文件
if(fd == -1)
{
perror("open");
return 2;
}
//使用mmap将文件映射到内存空间
void *p=mmap(NULL,6,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(p == MAP_FAILED) //错误处理
{
perror("mmap");
return 1;
}
*((int *)p)=0x31323334; //向内存写入,也就是向文件写入
getchar(); //等待另一个进程
*((int *)p)=0x35363738; //改变写入的值,看另一个进程读取值的变化
getchar();
munmap(p,6); //释放内存空间(不确定)
close(fd); //文件标志计数减1
return 0;
}
进程2的程序代码
#include<stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
int fd;
fd=open(argv[1],O_RDWR);
if(fd == -1)
{
perror("open");
return 2;
}
void *p=mmap(NULL,6,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(p == MAP_FAILED)
{
perror("mmap");
return 1;
}
printf("p char %c\n",*((int *)p)); //输出p的一个字节,以char形式
printf("p %s\n",((int *)p)); //输出p的内容
getchar();
printf("p char %c\n",*((int *)p)); //输出进程1改变后的值
printf("p %s\n",((int *)p));
getchar();
munmap(p,6);
close(fd);
return 0;
}
运行操作和结果:
进程一
[sun@localhost day6]$ ./a.out hello //第一步
//第三步:按空格
进程二
[sun@localhost day6]$ ./B hello //第二步
p char 4
p 4321o world
//第四步:按空格
p char 8
p 8765o world
此结果表明,文件是可以被两个进程同时映射到内存空间进行操作的,我们的实验也成功了
现在我们要考虑的是如何将数据存储在连续的内存空间,好方便我们进行存取
关于这个后续我会把我做出的程序继续分享给大家