实现简易shell (输入 输出 追加重定项)
在之前的基础上加上支持 输出重定项 输入重定项 追加重定向
相关知识可以查看
系统文件io调用接口
文件描述符
进程程序替换
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <sys/wait.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8
9
10 int main()
11 {
12
13 char cmd[1024];
14 char* myargv[16];
15 int fd=-1;
16 while(1)
17 {
18
19 printf("[wens@localhost myshell]# ");
20
21 fgets(cmd,sizeof(cmd),stdin);
22
23 int i=0;
24
25 cmd[strlen(cmd)-1]='\0';
26
27 myargv[i++]=strtok(cmd," ");//将字符串分割解析
28
29 char *ret=NULL;
30
W> 31 while(ret=strtok(NULL," "))
32 {
33 myargv[i++]=ret;
34 }
35
36 myargv[i]=NULL;
37
38 // for( j=0;j<i;j++)
39 // printf("%s\n",myargv[j]);
40
41
42
43
44
45
46 int j=0;
47 pid_t id=fork();
48 if(id==0)
49 {
50 // printf("child\n");
51
52 for(j=0;j<i;j++)
53 {
54 if(strcmp(myargv[j],">")==0) // 输出 重定项
55 {
56 close(1);
57 fd=open(myargv[j+1],O_WRONLY|O_CREAT,0644);
58 //srv printf("%d\n",fd);
59 if(fd<0)
60 {
61 perror("open");
62 exit(1);
63 }
64 myargv[j]=NULL;
65 i=j;
66 break;
67 }
68 else if(strcmp(myargv[j],"<")==0) // 输入 重定项
69 {
70 close(0);
71 fd=open(myargv[j+1],O_RDONLY,0644);
72 if(fd<0)
73 {
74 perror("open");
75 exit(1);
76 }
77
78 myargv[j]=NULL;
79 i=j;
80 break;
81 } else if(strcmp(myargv[j],">>")==0) / / 追加 重定项
82 {
83 close(1);
84 fd=open(myargv[j+1],O_WRONLY|O_CREAT|O_APPEND,0644);
85 if(fd<0)
86 {
87 perror("open");
88 exit(1);
89 }
90
91 myargv[j]=NULL;
92 i=j;
93 break;
94 }
95
96 }
97 execvp(myargv[0],myargv);
98 //进行程序替换
99
100 exit(1);
101
102 }else{
103 // printf("parent\n");
104 waitpid(id,NULL,0); //等待子进程
105 }
106 }
107
108
109 return 0;
110
111 }
输出重定项
[wens@localhost newshell]$ ./newshell
[wens@localhost myshell]# ls
Makefile newshell newshell.c
[wens@localhost myshell]# ls > pp
[wens@localhost myshell]# cat pp
Makefile
newshell
newshell.c
pp
[wens@localhost myshell]#
输入重定项
[wens@localhost myshell]# wc < pp
9 14 116
[wens@localhost myshell]# cat < pp
Makefile
newshell
newshell.c
pp
newshell:newshell.c
gcc -o newshell newshell.c
.PHONY:clean
clean:
rm -f newshell
[wens@localhost myshell]#
追加重定项
[wens@localhost myshell]# cat Makefile >> pp
[wens@localhost myshell]# cat pp
Makefile
newshell
newshell.c
pp
newshell:newshell.c
gcc -o newshell newshell.c
.PHONY:clean
clean:
rm -f newshell
[wens@localhost myshell]#