用c语言 模拟 一个进程管理程序 拥有创建、撤销、阻塞、唤醒与调度等功能
时间: 2023-12-26 07:05:04 浏览: 112
这是一个简单的进程管理程序,可以创建、撤销、阻塞、唤醒和调度进程。
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESS 10 // 最大进程数
typedef enum {READY, RUNNING, BLOCKED} state_t; // 进程状态
typedef struct {
int pid; // 进程ID
state_t state; // 进程状态
} process_t;
process_t processes[MAX_PROCESS]; // 进程数组
int num_processes = 0; // 进程数
// 创建进程
void create_process() {
if (num_processes == MAX_PROCESS) {
printf("Cannot create more processes!\n");
return;
}
process_t new_process;
new_process.pid = num_processes + 1;
new_process.state = READY;
processes[num_processes] = new_process;
num_processes++;
printf("Process %d created.\n", new_process.pid);
}
// 撤销进程
void destroy_process(int pid) {
int i;
for (i = 0; i < num_processes; i++) {
if (processes[i].pid == pid) {
// 撤销进程
printf("Process %d destroyed.\n", pid);
if (i != num_processes - 1) {
processes[i] = processes[num_processes - 1];
}
num_processes--;
return;
}
}
printf("Process %d not found!\n", pid);
}
// 阻塞进程
void block_process(int pid) {
int i;
for (i = 0; i < num_processes; i++) {
if (processes[i].pid == pid) {
// 阻塞进程
processes[i].state = BLOCKED;
printf("Process %d blocked.\n", pid);
return;
}
}
printf("Process %d not found!\n", pid);
}
// 唤醒进程
void unblock_process(int pid) {
int i;
for (i = 0; i < num_processes; i++) {
if (processes[i].pid == pid) {
// 唤醒进程
processes[i].state = READY;
printf("Process %d unblocked.\n", pid);
return;
}
}
printf("Process %d not found!\n", pid);
}
// 调度进程
void schedule() {
int i;
int running = -1;
// 找到正在运行的进程
for (i = 0; i < num_processes; i++) {
if (processes[i].state == RUNNING) {
running = i;
break;
}
}
// 如果没有正在运行的进程,就找到一个 READY 状态的进程运行
if (running == -1) {
for (i = 0; i < num_processes; i++) {
if (processes[i].state == READY) {
running = i;
processes[i].state = RUNNING;
printf("Process %d is running.\n", processes[i].pid);
break;
}
}
}
// 如果有正在运行的进程,就把它切换为 READY 状态,找到下一个 READY 状态的进程运行
if (running != -1) {
processes[running].state = READY;
for (i = (running + 1) % num_processes; i != running; i = (i + 1) % num_processes) {
if (processes[i].state == READY) {
processes[i].state = RUNNING;
printf("Process %d is running.\n", processes[i].pid);
break;
}
}
if (i == running) {
printf("No process is ready to run.\n");
}
}
}
int main() {
int choice, pid;
while (1) {
printf("1. Create process\n");
printf("2. Destroy process\n");
printf("3. Block process\n");
printf("4. Unblock process\n");
printf("5. Schedule process\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
create_process();
break;
case 2:
printf("Enter process ID: ");
scanf("%d", &pid);
destroy_process(pid);
break;
case 3:
printf("Enter process ID: ");
scanf("%d", &pid);
block_process(pid);
break;
case 4:
printf("Enter process ID: ");
scanf("%d", &pid);
unblock_process(pid);
break;
case 5:
schedule();
break;
case 6:
exit(0);
default:
printf("Invalid choice!\n");
}
}
return 0;
}
```
阅读全文