用C语言编程模拟一个进程管理程序
时间: 2024-05-08 15:15:41 浏览: 11
以下是一个简单的进程管理程序,可以实现创建进程、终止进程、显示进程列表等简单功能。具体实现方式可能因系统平台而异。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 16
#define MAX_PROC_NUM 32
typedef struct {
int pid;
char name[MAX_NAME_LEN];
int state;
} Process;
Process procs[MAX_PROC_NUM];
int proc_num = 0;
void create_process(char *name) {
if (proc_num >= MAX_PROC_NUM) {
printf("Too many processes.\n");
return;
}
Process *p = &procs[proc_num++];
p->pid = proc_num;
strcpy(p->name, name);
p->state = 1;
printf("Process %d created with name %s.\n", p->pid, p->name);
}
void terminate_process(int pid) {
int i;
for (i = 0; i < proc_num; i++) {
if (procs[i].pid == pid) {
procs[i].state = 0;
printf("Process %d terminated.\n", pid);
return;
}
}
printf("Process %d not found.\n", pid);
}
void list_processes() {
int i;
printf("Process list:\n");
printf("PID\tName\tState\n");
for (i = 0; i < proc_num; i++) {
printf("%d\t%s\t%s\n", procs[i].pid, procs[i].name, procs[i].state ? "running" : "terminated");
}
}
int main() {
int running = 1;
char cmd[16], name[MAX_NAME_LEN];
int pid;
printf("Process management program\n");
printf("Commands: create, terminate, list, exit\n");
while (running) {
printf("> ");
scanf("%s", cmd);
if (strcmp(cmd, "create") == 0) {
scanf("%s", name);
create_process(name);
} else if (strcmp(cmd, "terminate") == 0) {
scanf("%d", &pid);
terminate_process(pid);
} else if (strcmp(cmd, "list") == 0) {
list_processes();
} else if (strcmp(cmd, "exit") == 0) {
running = 0;
} else {
printf("Invalid command.\n");
}
}
return 0;
}
```
该程序使用一个结构体数组来存储进程信息,每个进程有一个唯一的 PID、一个名称和一个状态(1 表示运行中,0 表示已终止)。程序通过不断读取用户输入的命令来实现各种功能。注意该程序没有实现进程调度和并发执行等高级功能,仅用于演示基本的进程管理操作。