#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct __page{
int size, pSize, pid;
}page;
enum stat{unallocated, fragmentation, freeP};
int main(int argc, char **argv){
if(argc != 3){
fprintf(stderr, "Usage: %s <slices> <algorithm>\n", argv[0]);
exit(EXIT_FAILURE);
}
time_t t;
srand((unsigned) time(&t));
int i, pSize, pid = 0, v, v_id;
int slices = atoi(argv[1]);
char fit = argv[2][0];
page *memory = (page *) malloc(slices * sizeof(page));
int stats[3] = {0, 0, 0};
stats[2] = slices;
switch(fit){
case 'f':
printf("First fit algorithm\n\n");
break;
case 'b':
printf("Best fit algorithm\n\n");
break;
case 'w':
printf("Worst fit algorithm\n\n");
break;
default:
printf("algorithm not found!\n");
exit(EXIT_FAILURE);
}
for(i = 0; i < slices; i++){
memory[i].size = 100 * (rand() % 8 + 1);
memory[i].pSize = -1;
memory[i].pid = -1;
printf("page %d - size: %d\n", i, memory[i].size);
}
printf("\n");
while(1){
v_id = -1;
v = -1;
printf("process %d size: ", pid);
scanf("%d", &pSize);
if(pSize == 0)
break;
switch(fit){
case 'f':
for(v_id = 0; v_id < slices; v_id++)
if(memory[v_id].pSize == -1 && memory[v_id].size >= pSize){
break;
}
break;
case 'b':
for(i = 0; i < slices; i++)
if(memory[i].pSize == -1 && memory[i].size >= pSize){
v_id = i;
v = memory[i].size;
break;
}
for(; i < slices; i++)
if(memory[i].pSize == -1 && memory[i].size >= pSize && memory[i].size < v){
v_id = i;
v = memory[i].size;
}
break;
case 'w':
for(i = 0; i < slices; i++)
if(memory[i].pSize == -1 && memory[i].size >= pSize){
printf("a:%d\n", i);
v_id = i;
v = memory[i].size;
break;
}
for(; i < slices; i++)
if(memory[i].pSize == -1 && memory[i].size >= pSize && memory[i].size > v){
printf("b:%d\n", i);
v_id = i;
v = memory[i].size;
}
break;
}
if(v_id == slices){
printf("process %d could not be allocated\n", pid);
printf("\tprocess size: %d\n\n",pSize);
stats[0]++;
}
else{
memory[v_id].pSize = pSize;
memory[v_id].pid = pid;
printf("process %d allocated in page %d\n", pid, v_id);
printf("\tprocess size: %d\n", pSize);
printf("\tpage size: %d\n", memory[v_id].size);
printf("\tinternal fragmentation: %d\n\n", memory[v_id].size - memory[v_id].pSize);
stats[1] += memory[v_id].size - memory[v_id].pSize;
stats[2]--;
}
pid++;
}
printf("Unallocated processes: %d\n", stats[unallocated]);
printf("Total internal fragmentation: %d\n", stats[fragmentation]);
printf("free pages: %d\n", stats[freeP]);
free(memory);
return 0;
}
Comments