SHELL外壳的简易实现
1.什么是shell外壳?
shell外壳是连接用户和操作系统的一种中间层软件,负责将用户输入的指令经过处理后提交给操作系统。shell外壳本身也是一个进程,它最主要的职责就是创建子进程并让子进程完成某些任务,但有时shell外壳也会自己执行任务,在linux系统下shell外壳称为bash。
2.如何实现shell外壳
shell外壳的简易实现先依靠fork函数创建子进程,再利用exec*系列函数把子进程替换成某些已经存在于磁盘的可执行程序,最后利用循环实现子进程的持续创建和替换,而父进程shell则不受影响。
以下是shell外壳的模拟实现代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/wait.h>
#define SUM 1024
#define SIZE 32
#define SEP " "
char cmd_line[SUM];
char* g_argv[SIZE];
int main()
{
while(1)
{
printf("[root]");
fflush(stdout);
memset(cmd_line,'\0',sizeof(cmd_line));
if(fgets(cmd_line,sizeof(cmd_line),stdin)==NULL)//从标准输入流获取字符串数据
{
continue;
}
cmd_line[strlen(cmd_line)-1]='\0&#