共享存储映射
文件进程间通信
使用文件也可以完成IPC,理论依据是,fork后,父子进程共享文件描述符。也就共享打开的文件。
练习:编程测试,父子进程共享打开的文件。借助文件进行进程间通信。
思考,无血缘关系的进程可以打开同一个文件进行通信吗?为什么?
/*使用文件完成进程间通信*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
int main()
{
int fd1,fd2;
pid_t pid;
char buf[1024];
char *str="---------test for shared fd in parent child process------\n";
pid = fork();
if(pid<0)
{
perror("fork error.\n");
exit(1);
}
else if(pid == 0)
{
fd1 = open("mytest.txt",O_RDWR);
if(fd1<0)
{
perror("open error.\n");
exit(1);
}
write(fd1,str,strlen(str));//子进程往文件里写
printf("child write over.\n");
}
else
{
fd2 = open("mytest.txt",O_RDWR);
if(fd2<0)
{
perror("open error.\n");
exit(1);
}
sleep(2);
int len = read(fd2,buf,sizeof(buf));//父进程从文件读
write(STDOUT_FILENO,buf,len);//打印
wait(NULL);//回收子进程
}
return 0;
}
1 mmap函数:参数;返回值
void *mmap(void *adrr, size_t length, int prot, int flags, int fd, off_t offset);
返回:成功:返回创建的映射区首地址;失败:MAP_FAILED宏
参数:
addr: 建立映射区的首地址,由Linux内核指定。使用时,直接传递NULL
length: 欲创建映射区的大小
prot: 映射区权限PROT_READ、PROT_WRITE、PROT_READ|PROT_WRITE
flags: 标志位参数(常用于设定更新物理区域、设置共享、创建匿名映射区)
MAP_SHARED: 会将映射区所做的操作反映到物理设备(磁盘)上。
MAP_PRIVATE: 映射区所做的修改不会反映到物理设备。
fd: 用来建立映射区的文件描述符
offset: 映射文件的偏移(4k的整数倍)
2 借助共享内存存放磁盘文件。借助指针访问磁盘文件。
3 父子进程、血缘关系进程 通信
4 匿名映射区