1、Shell
Shell最简单的定义:命令行解释器主要包含如下:
1、将用户的命令翻译给核心(kernel)- 操作系统处理
2、同时,将核心的处理结果翻译给使用者
通过Shell,用户可以输入命令并与操作系统进行交互。Shell可以执行各种任务,如文件管理、进程控制、系统配置等。
2、Shell执行命令流程
shell读取新的一行输入,建立一个新的进程,在这个进程中运行程序 并等待这个进程结束。
所以要写一个shell,需要循环以下过程:
1、获取命令行
2、解析命令行
3、建立一个子进程(fork)
4、替换子进程(execvp)
5、父进程等待子进程退出(wait)
3、编写shell
主接口如下
3.1 Interactive
接口功能描述:打印命令行提示符,获取用户输入的命令行字符串
3.2 Split
接口功能描述:对命令行字符串进行切割
3.3 Execute
接口功能描述:子进程中执行命令
3.4 BuildinCmd
接口功能描述:处理内建命令
4、代码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define SIZE 1024
#define MAX_ARGC 64
#define SEP " "
char *argv[MAX_ARGC];
char pwd[SIZE];
char env[SIZE]; // for test
int lastcode = 0;
const char* HostName()
{
char *hostname = getenv("HOSTNAME");
if(hostname) return hostname;
else return "None";
}
const char* UserName