自主实现minishell
1.什么是minishell?
2.minishell实现的基本原理
3.minishell的实现源码
4.自主实现的minishel的运行
----------------------------------------------------------------------------------------------------------
- 什么是minishell?
1.shell就是一个命令行解释器。当用户输入一个命令后,然后shell会进行解析额,然后调用相应的应用程序,完成相应功能.
- 2.minishell实现的基本原理
- 给出用户提示信息,然后等待用户的标准输入 【ls -l -a】 用 scanf 或fgets
2.对用户数据进行解析,得到程序名称【ls】以及参数信息【-l】和【-a】;
3.创建子进程,在子进程中进行程序替换。
4.shell程序需要等待子进程退出。
- 3.minishell的实现源码
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<unistd.h>
4 #include<string.h>
5 #include<ctype.h>
6 int main()
7 {
8 while(1)
9 {
10 //输出提示
11 printf("[test@localhost ]$ ");
12 fflush(stdout); //刷新缓冲区,但是不换行
13 char buff[1024];
14 fgets(buff,1023,stdin); //从标准输入读取数据
15 // printf("%s",buff);
16 buff[strlen(buff)-1]='\0';
17 char * tmp[100]={NULL};
18 int index=0;
19 char * str=buff;
20 while((*str)!='\0')
21 {
//以空白符为间隔,然后依次提取出每段字符串,然后放入tmp数组中
22 if(!isspace(*str))
23 {
24 tmp[index]=str;
25 index++;
26 while(!isspace(*str)&&(*str)!='\0')
27 {
28 str++;
29
30 }
31
32 *str='\0';
33 }
34 str++;
35
36 }
37
38 int i;
//打印一下,验证提取是否正确
39 for(i=0;i<index;i++)
40 {
41 printf("tmp[%d]=[%s]\n",i,tmp[i]);
42 }
43 //3.创建子进程
44 pid_t pid=fork();
45 if(pid<0)
46 {
//如果创建失败的话,就再创建一次,不能因为创建失败退出
47 continue;
48 }
49 else if(pid == 0)
50 {
51 //子进程
52 execvp(tmp[0],tmp);
53 exit(0);
54 }
55 else
56 {
57 //父进程阻塞等待子进程,否者会产生僵尸进程。
58 wait(NULL);
60 }
61
62 }
63 return 0;
64 }
4.自主实现的minishel的运行