自动实现一个minishell更新(增加重定向功能)

增加重定向功能

  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <stdlib.h>
  4 #include <string.h>
  5 #include <fcntl.h>
  6 #include <sys/types.h>
  7 #include <sys/stat.h>
  8 int main(){
  9     //1.等待用户输入
 10     while(1){
 11         printf("[fw@localhost$ root] ");
 12         char str[1024] = {0};//设置最大的长度
 13         if(scanf("%[^\n]%*c",str)!=1){
 14             getchar();
 15             continue;
 16         }
 17         //选出>或者>>两种符号
 18         int fd = 1;
 19         int dup_flag = 0;
 20         char* dup_file;
 21         char* ff = str;
 22         while(*ff!='\0'){
 23             if(*ff == '>'){
 24                 dup_flag = 1;
 25                 *ff = '\0';
 26                 ff++;
 27                 if(*ff == '>'){
 28                     dup_flag = 2;
 29                     *ff = '\0';
 30                     ff++;
 31                 }
 32                 while(*ff==' '){
 33                     ff++;
 34                 }
 35                 dup_file = ff;
 36             }
 37             ff++;
 38         }
 39         
 40         //2.解析输入数据,用数组存储起来,
 41         char* s[32]={0};
 42         char* start = str;
 43         char* end = str;
 44         int i = 0;
 45         while(*end !='\0'){
 46             if(*end!=' '){
 47                 s[i++] = end;
 48                 while(*end!=' '&&*end!='\0'){
 49                     end++;
 50                 }
 51             }
 52             *end = '\0';
 53             end++;
 54         }
 55         s[i]= NULL;
 56         if(strcmp(s[0],"cd") == 0){
 57             //   int chdir(const char *path);
 58             chdir(s[1]);
 59             continue;
 60         }
 61         //3.创建子进程,在子进程中进行数据读
 62         //4.等待子进程退出
 63         pid_t pid;
 64         pid = fork();
 65         if(pid<0){
 66             continue;
 67         }
 68         else if(pid == 0){//创建一个子进程执行逻辑
 69             //找到文件描述符
 70             if(dup_flag == 1){
 71                 fd = open(dup_file,O_WRONLY|O_CREAT|O_TRUNC);
 72             }
 73             if(dup_flag == 2){
 74                 fd = open(dup_file,O_WRONLY|O_CREAT|O_APPEND);
 75             }
 76             dup2(fd,1);
 77             //    int execvp(const char *file, char *const argv[]);
 78             if(execvp(s[0],s)<0){
 79                 perror("");
 80             }
 81             exit(0);
 82         }
 83         wait(NULL);//父进程等待子进程的推出,防止产生僵尸进程
 84     }
 85     return 0;
 86 }  

猜你喜欢

转载自blog.csdn.net/boke_fengwei/article/details/89206003
今日推荐