【Linux】——实现一个简单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[]
函数解释
  • 这些函数如果调用成功则加载新的程序从启动代码开始执行,不再返回。
  • 如果调用出错则返回-1
  • 所以exec函数只有出错的返回值而没有成功的返回值。
命名理解

这些函数原型看起来很容易混,但只要掌握了规律就很好记。

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

exec调用举例如下:

#include <unistd.h>
int main()
{
	char *const argv[] = { "ps", "-ef", NULL };
	char *const envp[] = { "PATH=/bin:/usr/bin", "TERM=console", NULL };
	execl("/bin/ps", "ps", "-ef", NULL);
	// 带p的,可以使用环境变量PATH,无需写全路径
	execlp("/bin/ps", "ps", "-ef", NULL);
	// 带e的,需要自己组装环境变量
	execle("/bin/ps", "ps", "-ef", NULL, envp);
	execv("/bin/ps", argv);

	// 带p的,可以使用环境变量PATH,无需写全路径
	execvp("ps", argv);
	// 带e的,需要自己组装环境变量
	execve("/bin/ps", argv, envp);
	exit(0);
}

minshell

  • 之前我们讲到进程的控制以及我们今天讲的进程替换,综合这些知识我们就可以实现一个简单的shell(命令行解释器)
  • 代码如下所示:
  1 #include <stdio.h> 
  2 #include <iostream> 
  3 #include <cstdio> 
  4 #include <cstring> 
  5 #include <cstdlib> 
  6 #include <string> 
  7 #include <unistd.h> 
  8 #include <sys/types.h> 
  9 #include <sys/wait.h> 
 10  
 11 using namespace std; 
 12  
 13 #define NUM 32 
 14  
 15 int main() 
 16 { 
 17     char buff[1024] = {0}; 
 18     string tips = "[CXY@localhost XXX]# ";//仿造一个命令行解释器提示符 
 19     cout << tips; 
 20     fgets(buff, sizeof(buff)-1, stdin);//从键盘中获取用户输入的信息,不能用cin,因为会有空格 
 21     buff[strlen(buff) - 1] = 0; 
 22  
 23     //ls -a -l -o -i 
 24     char *argv[NUM];//为使用替换函数execvp,创建该数组以传递命令 
 25     argv[0] = strtok(buff," ");//字符串分隔函数,将每个命令分隔 
 26     int i = 0; 
 27     while(argv[i] != NULL){ 
 28         i++; 
 29         argv[i] = strtok(NULL," "); 
 30     } 
 31     pid_t id = fork(); 
 32     if(id == 0){//child
 33         cout << "child running...." << endl;
 34         execvp(argv[0],argv);
 35         exit(123);
 36     }else{//father
 37         int status = 0;
 38         waitpid(id, &status, 0);//创建子进程去执行相关命令,父进程只要等就行了
 39         cout << "Exit Code: "<< WEXITSTATUS(status) << endl;
 40     }
 41     return 0;
 42 }
  • 运行结果展示:
  • 这里我们实现的命令行解释器只能执行Linux下80%的命令,像是管道符、重定向符这些命令无法实现,因为这些命令不是通过创建子进程来执行的。
    minshell
  • 6
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值