模拟实现shell
什么是shell
shell是系统的用户界面,提供了用户与内核进行交互操作的一种接口。它接受用户输入的命令并把它送入内核去执行。实际上shell就是一个命令解释器,它解释有用户输入的命令并且把它们送到内核。不仅如此,shell有自己的编程语言用于对命令的编辑,它允许用户编写由shell命令组成的程序。shell变成语言具有普通编程语言的很多特点,比如它也有循环结构和分支控制结构等,用这种编程语言编写的shell程序与其他应用程序具有同样的效果。
实现shell,需要做到以下四点:
- 接收带空格的字符串
- 解析字符串,实现做到遇到空格则发生截断,再将其放入子进程的参数列表(这里使用strtok函数)
- 创建一个子进程进行进程替换,实现用户的功能
- 父进程等待子进程结束,退出程序
1 #include <stdio.h>
2 #include <string.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5 #include <sys/wait.h>
6
7 #define SIZE 256
8 #define NUM 16
9
10 int main()
11 {
12 char cmd[SIZE];
13 const char *cmd_line = "[myshell@VM-8-16-centos miniShell]# ";
14
15 while(1){
16 cmd[0] = 0;
17 printf("%s", cmd_line);
18 fgets(cmd, SIZE, stdin);
19 cmd[strlen(cmd)-1] = '\0';
20
21 char *args[NUM];
22 args[0] = strtok(cmd," ");
23 int i = 1;
24 do{
25 args[i] = strtok(NULL, " ");
26 if(args[i] == NULL){
27 break;
28 }
29 ++i;
30 }while(1);
31
32 pid_t id = fork();
33 if(id < 0){
34 perror("fork error!\n");
35 continue;
36 }
37
38 if(id == 0){
39 //child
40 execvp(args[0], args);
41 exit(1);
42 }
43
44 int status = 0;
45 pid_t ret = waitpid(id, &status, 0);//0阻塞
46 if(ret > 0){
47 printf("status code : %d\n", (status>>8)&0xff);
48 }
49
50 }
51 return 0;
52 }