请用C语言编写一个C程序完成实验,实现先来先服务算法和短进程优先算法。要求定义进程控制块PCB,能输入进程个数、进程到达时间以及进程执行时间。请给出能准确运行且不闪退的详细代码。请让代码尽量简单且不闪退,有详细中文注释。请一次性给出完整的代码。
时间: 2024-12-14 09:24:35 浏览: 4
在C语言中,实现先来先服务(FCFS, First-Come-First-Served)和短进程优先(SJF, Shortest Job First)调度算法需要创建一个进程结构体(Process Control Block, PCB),并包含进程的基本信息和队列管理。以下是两个调度算法的简单实现,其中FCFS作为基础,然后添加了对SJF的支持。注意,这个例子假设所有进程都在同一时刻到达。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义进程控制块结构
typedef struct {
int pid; // 进程ID
int arrival_time; // 到达时间
int burst_time; // 执行时间
int service_time; // 已服务时间
struct process *next; // 指向下一个PCB的指针
} Process;
// 初始化空队列
struct process *init_queue() {
return NULL;
}
// 添加进程到队列
void add_to_queue(struct process **queue, Process *new_process) {
if (*queue == NULL) {
*queue = new_process;
} else {
Process *current = *queue;
while (current->next != NULL) {
current = current->next;
}
current->next = new_process;
}
}
// FCFS调度函数
void fcfs_schedule(struct process **queue) {
Process *current = *queue;
while (current != NULL) {
printf("PID %d arrives at time %d, burst time is %d.\n",
current->pid, current->arrival_time, current->burst_time);
// 简单模拟进程执行
sleep(current->burst_time); // 暂停执行时间
current->service_time += current->burst_time;
printf("PID %d has been served for %d time units.\n",
current->pid, current->service_time);
// 移动到下一个进程
current = current->next;
}
}
// SJF调度函数 - 假设已知所有进程的CPU时间
void sjf_schedule(struct process **queue) {
Process *shortest_burst = *queue;
Process *current = *queue;
while (current != NULL) {
if (current->burst_time < shortest_burst->burst_time) {
shortest_burst = current;
}
current = current->next;
}
fcfs_schedule(&shortest_burst);
}
int main() {
int num_processes;
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
Process *processes[num_processes];
srand(time(0)); // 设置随机种子
for (int i = 0; i < num_processes; i++) {
processes[i] = (Process*)malloc(sizeof(Process));
processes[i]->pid = i + 1;
processes[i]->arrival_time = rand() % 100; // 随机生成到达时间
processes[i]->burst_time = rand() % 20 + 1; // 随机生成执行时间
processes[i]->service_time = 0;
processes[i]->next = NULL;
}
// 将进程加入FCFS队列
struct process *queue = init_queue();
for (int i = 0; i < num_processes; i++) {
add_to_queue(&queue, processes[i]);
}
printf("\nFCFS scheduling:\n");
fcfs_schedule(&queue);
printf("\nSJF scheduling (assuming CPU times are known):\n");
sjf_schedule(&queue);
return 0;
}
```
阅读全文