mmap共享内存

mmapwrite.c

#include
#include
#include
#include
#include
#include

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

int main(int argc, char **argv) {
	
	int fd, i;
	person *p_map;
	char temp;
	
	fd=open("./mmap_text.txt", O_CREAT|O_RDWR|O_TRUNC,00777);
	lseek(fd, sizeof(person)*5, SEEK_SET);
	write(fd,"",1);
	p_map=(person*)mmap(NULL,sizeof(person)*10,PROT_READ|
PROT_WRITE, MAP_SHARED, fd, 0);
	close(fd);
	temp = 'a';
	
	for(i=0; i<10; i++) {
		temp += 1;
		memcpy((*(p_map+i)).name, &temp, 2);
		(*(p_map + i)).age = 20+i;
	}
	printf("initialize over!\n");
	sleep(2);
	munmap(p_map, sizeof(person)*10);
	printf("munmap ok!\n");
	
	return 0;
}

mmapread.c

#include
#include
#include
#include
#include
#include

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

int main(int argc, char **argv) {
	
	int fd, i;
	person *p_map;
	
	fd = open("./mmap_text.txt", O_CREAT|O_RDWR,00777);
	p_map=(person*)mmap(NULL,sizeof(person)*10,PROT_READ|
PROT_WRITE, MAP_SHARED, fd, 0);
	
	for(i=0; i<10; i++) {
		printf("name: %s, age: %d;\n", (*(p_map+i)).name, (*(p_map+i)).age);
	}

	munmap(p_map, sizeof(person)*10);
	printf("munmap ok!\n");
	
	close(fd);
	
	return 0;
}

 

你可能感兴趣的:(进程之间的通信)