linux系统编程--内存映射(进程通信)

1 进程间通信的思路

  • 有血源关系的
    • 父亲进程之间共享内存映射区
    • 相比于文件操作
      • 优势在于1:效率高(因为直接在内存上操作)2:不阻塞
      • 缺点在于:一定要注意读写顺序
  • 没有血源关系的进程间通信
    • 如何通信
      • 能使用匿名映射的方式 ,
      • 只能借助磁盘文件创建映射区
      • 不阻塞
    • a(a.c)进程 b(b.c)进程
      • a.c (
      •   	int fd=open("hello");
          	void *ptr=mmap(,,,,,fd,0);
          	//下来进行读写操作)
        
      • b.c
      •   	int fd1=open("hello");
          	void *ptr1=mmap(,,,,fd1,0);
          	//下来进行读写操作)
        

2父进程永远共享的

  • 文件描述符
  • 内存映射区

3有血源关系进程之间通信

3.1匿名映射内存

#include
#include
#include
#include
#include
#include 
#include 
#include
#include
int main(){
	int length=4096;
	//创建文件内存映射区
	void *buf=mmap(NULL,length,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANON,-1,0);
	if(MAP_FAILED==buf){
		perror("nmap,error");
		return 1;
	}
	pid_t pid=fork();
	if(pid==-1){
		perror("fork error");
		exit(1);
	}
	if(pid>0){
		//写数据
		strcpy(buf,"你好  hello");
		//回收
		wait(NULL);

	}else if(pid ==0){
		
		//读数据
		printf("文件:%s\n",(char *)buf);
	}
	//iprintf("%s\n",(char *)buf);
	munmap(buf,length);
return 0;
}

3.2有名映射内存

int main(){
	//打开一个文件
	int fd =open("english.txt",O_RDWR);
	int length=lseek(fd,0,SEEK_END);
	//创建文件内存映射区
	void *buf=mmap(NULL,length,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
	if(MAP_FAILED==buf){
		perror("nmap,error");
		return 1;
	}
	pid_t pid=fork();
	if(pid==-1){
		perror("fork error");
		exit(1);
	}
	if(pid>0){
		//写数据
		strcpy(buf,"你好  hello");
		//回收
		wait(NULL);

	}else if(pid ==0){
		
		//读数据
		printf("文件:%s\n",(char *)buf);
	}
	//iprintf("%s\n",(char *)buf);
	munmap(buf,length);
return 0;
}

4无血源关系进程之间通信

4.1read端

#include
#include
#include
#include
#include
#include 
#include 
#include
#include
int main(){
	//打开一个文件
	int fd =open("temp",O_RDWR|O_CREAT);
	ftruncate(fd,4096);
	int length=4096;
	//创建文件内存映射区
	void *buf=mmap(NULL,length,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
	if(MAP_FAILED==buf){
		perror("nmap,error");
		return 1;
	}
	while(1){
		sleep(1);
		//读数据
		printf("%s\n",(char *)buf+1024);
	}
	munmap(buf,length);
return 0;
}

4.2write端

#include
#include
#include
#include
#include
#include 
#include 
#include
#include
int main(){
	//打开一个文件
	int fd =open("temp",O_RDWR|O_CREAT,0664);
	int length=4096;
	//创建文件内存映射区
	void *buf=mmap(NULL,length,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
	if(MAP_FAILED==buf){
		perror("nmap,error");
		return 1;
	}
	while(1){
		//写数据
		char *p=(char *)buf;
		p+=1024;
		strcpy(p,"你好  hello\n");
		sleep(2);
	}
	munmap(buf,length);
return 0;
}

你可能感兴趣的:(系统编程)