您的位置:首页 > 运维架构 > Shell

实现一个简单的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)函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: