my_shell的简单实现

来源:互联网 发布:卖家怎么加入淘宝直播 编辑:程序博客网 时间:2024/06/05 14:35

linux下用户与操作系统交流的平台叫做shell,shell的功能是解析输入的指令,然后到相应的文件中去查找指令并执行它。

这里我们简单的实现一下my_shell(功能不全)。


 1 #include <unistd.h>  2 #include <sys/types.h>  3 #include <sys/wait.h>  4 #include <stdio.h>  5 #include <string.h>  6 #include <sys/stat.h>  7 #include <fcntl.h>  8   9 int main() 10 { 11     do{ 12             char* _argv[32]; 13              char ins[1024]; 14             int count=0; 15             char* ptr=ins; 16             int fd=100; 17             printf("[wang@localhost 5_mon]# "); 18             fflush(stdout); 19             int s = read(0,ins,sizeof(ins)-1); 20             if(s>0){//解析命令 21             ins[s-1]=0; 22             _argv[0]=ins; 23             while((*ptr)!=0){
 24             if((*ptr)=='>'){//这里主要为了实现输出重定向 25                    if(*(ptr-1)==' ') 26                   count--; 27                   while(*(++ptr)==' '){} 28  29                   char* filename=""; 30                   filename=ptr; 31                   while(*(ptr)!=' '&&(*ptr)!=0){++ptr;} 32                   *ptr=0; 33                  fd= open(filename,O_CREAT,0664); 34                  dup2(1,fd); 35                  close(1); 36                   break; 37               } 38                if((*ptr)!=' '){ 39                       ++ptr; 40               } 41               else { 42                   *ptr=0; 43                   _argv[++count]=++ptr; 44               } 45             }} 46             _argv[++count]=NULL;
47             pid_t id = fork(); 48             if(id == 0){//子进程调用exec函数 49             execvp(_argv[0],_argv); 50             printf("\n"); 51               } 52             else{ 53              int ret= waitpid(id,NULL,WNOHANG); 54              if(ret>0) {//将关闭的标准输出重新打开 55              fflush(stdout); 56                  dup2(fd,1); 57              } 58             } 59     }while(1); 60     return 0; 61 }                                                              61,1          Bot

这是在linux vim中编写的代码。

由于初学,导致在输出重定向时出了点问题,文件创建好后,系统却显示无这个文件,但是文件确实存在,关于此问题我查了很多的资料却无能为力,如果有看到的大神,请在下方评论不吝赐教,感激不尽。


原创粉丝点击