1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <string.h>
5
6 void do_shell(char **argv)
7 {
8 int n;
9 if ((n=fork()) == 0)
10 {
11 execvp(argv[0], argv);
12 exit(0);
13 }
14 else if (n > 0)
15 {
16 wait(NULL);
17 }
18 return ;
19 }
20
21 void do_parse(char *buf)
22 {
23 char *argv[8] = {};
24 int argc = 0;
25 int status = 0;
26 int i;
27 for (i=0; buf[i]!=0; i++)
28 {
29 if (!isspace(buf[i]) && status == 0)
30 {
31 argv[argc++] = buf+i;
32 status = 1;
33 }
34 else if (isspace(buf[i]))
35 {
36 buf[i] = 0;
37 status = 0;
38 }
39 }
40 argv[argc] = NULL;
41 do_shell(argv);
42 }
43
44 int main()
45 {
46 while (1)
47 {
48 char buf[1024] = {};
49 printf("myshell:");
50 scanf("%[^\n]%*c", buf);
51 if (strncmp(buf, "exit", 4) == 0)
52 exit(0);
53 do_parse(buf);
54 }
55 }
自主shell原理:首先将读入的字符串分割,然后用fork创建一个子进程,在子进程中调用execvp函数来执行从读入的命令,execvp用新的程序文件替换了子进程原先的执行文件,而父进程等待子进程终止通过调用wait来实现。