- 论坛徽章:
- 0
|
mmap.c
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/types.h>
struct record
{
unsigned int hash;
unsigned int key;
unsigned int value;
unsigned int offest;
};
struct xmap
{
struct record *records;
unsigned int records_count;
unsigned int size_index;
};
struct xmap *alloc_user_def_t(int fd)
{
struct xmap *p;
struct record *recs;
p = (struct xmap *)mmap(NULL, sizeof(struct xmap) + sizeof(struct record) * 20, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (p == NULL)
{
return NULL;
}
p->records = calloc(20, sizeof(struct record));
recs = p->records;
recs[0].hash = 9832;
recs[0].key = 87643;
recs[0].value = 980;
recs[0].offest = 987;
recs[1].hash = 8982;
recs[1].key = 907;
recs[1].value = 243;
recs[1].offest = 124;
p->size_index = 9897;
p->records_count = 67;
return p;
}
int main()
{
int fd, i;
struct xmap *ptr;
struct record *recs;
fd = open("data.mmap", O_CREAT|O_RDWR, 0777);
lseek(fd, (sizeof(struct xmap) + sizeof(struct record) * 20) -1 , SEEK_SET);
write(fd,"",1);
ptr = alloc_user_def_t(fd);
recs = ptr->records;
printf("recs[0].hash = %d\r\n", recs[0].hash);
printf("recs[0].key = %d\r\n", recs[0].key);
printf("recs[1].hash = %d\r\n", recs[1].hash);
printf("recs[1].key = %d\r\n", recs[1].key);
printf("ptr->size_index = %d\r\n", ptr->size_index);
munmap(ptr, sizeof(struct xmap) + sizeof(struct record) * 20);
free(recs);
close(fd);
return 0;
}
|
mmap_read.c
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/types.h>
struct record
{
unsigned int hash;
unsigned int key;
unsigned int value;
unsigned int offest;
};
struct xmap
{
struct record *records;
unsigned int records_count;
unsigned int size_index;
};
int main()
{
int fd, i;
struct xmap *ptr;
struct record *recs;
fd = open("data.mmap", O_CREAT|O_RDWR, 0777);
ptr = (struct xmap *)mmap(NULL, sizeof(struct xmap) + sizeof(struct record) * 20, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
recs = ptr->records;
printf("recs[0].hash = %d\r\n", recs[0].hash);
printf("recs[0].key = %d\r\n", recs[0].key);
printf("recs[1].hash = %d\r\n", recs[1].hash);
printf("recs[1].key = %d\r\n", recs[1].key);
printf("ptr->size_index = %d\r\n", ptr->size_index);
munmap(ptr, sizeof(struct xmap) + sizeof(struct record) * 20);
close(fd);
return 0;
}
|
mmap_read.c
recs = ptr->records;
printf("recs[0].hash = %d\r\n", recs[0].hash);
printf("recs[0].key = %d\r\n", recs[0].key);
printf("recs[1].hash = %d\r\n", recs[1].hash);
printf("recs[1].key = %d\r\n", recs[1].key);
执行到这里 就有错误
struct xmap 结构体的 struct record *records; 大小是动态的
请大家帮我看看 怎么做用mmap 来保存这些数据 |
|