写一个简单的shell命令解释器
2017-02-25 14:11
465 查看
/************************************************************************* # > File Name: myshell.c # Author: HuoZG # mail:248786797@qq.com # Created Time: Thu 23 Feb 2017 05:23:22 AM PST ************************************************************************/ #include<stdio.h> #include<ctype.h> // isspace() #include<stdlib.h> // exit() fflush(); #include<sys/wait.h> // waitpid() #include<unistd.h> // execvp // 需要 argv 和 命令 不需要 int main() { char buf[128]; // save input while(1) { char path[100]; gethostname(path, sizeof(path)); printf("[test@%s ~]$", path); fflush(stdout); ssize_t _s = read(0, buf, sizeof(buf)-1); if(_s >0) {// read sucess buf[_s-1] = '\0'; } else {// read failed printf("read!\n"); return 1; } char* myargv[32];// get command myargv[0] = buf; int index = 1; char* start = buf; while(*start) { if(isspace(*start)) { *start = '\0'; start++; myargv[index] = start; index++; } else { start++; } } myargv[index] = NULL; pid_t id = fork(); if(id < 0 ) { printf("create failed\n"); return 2; } else if(id == 0) {//child execvp(myargv[0], myargv); printf("command not found\n"); return 3; } else {// father int status = 0; ssize_t ret = waitpid(id, &status, 0); if(ret > 0 && WIFEXITED(status)) { //printf("wait sucess ;status:%d \n", WEXITSTATUS(status)); } else { perror("waitpid"); } } } return 0; }
目前只可以实现一些基本的命令。因为还在学习,只写一个最最最原始的。
相关文章推荐
- [开源项目]Shell4Win,一个在Windows下执行shell命令的解释器
- shell跑一个PHP脚本的简单命令
- shell简介:shell是一个命令解释器
- 编写自己的shell解析器(一)一个简单的循环命令输入和历史打印
- linux中新增一个shell命令最简单的方法
- 一个重启Tomcat的简单shell命令
- 编写简单的网络版shell命令解释器
- 一个简单的shell脚本程序(运用expr命令)
- 初学shell,为了练习sed,写了个简单的批量修改文件名的脚本,后来执行时发现系统竟然自带有一个rename命令,顺便也记下了
- Tinyshell: 一个简易的shell命令解释器
- linux入门:编写一个简单的shell(仅支持部分ls,ps命令)
- 自编简单的shell命令解释器要求及代码
- 一个重启Tomcat的简单shell命令
- 一个通用的调用shell命令及打印退出状态的C语言实现
- 自己动手写一个简单的Shell之二:运行程序
- 又学到了一个shell命令
- 自己动手写一个简单的Shell之四:流程控制
- 自己动手写一个简单的Shell之三:命令行解析
- 将moc输出加入到link命令里 一个简单方法
- 实现一个简单的ls命令