1.在Linux中的进程之间可以通过内存映射进行通信。内存映射的原理是将创建的文件地址映射到内核中的进程的地址空间中,此时,进程可以读写文件中。两个进程同时映射到一个文件地址,你们通过对文件的读写,可以到达进行通信的目的。内存映射必须先创建一个文件,文件的大小>0。
2.1利用内存映射实现父子进程之间的通信代码:
/*进程通信之内存映射。在父子进程之间使用内存映射通信*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <wait.h>
#include <sys/mman.h>
int main()
{
//1.打开文件
pid_t fd = open("test.txt",O_RDWR); //以读写的方式打开文件
int size = lseek(fd,0,SEEK_END); //获取文件大小
//2.创建内存映射
void *prt = mmap(NULL,size,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
//3.创建子进程
int pid = fork();
if(pid > 0)
{
wait(NULL); //回收子进程的资源
//父进程读取数据
char buf[1024];
strcpy(buf,(char *)prt);
printf("read data:%s",buf);
}
if(pid == 0)
{
//子进程写入数据
strcpy((char *)prt,"let us start chat");
}
//4.释放内存映射,关闭文件
munmap(prt,size);
close(fd);
return 0;
}
运行结果:
2.2利用内存映射实现两个不同进程之间的通信代码:
/*两个没有关系的进程之间使用内存映射进行通信。此部分是读进程*/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <wait.h>
#include <sys/mman.h>
int main()
{
//1.打开文件
//int fd = open("read-write.txt",O_RDWR);
int fd = open("read-write.txt",O_RDONLY);
int size = lseek(fd,0,SEEK_END); //获取文件的大小
//2.创建内存映射
//void *prt = mmap(NULL,size,PROT_WRITE | PROT_READ,MAP_SHARED,fd,0);
void *prt = mmap(NULL,size, PROT_READ,MAP_SHARED,fd,0); //只读的方式创建内存映射
while(1)
{
char buf[1024];
strcpy(buf,(char *)prt);
printf("read data : %s\n",buf);
sleep(5);
}
//3.释放内存映射,关闭文件
munmap(prt,size);
close(fd);
return 0;
}
/*两个没有关系的进程之间使用内存映射进行通信。此部分是写进程*/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <wait.h>
#include <sys/mman.h>
int main()
{
//1.打开文件
/*需要注意,打开文件的权限必须大于等于创建的内存映射的权限,内存映射时,如果想要写入数据
必须同时具有读和写的权限。比如在这里,内存映射的权限为写,那么文件打开的权限必须为读和写,
否则会出现错误*/
int fd = open("read-write.txt",O_RDWR);
//int fd = open("read-write.txt",O_WRONLY);
int size = lseek(fd,0,SEEK_END); //获取文件的大小
//2.创建内存映射
void *prt = mmap(NULL,size,PROT_WRITE | PROT_READ,MAP_SHARED,fd,0);
while(1)
{
char buf[1024]={"you and me"};
strcpy((char *)prt,buf);
//printf("read data : %s\n",buf);
sleep(2);
}
//3.释放内存映射,关闭文件
munmap(prt,size);
close(fd);
return 0;
}
运行结果:
3.总结:内存映射的主要原理是将一个文件地址映射到两个进程中,两个进程通过操作此文件实现通信。内存映射地址的权限要小于等于打开的文件权限,同时在内存映射时,如果要有写入的权限,必须得有读取的权限。