我正在尝试在 C 中实现不同的 OS 调度算法。我已经实现了 FCFS 和非抢占式最短作业优先调度,但是,对于抢占式 SJF 将发生的循环,我遇到了困难。这是我的文本文件的示例。
Process Arrival Burst
1 0 7
2 2 4
3 4 1
4 5 4
通过求解,我得到的平均等待时间是 4,但是,我似乎无法正确获得算法。
这是我的代码示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 256
//Create 2 structures
//XYZ: X = ALGO; Y = NUM OF PROCESSES; Z = FOR RR
//ABC: A = PID; B = ARRIVAL TIME; C = EXEC TIME
struct XYZ {
int algo, numProcesses, timeSlice;
};
struct ABC {
int pid, arrivalTime, execTime, endTime, waitTime, startTime;
};
int main(){
/*
ALGO DEFINER:
0 = FCFS ; 1 = NON PREEMPTIVE; 2 = PREEMPTIVE ; 3 = RR
*/
char filename[255];
struct XYZ scheduler;
struct ABC process[255], temp;
int i, j, k;
float average = 0.0, totalSum = 0.0;
FILE *filepointer;
int num = 0; //initialize to 0, if not, num = num+1 will start with 1
printf("Enter the name/path of the file: ");
scanf("%s", filename);
//If filename does not exist
filepointer = fopen(filename, "r");
if(filepointer == NULL){
printf("Filename %s does not exist\n", filename);
exit(1);
}
//If filename exists, continue
//Checking of file contents first
char buffer[LEN];
i = 0;
printf("File contents: \n");
//scan the file
while(fgets(buffer, LEN - 1, filepointer) != NULL){
sscanf(buffer, "%d %d %d", &process[i].pid, &process[i].arrivalTime, &process[i].execTime);
printf("%d %d %d\n", process[i].pid, process[i].arrivalTime, process[i].execTime);
i = i+1;
num = num+1; //store the number of lines, in my test is 10
}
//Store the first line as the XYZ structure
scheduler.algo = process[0].pid;
scheduler.numProcesses = process[0].arrivalTime;
scheduler.timeSlice = process[0].execTime;
//Preemptive SJF scheduling
//Sort the arrival time of each process
for(i = 1; i < num; i++){
for(j = 1; j < num-i; j++){
if(process[j].arrivalTime > process[j+1].arrivalTime){
temp = process[j];
process[j] = process[j+1];
process[j+1] = temp;
}
}
}
printf("Arrangement\n");
for(i = 0; i < num; i++){
printf("%d %d %d\n", process[i].pid, process[i].arrivalTime, process[i].execTime);
}
//Run the algo on the sorted arrival time
//Scan the whole dataset starting from the 1st line, line 0 is the indicator
for(i = 1; i < num; i++){
//insert code here for preemptive
}
return 0;
}