- 论坛徽章:
- 0
|
先贴下代码
<code>
#include<unistd.h>
#include<stdio.h>
#include<sys/mman.h>
#include<fcntl.h>
#include<stdlib.h>
typedef struct {
int integer;
char string[24];
} RECORD;
#define NRECORDS (100)
int main()
{
RECORD record, *mapped;
int i, f;
FILE *fp;
fp=fopen("records.dat","w+");
for(i=0;i<NRECORDS;i++)
{
record.integer = i;
sprintf(record.string,"RECORD-%d",i);
fwrite(&record,sizeof(record),1,fp);
}
fclose(fp);
printf("#############1#############\n");
fp = fopen("records.dat","r+");
fseek(fp,43*sizeof(record),SEEK_SET);
fread(&record,sizeof(record),1,fp);
record.integer = 143;
sprintf(record.string,"RECORD-%d",record.integer);
fseek(fp,43*sizeof(record),SEEK_SET);
fwrite(&record,sizeof(record),1,fp);
fclose(fp);
printf("###############2##############\n");
f = open("record.dat",O_RDWR);
mapped = (RECORD *)mmap(0,NRECORDS*sizeof(record),PROT_READ|PROT_WRITE,MAP_SHARED,f,0);
mapped[42].integer = 243;
sprintf(mapped[42].string,"RECORD-%d",mapped[42].integer);
msync((void *)mapped,NRECORDS*sizeof(record), MS_ASYNC);
munmap((void *)mapped, NRECORDS*sizeof(record));
close(f);
printf("##################3#############\n");
exit(0);
}
</code>
经过我调试发现mapped[42].integer = 243这行出现段错误。 不知道为什么。。。。 |
|