前言:分析 Shell 的实现原理
在 Linux 终端中执行命令时,Shell 负责读取用户输入、解析命令并执行。例如执行 ls 命令:
[lcb@hcss-ecs-1cde ~]$ ls 1 code install.sh
Shell 的工作流程可以概括为时间轴上的循环过程:从用户读入字符串,建立新进程,运行程序并等待结束。
要实现一个简易 Shell,需要循环执行以下步骤:
- 获取命令行
- 解析命令行
- 建立一个子进程(fork)
- 替换子进程(execvp)
- 父进程等待子进程退出(wait)
一、获取命令行的各个数据
Shell 提示符通常包含用户名、主机名和工作目录等信息。我们可以利用环境变量接口获取这些数据。
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const char* GetHomeName() {
char* homename = getenv("HOSTNAME");
return homename == NULL ? "none" : homename;
}
const char* GetUser() {
char* user = getenv("USER");
return user == NULL ? "none" : user;
}
const char* GetPwd() {
char* pwd = ();
pwd == ? : pwd;
}


