mmap記憶體對映

程式碼修行者發表於2016-07-10

資料寫入檔案

#include<stdio.h>
#include<sys/mman.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);

        fp = fopen("records.dat","r+");
        fseek(fp,43*sizeof(record),SEEK_SET);
        fread(&record,sizeof(record),1,fp);
        printf("%d",record.integer);

        record.integer = 143;
        sprintf(record.string,"RECORD-%d",143);

        fseek(fp,43*sizeof(record),SEEK_SET);
        fwrite(&record,sizeof(record),1,fp);
        fclose(fp);
}

記憶體對映

#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 f = open("records.dat",O_RDWR);

        //對映大記憶體
        mapped = (RECORD *)mmap(0,NRECORDS * sizeof(record),PROT_READ|PROT_WRITE,MAP_SHARED,f,0);
        sprintf(mapped[43].string,"RECORD-%d",243);

        //回寫到檔案
        msync((void *)mapped, NRECORDS * sizeof(record), MS_ASYNC);
        //關閉對映
        munmap((void *)mapped,NRECORDS * sizeof(record));

        close(f);
}

相關文章