用c语言实现进程管理
以下是一个简单的进程管理系统的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
// 创建子进程
pid = fork();
if (pid < 0) { // 错误处理
fprintf(stderr, "Fork failed\n");
exit(1);
}
else if (pid == 0) { // 子进程
printf("Child process\n");
execlp("/bin/ls", "ls", NULL); // 执行ls命令
}
else { // 父进程
printf("Parent process\n");
wait(NULL); // 等待子进程结束
printf("Child process completed\n");
}
return 0;
}
该程序创建一个子进程,并让子进程执行ls
命令。父进程等待子进程执行完毕后输出一条消息。在此过程中,fork()
函数用于创建子进程,execlp()
函数用于在子进程中执行ls
命令,wait()
函数用于父进程等待子进程结束。这是一个简单的进程管理示例,实际应用中还需要更多的功能来管理进程,如进程的创建、销毁、优先级调整等
原文地址: https://gggwd.com/t/topic/e3yA 著作权归作者所有。请勿转载和采集!