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中编写的代码。
由于初学,导致在输出重定向时出了点问题,文件创建好后,系统却显示无这个文件,但是文件确实存在,关于此问题我查了很多的资料却无能为力,如果有看到的大神,请在下方评论不吝赐教,感激不尽。
阅读全文
0 0
- my_shell的简单实现
- my_shell
- 用realine库完善你的my_shell
- my_shell 编写
- my_shell.c
- 杀毒软件的简单实现的简单实现
- 杀毒软件的简单实现
- 俄罗斯方块的简单实现
- 简单文件系统的实现
- 杀毒软件的简单实现
- 杀毒软件的简单实现
- strstr()的简单实现
- printf 的简单实现
- 简单文件系统的实现
- 简单的ajax实现
- 简单的时钟实现
- ICollection的简单实现
- P2P的简单实现
- 区块链开发专题(数字货币如何实现交易支付)
- 收集EVA日志和配置信息
- HotSpot虚拟机对象的创建、存储和定位
- 考研数学笔记 16~20
- 数据仓库A
- my_shell的简单实现
- USASO Section1.1Your Ride Is Here[其他]
- 整数排序
- Excel合并多个工作表(Sheet)到一个Sheet中脚本
- 饥饿与活锁
- 深入理解javascript原型和闭包(3)——prototype原型
- Brocade HP SAN 交换机产品对应表
- python 命令行版todolist
- 内存溢出和内存泄露分析