【Linux】简易的shell

       shell:简单点理解,就是系统跟计算机硬件交互时使用的中间介质,它只是系统的一个工具实际上,在shell和计算机硬件之间还有一层东西那就是系统内核shell本质上就是将进程程序替换。

替换原理:

           用fork创建子进程后执行的是和父进程相同的程序(但有可能执行不同的代码分支),子进程往往要调用一种exec函数以执行另一个程序。当进程调用一种exec函数时,该进程的用户空间代码和数据完全被新程序替换,从新程序的启动例程开始执行。调用exec并不创建新进程,所以调用exec前后该进程的id并未改变。

替换函数:

        其中有六种以exec开头的函数,统称为exec函数:

#include<unistd.h>

int execl(const char* path,const char* arg,...);
int execlp(const char* file,const char* arg,...);
int execle(const char* path,const char* arg,...,char* const envp[]);
int execv(const char* path,char* const argv[]);
int execvp(const char* file,char* const argv[]);
int execve(const char* path,char* const argv[],char* const envp[]);

函数解释:

      1、这些函数如果调用成功则加载新的程序从启动代码开始执行,不在返回。

      2、如果调用出错则返回1。

      3、所以exec函数只有出错的返回值而没有成功的返回值。

命名理解:

      1、l(list): 表示参数列表 
      2、v(vector) : 参数用数组 
      3、p(path):有p自动搜索环境变量PATH 
      4、e(env) : 表示自己维护环境变量

shell的实现:

shell从用户读入字符串“ls”,shell建立一个新的进程,然后在那个进程中运行ls程序并等待那个进程结束。


所以要写一个shell,需要循环以下过程: 
(1)获取命令行 
(2)解析命令行 
(3)建立一个子进程(fork) 
(4)替换子进程(execvp) 

(5)父进程等待子进程退出(wait)

根据这些思路,实现一个简单的shell:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<string.h>

char *argv[8];
int argc = 0;
	void do_parse(char *buf)
{
	int i;
	int status = 0;
	for(argc=i=0;buf[i];i++){
	
		if(!isspace(buf[i]) &&status == 0){
		
			argv[argc++] = buf + i;
			status = 1;
		}else if(isspace(buf[i])){
		
			status = 0;
			buf[i] = 0;
		}	
	}
	argv[argc] = NULL;
}

void do_execute(void)
{
	pid_t pid = fork();
	switch(pid){
	
		case -1:
		perror("fork");
		exit(EXIT_FAILURE);
		break;
		case 0:
		execvp(argv[0],argv);
		perror("execvp");
		exit(EXIT_FAILURE);
		default:
		{
			int st;
			while(wait(&st) != pid)
				;
		}
	}
}
	int main(void)
{
	char buf[1024]  = {};
	while(1){
	
		printf("myshell>:");
		scanf("%[^\n]%*c",buf);
		do_parse(buf);
		do_execute();
	}
}

测试结果:



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值