阅读背景:

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_normalfile1.c-----------*/
#



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: