ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

Linux shell命令解释器

Linux shell命令解释器 自主Shell命令行解释器目标要能处理普通命令要能处理内建命令要能帮助我们理解内建命令/本地变量/环境变量这些概念要能帮助我们理解shell的允许原理实现原理用下图的时间轴来表示事件的发生次序。其中时间从左向右。shell由标识为sh的方块代表它随着时间的流逝从左向右移动。shell从用户读入字符串“ls”。shell建立一个新的进程然后在那个进程中运行ls程序并等待那个进程结束。然后shell读取新的一行输入建立一个新的进程在这个进程中运行程序并等待这个进程结束。所以要写一个shell需要循环一下过程获取命令行解析命令行建立一个子进程替换子进程父进程等待子进程退出。代码源码#includeiostream#includecstdio#includecstring#includecstdlib#includeunistd.h#includesys/types.h#includesys/wait.husingnamespacestd;#defineCOMMAND_SIZE1024#defineFORMAT[%s%s %s]# #defineSEP //下面是shell定义的全局数据#defineMAXARGC128char*g_argv[MAXARGC];intg_argc128;constchar*GetUserName(){constchar*namegetenv(USER);returnnameNULL?None:name;}constchar*GetHostName(){constchar*hostnamegetenv(HOSTNAME);returnhostnameNULL?None:hostname;}constchar*GetPwd(){constchar*pwdgetenv(PWD);returnpwdNULL?None:pwd;}stringDirName(constchar*pwd){#defineSLASH/string dirpwd;if(dirSLASH){return/;}autoposdir.rfind(SLASH);if(posstring::npos){returnBUG;}returndir.substr(pos1);}voidMakeCommandLine(charcmd_prompt[],intsize){snprintf(cmd_prompt,size,FORMAT,GetUserName(),GetHostName(),DirName(GetPwd()).c_str());}voidPrintCommandPrompt(){charprompt[COMMAND_SIZE];MakeCommandLine(prompt,sizeof(prompt));printf(%s,prompt);fflush(stdout);}boolGetCommandLine(char*out,intsize){char*cfgets(out,size,stdin);if(cNULL){returnfalse;}out[strlen(out)-1]0;//清理\nif(strlen(out)0){returnfalse;}returntrue;}//3.命令行分析boolCommandParse(char*commandline){//命令行分析 ”ls -a -l“ --- ls -a -lg_argc0;g_argv[g_argc]strtok(commandline,SEP);//nullptr 传的是历史被切的字串while(g_argv[g_argc]strtok(nullptr,SEP)){}g_argc--;returntrue;}voidPrintArgv(){for(inti0;g_argv[i];i){printf(argv[%d]-%s\n,i,g_argv[i]);}printf(argc: %d\n,g_argc);}intExecute(){pid_t idfork();if(id0){//childexecvp(g_argv[0],g_argv);exit(1);}//fatherpid_t ridwaitpid(id,nullptr,0);(void)rid;return0;}intmain(){while(true){//1.输出命令行提示符PrintCommandPrompt();//2.获取用户输入的命令//printf([%s%s %s]# ,GetUserName(),GetHostName(),GetPwd());charcommandline[COMMAND_SIZE];if(!GetCommandLine(commandline,sizeof(commandline))){continue;}printf(echo :%s\n,commandline);//3.命令行分析CommandParse(commandline);PrintArgv();//4.执行命令Execute();}return0;}源码拆解1.输出命令行提示符stringDirName(constchar*pwd){#defineSLASH/string dirpwd;if(dirSLASH){return/;}autoposdir.rfind(SLASH);if(posstring::npos){returnBUG;}returndir.substr(pos1);}voidMakeCommandLine(charcmd_prompt[],intsize){snprintf(cmd_prompt,size,FORMAT,GetUserName(),GetHostName(),DirName(GetPwd()).c_str());}voidPrintCommandPrompt(){charprompt[COMMAND_SIZE];MakeCommandLine(prompt,sizeof(prompt));printf(%s,prompt);fflush(stdout);}觉得我回答有用的话记得点个关注哟谢谢支持
返回列表