磁盘调度算法c语言代码包括先来先服务(FCFS)、最短寻道时间优先(SSTF)、扫描算法(SCAN)
时间: 2023-07-27 09:21:37 浏览: 129
[操作系统磁盘调度算法]OS实验C语言代码实现FCFS/SSTF/SCAN/CSCAN
5星 · 资源好评率100%
以下FCFS、SSTF和SCAN算法的C语言代码:
1. 先来先服务(FCFS)算法:
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, j, sum = 0, head, req[100];
printf("Enter the number of requests: ");
scanf("%d", &n);
printf("Enter the requests: ");
for(i=0; i<n; i++)
scanf("%d", &req[i]);
printf("Enter the initial head position: ");
scanf("%d", &head);
printf("The order of servicing the requests is:\n%d ", head);
for(i=0; i<n; i++)
{
printf("%d ", req[i]);
sum += abs(head - req[i]);
head = req[i];
}
printf("\nTotal head movements: %d", sum);
return 0;
}
```
2. 最短寻道时间优先(SSTF)算法:
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, j, sum = 0, head, min, diff, pos, req[100], flag[100]={0};
printf("Enter the number of requests: ");
scanf("%d", &n);
printf("Enter the requests: ");
for(i=0; i<n; i++)
scanf("%d", &req[i]);
printf("Enter the initial head position: ");
scanf("%d", &head);
printf("The order of servicing the requests is:\n%d ", head);
for(i=0; i<n; i++)
{
min = 1000;
for(j=0; j<n; j++)
{
if(flag[j]==0)
{
diff = abs(head - req[j]);
if(diff < min)
{
min = diff;
pos = j;
}
}
}
sum += abs(head - req[pos]);
head = req[pos];
flag[pos] = 1;
printf("%d ", req[pos]);
}
printf("\nTotal head movements: %d", sum);
return 0;
}
```
3. 扫描算法(SCAN):
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, j, sum = 0, head, max, k, req[100], flag[100];
printf("Enter the number of requests: ");
scanf("%d", &n);
printf("Enter the requests: ");
for(i=0; i<n; i++)
scanf("%d", &req[i]);
printf("Enter the initial head position: ");
scanf("%d", &head);
printf("Enter the maximum cylinder size: ");
scanf("%d", &max);
printf("The order of servicing the requests is:\n");
for(i=head; i<=max; i++)
flag[i] = 0;
for(i=0; i<n; i++)
flag[req[i]] = 1;
for(i=head; i>=0; i--)
flag[i] = 0;
sum = head;
printf("%d ", head);
for(i=head; i<=max; i++)
{
if(flag[i]==1)
{
printf("%d ", i);
sum += abs(head - i);
head = i;
}
}
for(i=max; i>=0; i--)
{
if(flag[i]==1)
{
printf("%d ", i);
sum += abs(head - i);
head = i;
}
}
printf("\nTotal head movements: %d", sum);
return 0;
}
```
上述代码分别实现了FCFS、SSTF和SCAN三种磁盘调度算法,您可以根据需要选择其中的一种或多种进行使用。
阅读全文