实现一个简单的shell
2010-10-12 20:47
736 查看
#include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <signal.h> #include <unistd.h> #define MAXARGS 20 #define ARGLEN 100 main() { char *arglist[MAXARGS+1]; int numargs; char argbuf[ARGLEN]; char *makestring(); numargs=0; while(numargs<MAXARGS) { printf("Arg[%d]?",numargs); if(fgets(argbuf,ARGLEN,stdin)&&*argbuf!='/n') { arglist[numargs++]=makestring(argbuf); } else { if(numargs>0) { arglist[numargs]=NULL; execute(arglist); //zhixing numargs=0; } } } } execute(char *arglist[]) { int pid,exitstatus; pid=fork(); switch(pid) { case -1: perror("fork failed!"); exit(1); case 0: execvp(arglist[0],arglist); perror("execvp failed!"); exit(1); default: while(wait(&exitstatus)!=pid) ; printf("child exit with status %d,%d/n",exitstatus>>8,exitstatus&0377); } } char *makestring(char *buf) { char *cp,*malloc(); buf[strlen(buf)-1]='/0'; cp=malloc(strlen(buf)+1); if(cp==NULL) { fprintf(stderr,"no memory/n"); exit(1); } strcpy(cp,buf); return cp; }
这是来自unix/linux编程实践教程上的例子。
除了linux的系统调用,值得注意的是还有一些细节问题。
比如对于fgets()函数接受的字符串的处理。
char *fgets(char *s, int size, FILE *stream);
fgets() reads in at most one less than size characters from stream and
stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer.
A '/0' is stored after the last character in the buffer.
fgets 函数,从数据流读取比size少1个字符,把他们存储到s指向的缓冲区。如果遇到EOF或者换行,则
停止。如果是换行符,换行符也被存储在缓冲区。'/0'被存储在缓冲区的末尾.
所以在过程中要去掉击键产生的'/n',通过makestring(char *buf)函数。
相关文章推荐
- shell实现一个简单的计算器功能小脚本
- shell实现一个简单进度条
- 一个简单的wifi开关shell脚本实现
- Clojure:在REPL上实现一个简单的shell(二)
- 用c语言的实现一个简单的交互式shell
- Clojure:在REPL上实现一个简单的shell(三)
- Clojure:在REPL上实现一个简单的shell(一)
- 【C语言】实现一个简单SHELL应用
- Linux编程实现一个简单的Shell
- 【Linux】实现一个简单的shell
- 一个简单地Shell-like 的实现
- 操作系统上机——实现一个简单的shell
- 实现一个简单shell(支持重定向)
- C语言 实现一个简单的Shell (支持管道和"cd")
- Linux.实现一个简单的shell
- Linux下实现一个简单进度条和shell脚本实现彩色进度条
- 用Qt实现一个简单的shell (Qt5+V8)
- 一个简单的shell脚本-----实现虚拟机实验环境的简单配置
- 关于一个简单的shell的实现
- 利用linux下的c语言编程来简单的实现一个shell功能实现!