Shell is a command line interpreter, but many people don't understand it well, but if you can understand this simple shell implementation, the problem will be solved.
1. The shell is a command line interpreter.
2. It is a program used to capture commands and will not execute
3. Shell is a program that users can communicate with the kernel better
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<unistd.h>
4 #include<sys/wait.h>
5 #include<string.h>
6 int main(){
7 while(1){
8 printf("[user@localhost path]$ ");
9 fflush(stdout);
10 //这里不能用换行刷新缓冲区,否则输入就另起一行
11 char scan[1024]={
0};
12 fgets(scan,1024,stdin);
13 //这一步一定要-1,因为输入的时候会输入一个回车,这一步把回车替换
14 scan[strlen(scan)-1]='\0';
15
16 char* idx=scan;
17 char* myagv[10]={
NULL};
18 int myagc=0;
19 while(*idx!='\0'){
20 if(*idx!=' '){
21 myagv[myagc]=idx;
22 ++myagc;
23 while(*idx!='\0'&&*idx!=' '){
24 ++idx;
25 }
26 *idx='\0';
27 ++idx;
28 }
29 myagv[myagc]=NULL;
30 }
31
32 //cd命令是shell本身实现
33 if(strcmp("cd",myagv[0])==0){
34 chdir(myagv[1]);//chdir系统调用接口实现切换目录
35 continue;
36 }
37
38 //开始创建进程
39 pid_t pid=fork();
40 if(pid<0){
41 perror("make error");
42 }
43 if(pid==0){
44 execvp(myagv[0],myagv);
45 //用myagv指针数组来存输入内容,选execvp
46 perror("error");
47 exit(-1);
48 }
49 waitpid(-1,NULL,0);//进程等待
50
51
52 }
53 return 0;
54 }
We can see that minishell helps us to create a process, replace waiting and exit. This is the working mode of the shell. Of course, the actual shell is more complicated and multi-functional. I hope it will help you.