说明:这个例子是采用共享文件映射形式,写端写入数据,读端读取数据。
写端:
-
-
#include
-
#include
-
#include
-
#include
-
-
#include
-
#include
-
-
typedef struct{
-
char name[4];
-
int age;
-
}people;
-
-
main(int argc, char** argv)
-
{
-
int fd,i;
-
people *p_map;
-
char temp;
-
-
-
fd=open(argv[1],O_CREAT|O_RDWR|O_TRUNC,00777);
-
printf("file opened\n");
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
lseek(fd,sizeof(people)*5-1,SEEK_SET);
-
write(fd,"",1);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
p_map = (people*) mmap(NULL, sizeof(people)*100, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
-
close( fd );
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
temp = 'a';
-
for(i=0; i<100; i++)
-
{
-
temp += 1;
-
memcpy(( *(p_map+i)).name, &temp, 2);
-
(*(p_map+i)).age = 20+i;
-
}
-
printf("initialize over\n");
-
-
-
sleep(10);
-
munmap((char*)p_map, sizeof(people)*100);
-
printf("umap ok\n");
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
}
读端:
-
-
#include
-
#include
-
#include
-
#include
-
-
#include
-
#include
-
-
typedef struct{
-
char name[4];
-
int age;
-
}people;
-
-
main(int argc, char** argv)
-
{
-
int fd,i;
-
people *p_map;
-
-
-
fd=open( argv[1],O_CREAT|O_RDWR,00777 );
-
-
-
p_map = (people*)mmap(NULL,sizeof(people)*100, PROT_READ|PROT_WRITE, MAP_SHARED,fd,0);
-
for(i = 0;i<100;i++)
-
{
-
printf( "name: %s age %d;\n",(*(p_map+i)).name, (*(p_map+i)).age );
-
}
-
-
-
munmap((char*)p_map,sizeof(people)*100);
-
}
阅读(1780) | 评论(0) | 转发(0) |