Linux下利用程序替换来实现shell(exec*函数调用)
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <sys/wait.h>
5 #include <string.h>
6
7 #define NUM 128
8 #define CMD_NUM 64
9
10 int main()
11 {
12 char command[NUM];
13 for( ; ; )
14 {
15 char *arvg[CMD_NUM]={NULL};
16 //1.打印提示符
17 command[0]='\0';//用折中方式,可以做到O(1)时间复杂度,清空字符串
18 printf("[who@myhome mini_shell]#");
19 fflush(stdout);
20
21 //2.获取字符串
22 fgets(command,NUM,stdin);
23 command[strlen(command)-1]='\0';//将回车'\n'置为\0 "ls\n\0";
24 //printf("echo:%s\n",command);
25
26
27 //"ls -a -l \0";
28 //3.解析命令字符串 ,char* arvg[];
29 //strtok();
30 const char *sep=" ";
31 arvg[0]=strtok(command,sep);
32 int i=1;
33 while(arvg[i]=strtok(NULL,sep))
34 {
35 i++;
36 }
37
38
39 //for(int i=0;arvg[i];i++)
40 //{
41 //printf("arvg[%d]:%s\n",i,arvg[i]);
42 //}
43
44
45 //4.检验命令是否需要shell本身执行,内建命令
46 if(strcmp(arvg[0],"cd")==0)
47 {
48 if(arvg[1]!=NULL)
49 chdir(arvg[1]);
50 continue;
51 }
52
53 //5.执行第三方命令
54 if(fork()==0)
55 {
56 //child
57 execvp(arvg[0],arvg);
58 exit(1);
59 }
60 int status=0;
61 waitpid(-1,&status,0);
62 printf("exit code %d\n",(status>>8)&0xFF);
63
64 }
65
66 return 0;
67 }