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

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

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

然后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;
}

程序测试

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

(本篇完)

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白又菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值