From ea10ad5df15a0eb51d28f474e1683f89db70d347 Mon Sep 17 00:00:00 2001 From: augustin64 Date: Tue, 26 Mar 2024 17:40:15 +0100 Subject: [PATCH] Clean mmap.c a bit --- TP/TP1/rendu/mmap.c | 81 ++++++++++++++++++++------------------------- 1 file changed, 35 insertions(+), 46 deletions(-) diff --git a/TP/TP1/rendu/mmap.c b/TP/TP1/rendu/mmap.c index 6714698..421270f 100644 --- a/TP/TP1/rendu/mmap.c +++ b/TP/TP1/rendu/mmap.c @@ -3,6 +3,8 @@ #include #include +#define CHECK_FERROR(f) { if (ferror(f)) {fprintf(stderr, "IO Error"); exit(1);} } + #include "mmap.h" struct MMap* mmap_init(){ @@ -70,31 +72,25 @@ int check_page_alloc(struct MMap *mmap) { int move_to_swap(struct MMap *mmap, struct PageInfo *page) { int key = -1; fseek(mmap->swap, 0, SEEK_SET); - if( ferror(mmap->swap) ) { - return -1; - } + CHECK_FERROR(mmap->swap); + for (int i = 0; i < 100*sizeof(int); i+=sizeof(int)) { fread(&key, sizeof(int), 1, mmap->swap); - if( ferror(mmap->swap) ) { - return -1; - } + CHECK_FERROR(mmap->swap); + if (key == -1) { fseek(mmap->swap, i, SEEK_SET); - if( ferror(mmap->swap) ) { - return -1; - } + CHECK_FERROR(mmap->swap); + fwrite(&page->key, sizeof(int), 1, mmap->swap); - if( ferror(mmap->swap) ) { - return -1; - } + CHECK_FERROR(mmap->swap); + fseek(mmap->swap, 100*sizeof(int) + (i/sizeof(int))*4096, SEEK_SET); - if( ferror(mmap->swap) ) { - return -1; - } + CHECK_FERROR(mmap->swap); + fwrite(page->data, 4096, 1, mmap->swap); - if( ferror(mmap->swap) ) { - return -1; - } + CHECK_FERROR(mmap->swap); + return 0; } } @@ -104,36 +100,29 @@ int move_to_swap(struct MMap *mmap, struct PageInfo *page) { struct PageInfo* read_from_swap(struct MMap* mmap, struct PageInfo *page) { int key = -1; fseek(mmap->swap, 0, SEEK_SET); - if( ferror(mmap->swap) ) { - return NULL; - } + CHECK_FERROR(mmap->swap); + for (int i = 0; i < 100*sizeof(int); i+=sizeof(int)) { int ret = fread(&key, sizeof(int), 1, mmap->swap); - if( ferror(mmap->swap) ) { - return NULL; - } - if (key == page->key) { - fseek(mmap->swap, 100*sizeof(int) + (i/sizeof(int))*4096, SEEK_SET); - if( ferror(mmap->swap) ) { - return NULL; - } - fread(page->data, 4096, 1, mmap->swap); - if( ferror(mmap->swap) ) { - return NULL; - } - fseek(mmap->swap, i, SEEK_SET); - if( ferror(mmap->swap) ) { - return NULL; - } - int tmp = -1; - fwrite(&tmp, sizeof(int), 1, mmap->swap); - if( ferror(mmap->swap) ) { - return NULL; - } - return page; - } else { - return NULL; - } + CHECK_FERROR(mmap->swap); + + if (key != page->key) + continue; + + fseek(mmap->swap, 100*sizeof(int) + (i/sizeof(int))*4096, SEEK_SET); + CHECK_FERROR(mmap->swap); + + fread(page->data, 4096, 1, mmap->swap); + CHECK_FERROR(mmap->swap); + + fseek(mmap->swap, i, SEEK_SET); + CHECK_FERROR(mmap->swap); + + int tmp = -1; + fwrite(&tmp, sizeof(int), 1, mmap->swap); + CHECK_FERROR(mmap->swap); + + return page; } return NULL; }