在Linux上编写C语言,实现从键盘输入时间片长度、任务个数、每一个任务的到达时间及服务时间; 构造相应的进程并按时间片轮转调度算法对所有进程进行调度,进程运行情况可以输出到终端,从而深入理解时间片轮转调度算法的原理。 编写linux上可运行的程序
时间: 2024-02-09 13:13:16 浏览: 58
好的,下面是一个可以在Linux上运行的C语言程序,实现了时间片轮转调度算法:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESSES 10
struct Process {
int id;
int arrival_time;
int service_time;
int remaining_time;
};
int main() {
struct Process processes[MAX_PROCESSES];
int num_processes, time_slice, current_time = 0, i, j, quantum_count = 0, done_count = 0;
float avg_wait_time = 0, avg_turnaround_time = 0;
// 输入时间片长度和任务个数
printf("Enter time slice length: ");
scanf("%d", &time_slice);
printf("Enter number of processes: ");
scanf("%d", &num_processes);
// 输入每个进程的到达时间和服务时间
for (i = 0; i < num_processes; i++) {
printf("Enter arrival time and service time for process %d: ", i+1);
scanf("%d %d", &processes[i].arrival_time, &processes[i].service_time);
processes[i].id = i+1;
processes[i].remaining_time = processes[i].service_time;
}
// 按照到达时间排序
for (i = 0; i < num_processes; i++) {
for (j = i+1; j < num_processes; j++) {
if (processes[i].arrival_time > processes[j].arrival_time) {
struct Process temp = processes[i];
processes[i] = processes[j];
processes[j] = temp;
}
}
}
// 时间片轮转调度
printf("\nProcess execution order:\n\n");
printf("Time\tProcess\n");
while (done_count < num_processes) {
for (i = 0; i < num_processes; i++) {
if (processes[i].remaining_time > 0 && processes[i].arrival_time <= current_time) {
printf("%d\tP%d\n", current_time, processes[i].id);
quantum_count++;
processes[i].remaining_time--;
if (processes[i].remaining_time == 0) {
done_count++;
avg_wait_time += current_time - processes[i].arrival_time - processes[i].service_time + time_slice*quantum_count;
avg_turnaround_time += current_time - processes[i].arrival_time + time_slice*quantum_count;
quantum_count = 0;
}
else if (quantum_count == time_slice) {
quantum_count = 0;
}
}
}
current_time++;
}
// 输出平均等待时间和平均周转时间
avg_wait_time /= num_processes;
avg_turnaround_time /= num_processes;
printf("\nAverage waiting time: %.2f units\n", avg_wait_time);
printf("Average turnaround time: %.2f units\n", avg_turnaround_time);
return 0;
}
```
你可以将以上代码保存在一个名为 `scheduler.c` 的文件中,并使用以下命令编译并运行该程序:
```
gcc scheduler.c -o scheduler
./scheduler
```
然后按照程序提示输入时间片长度、任务个数以及每个进程的到达时间和服务时间即可。程序将输出每个进程的执行情况以及平均等待时间和平均周转时间。
阅读全文