创建一个mini_shell的过程
- 获取标准输入。
- 对数据进行解析,得到要运行的的所有命令参数信息。
- 创建子进程,进行程序替换,让子进程运行。
- 父进程进行进程等待 。
代码实现:
1 //1.获取标准输入
2 //2.对数据进行解析-》得到要运行的的所有命令参数信息
3 //[ ls -l ] ->[ls][-l]
4 //3.创建子进程,进行程序替换,让子进程运行
5 //4.父进程等待子进程退出
6
7 #include<stdio.h>
8 #include<stdlib.h>
9 #include<unistd.h>
10 #include<string.h>
11 #include<error.h>
12 #include<sys/wait.h>
13 #include<ctype.h>//isspace()的头文件
14 int main()
15 {
16 while(1)
17 {
18 printf("[wzf@localhost]$ ");
19 fflush(stdout);
20 char buf[1024] = {0};
21 fgets(buf,1023,stdin);//从标准输入获取用户敲击的命令
22 buf[strlen(buf) - 1] = '\0';
23 printf("cmd:[%s]\n",buf);
24
25 //解析
26 int argc = 0;
27 char* argv[32] = {NULL};
28 char* ptr = buf;
29 while(*ptr != '\0')
30 {
31 if(!isspace(*ptr))
32 {
33 argv[argc] = ptr;
34 argc++;
35 while(!isspace(*ptr) && *ptr != '\0')
36 {
37 ptr++;
38 }
39 *ptr = '\0';
40 }
41 ptr++;
42 }
43 argv[argc] = NULL;//这一定不能忘记
44
45 int i = 0;
46 for(i ; i < argc; i++)
47 {
48 printf("[%s]\n",argv[i]);
49 }
50
51 pid_t pid = fork();
52 if(pid == 0)
53 {
54 execvp(argv[0],argv);
55 exit(-1);
56 }
57 waitpid(-1,NULL,0);
58 }
59 return 0;
60 }