|
发表于 2023-12-21 15:55:31
|
显示全部楼层
本楼为最佳答案
 首先,我们需要定义一个结构体类型来描述进程的属性。根据题目要求,可以定义一个名为"Process"的结构体,包括进程的编号、名称、优先级、状态、剩余执行时间和描述等属性。
然后,我们需要定义一个结构体数组来存储4个进程。可以使用以下代码进行定义:
- #include <stdio.h>
- // 定义进程结构体类型
- typedef struct {
- int pID; // 进程编号
- char pName[20]; // 进程名称
- int pPriority; // 进程优先级
- int pState; // 进程状态
- int pCPU; // 剩余执行时间
- char pDescription[50]; // 进程描述
- } Process;
- int main() {
- // 定义进程数组
- Process processes[4] = {
- {1, "chrome.exe", 101, 1, 2, "google chrome"},
- {2, "chrome.exe", 101, 1, 1, "google chrome"},
- {3, "chrome.exe", 101, 1, 0, "google chrome"},
- {4, "360.exe", 102, 1, 0, "360 safe protect"}
- };
-
- // 进程调度
- int i;
- for (i = 0; i < 4; i++) {
- // 找到当前就绪状态中优先级最高的进程
- int maxPriorityIdx = -1;
- int maxPriority = -1;
- int j;
- for (j = 0; j < 4; j++) {
- if (processes[j].pState == 1 && processes[j].pPriority > maxPriority) {
- maxPriorityIdx = j;
- maxPriority = processes[j].pPriority;
- }
- }
-
- if (maxPriorityIdx != -1) {
- // 将该进程状态改为执行状态,输出当前进程信息,然后执行pCPU--
- processes[maxPriorityIdx].pState = 2;
- printf("%d :%s %d %d %d %d %s\n", processes[maxPriorityIdx].pID, processes[maxPriorityIdx].pName,
- processes[maxPriorityIdx].pPriority, processes[maxPriorityIdx].pState,
- processes[maxPriorityIdx].pCPU, processes[maxPriorityIdx].pDescription);
- processes[maxPriorityIdx].pCPU--;
-
- // 如果剩余执行时间为0,则将该进程状态改为完成状态
- if (processes[maxPriorityIdx].pCPU == 0) {
- processes[maxPriorityIdx].pState = 3;
- printf("%d :%s %d %d %d %s\n", processes[maxPriorityIdx].pID, processes[maxPriorityIdx].pName,
- processes[maxPriorityIdx].pPriority, processes[maxPriorityIdx].pState,
- processes[maxPriorityIdx].pCPU, processes[maxPriorityIdx].pDescription);
- }
- }
- }
-
- return 0;
- }
复制代码
以上代码模拟了进程调度的过程,并按照题目要求输出当前进程的信息。运行程序,即可看到与样例输出相符的结果。需要注意的是,此处只模拟了一次进程调度的过程,如果需要循环执行进程调度直到没有就绪状态进程为止,可以在外层增加循环语句来实现。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|