mmap的使用之两个进程通过映射普通文件实现共享内存通信

/*-------------map_normalfile1.c-----------*/
#include	<sys/mman.h>
#include	<sys/types.h>
#include	<fcntl.h>
#include	<string.h>
#include	<stdio.h>
#include	<unistd.h>


typedef struct{
	char name[4];
	int age;
}  people;

//mmap_normal_file1.c 两个进程通过映射普通文件实现共享内存通信 
void main(int argc, char **argv)//map a normal file as shared mem:
{
	int fd,i;
	people *p_map;
	char temp;
	char data[64];
	fd = open(argv[1], O_CREAT | O_RDWR | O_TRUNC, 00777);
	lseek(fd, sizeof(people) * 5 - 1, SEEK_SET);
	write(fd, "", 1);
	//把文件映射到共享内存
	p_map = (people*)mmap(NULL, sizeof(people) * 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	close(fd);
	temp = 'a';
	for(i=0;i<10;i++)
	{
		temp += 1;
		sprintf(data, "exe%c", temp);
		memcpy((*(p_map + i)).name, &data, strlen(data));
		(*(p_map + i)).age = 20 + i;
	}
	printf("initializeover  write finish \n");
	sleep(10);
	munmap(p_map, sizeof(people) * 10);
	printf("umap ok\n"); 
}
 

/*-------------map_normalfile2.c-----------*/  
#include <sys/mman.h>  
#include <sys/types.h>  
#include <fcntl.h>
#include <stdio.h>  
#include <unistd.h>  

typedef struct {  
    char name[4];   
    int age;   
}people;   
	
//mmap_normal_file2.c 两个进程通过映射普通文件实现共享内存通信 
void main(int argc, char **argv)//map a normal file as shared mem:  
{
	  
    int fd, i;   
    people *p_map;   
    fd = open(argv[1], O_CREAT | O_RDWR, 00777);   
    p_map = (people*)mmap(NULL, sizeof(people) * 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);   
    for(i = 0 ; i < 10 ; i++)  
	{
		  
	    printf("read data name=%s age=%d;\n", (*(p_map + i)).name, (*(p_map + i)).age);   
	}  
	munmap(p_map, sizeof(people) * 10);   
	
}

#Generated by VisualGDB project wizard.
#Note: VisualGDB will automatically update this file when you add new sources to the project.
#CMakeList.txt
cmake_minimum_required(VERSION 2.7)
project(LinuxProject1)
set(LIBRARIES_FROM_REFERENCES "")
add_executable(mmap_normal_file1 mmap_normal_file1.c)
add_executable(mmap_normal_file2 mmap_normal_file2.c)
target_link_libraries(mmap_normal_file1 "${LIBRARIES_FROM_REFERENCES}")
target_link_libraries(mmap_normal_file2 "${LIBRARIES_FROM_REFERENCES}")

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值