引言
Linux 系统主要由内核和外壳组成,普通用户操作的是外壳程序。在 Shell 之上存在命令行解释器(如 Bash),负责接收并执行用户输入的指令。本文旨在模拟实现一个简易版命令行解释器。
Bash 本质
Bash 是一个不断运行的进程。输入指令后,Bash 会创建子进程并进行程序替换。由于进程间具有独立性,可以同时存在多个 Bash 实例,支持多用户登录。
需求分析
Bash 需要完成命令解释和程序替换任务,主要功能包括:
- 接收指令字符串
- 对指令进行分割
- 创建子进程,执行进程替换
- 回收僵尸进程
- 处理特殊指令
基本框架
简易版 Bash 代码基本框架如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>
#include <assert.h>
#define ARGV_SIZE 64
void split(char* argv[ARGV_SIZE], char* ps);
int main() {
while(1) {
printf("[User@myBash default]$ ");
fflush(stdout);
// 读取指令
// 指令分割
pid_t id = fork();
if(id == 0) {
execvp(...); // 具体细节略
();
}
status = ;
waitpid(id, &status, );
}
;
}


