综合上篇博文的知识,我们可以实现一个简易的shell -->/​​*上篇文章链接*​​/

用下图的时间轴来表示时间的发生次序。其中时间从左到右。shell由标识符为sh的方块代表,它随着时间的流逝从左到右移动。shell从用户读入字符串"ls" 。shell建议一个新的子进程,然后在子进程中运行ls程序并等待子进程结束。其中这部分包含了进程的创建,进程程序替换,进程等待部分知识,在上篇博文都有介绍。

[ Linux ] 手动实现一个简易版的shell_模拟实现

然后shell读取新的一行输入,建立一个新的进程,在这个进程中运行程序,并等待这个进程结束。

思路和步骤

所以要写一个shell,需要循环一下过程:

  • 获取命令行
  • 解析命令行(使用strtok分割字符串)
  • 建立子进程(fork)
  • 替换子进程(execvp)
  • 父进程等待子进程退出(waitpid)

代码实现

根据这些思路和步骤,我们来看一下实现的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#define SEP " "
#define SIZE 128
#define NUM 1024
char command_line[NUM];
char* command_args[SIZE];

char env_buffer[NUM];
extern char** environ;

int ChangeDir(const char* new_path)
{
chdir(new_path);
return 0;//调用成功
}

void PutEnvInMyShell(char* new_env)
{
putenv(new_env);
}

int main()
{
//一个shell 本质上就是一个死循环
while(1)
{
//不关心获取这些属性的接口
//1.显示提示符
printf("[张三@我的主机名 当前目录]# ");
fflush(stdout);
//2.获取用户输入
memset(command_line,'\0',sizeof(command_line)*sizeof(char));
fgets(command_line,NUM,stdin);//获取 输入 stdin
command_line[strlen(command_line) - 1] = '\0';//清空\n
//printf("%s\n",command_line);

//3."ls -l -a -i" --> "ls","-l","-a","-i" 字符串切分
command_args[0] = strtok(command_line, SEP);
int index = 1;
//给ls添加颜色
if(strcmp(command_args[0]/*程序名*/,"ls") == 0)
command_args[index++] = (char*)"--color=auto";
//strtok 截取成功 返回字符串起始地址
//截取失败 返回NULL
while(command_args[index++] = strtok(NULL,SEP));
// for debug
//for(int i = 0;i<index;++i)
//{
// printf("%d:%s\n",i,command_args[i]);
//}

//4.TODO
//如果直接exec*执行cd,最多只是让子进程进行路径切换,
//子进程是一运行就完毕的进程!我们在shell中,更希望
//父进程的路径切换
//如果有些行为必须让父进程shell执行,不想让子进程
//这种情况下不能创建子进程,只能让父进程自己实现对应的代码
//这部分由父shell自己执行的命令称之为内建命令
if(strcmp(command_args[0],"cd") == 0 && command_args[1] != NULL)
{
ChangeDir(command_args[1]);
continue;
}

if(strcmp(command_args[0],"export") == 0 && command_args[1] != NULL)
{
strcpy(env_buffer,command_args[1]);
PutEnvInMyShell(env_buffer);
continue;
}

//5.创建子进程
pid_t id = fork();
if(id == 0)
{
//child
//6.程序替换
execvp(command_args[0],/*里面保存的就是执行的名字*/command_args);

exit(1);//执行到这里一定失败了
}
int status = 0;
pid_t ret = waitpid(id,&status,0);
if(ret>0)
{
printf("等待子进程成功: sig:%d, code:%d\n",status&0x7F,(status>>8)&0xFF);
}
}

return 0;
}

程序测试

[ Linux ] 手动实现一个简易版的shell_shell_02

[ Linux ] 手动实现一个简易版的shell_进程替换_03


大家感兴趣的话可以自己模拟实现一下哦~

(本篇完)