各位看官们,大家好,上一回中咱们说的是字符串初始化的例子,这一回咱们说的例子是:DIY shell。闲话休提,言归正转。让我们一起talk C栗子吧!
看官们,我们每天都在使用shell,而且似乎已经离不开它了。这是前辈们留给我们的好东东。今天我们介绍如何DIY一个shell,算是向前辈的致敬吧。
我们DIY的思路如下:
- 1.输入一个类似$的字符,提示用户向终端中输入内容;
- 2.从终端中读取用户输入的命令;
- 3.判断用户输入的命令,并且执行相应的命令;
- 4.重复步骤1到3,直到用户输入exit命令时,结束程序,退出shell。
下面是我写的shell程序的简单框架,请大家参考:
int main(int argc, char *argv[])
{
char buf[BUF_SIZE];
int res = 1;
int flag = 1;
int index = 0;
while(flag) // do this untial input exit commond
{
printf("|->");
if(NULL == fgets(buf,BUF_SIZE,stdin)) // get the input
return 0;
index = sizeof(input)/sizeof(input_type);
while(index-- > 0)
{
res = strncmp(buf,input[index].str,input[index].size); // find the commond
if(res == 0)
{
switch(index)
{
case 0: // exec exit commond
flag = 0;
break;
case 1: // exec cd commond
cds(buf);
break;
case 2: // exec ls commond
lss(buf);
break;
default:
printf("can 's \n");
break;
}
index = -1; // if find the commond, stop finding
}
}
if(index == -1)
printf("can't find commond: %s ",buf);
}
return 0;
}
程序中的cd和ls函数还没有完全实现。此外,这只是一个简单的程序框架,很多shell的功能都没有实现。这些内容,我们会在后面的章节中介绍并且实现。
看官们,正文中就不写代码了,详细的代码放到了我的资源中,大家可以点击这里下载使用。下面是程序的运行结果,请大家参考。在程序中我们使用了“|->”代码shell中的$,虽然形式不同,但是目的都是为了提示用户输入命令。
|->abc //abc is not a commond
can't find commond: abc
|->cd // exec the cd commond
cd running
|->ls // exec the cd commond
ls running
|->exit // exit the shell program
各位看官,关于DIY shell的例子咱们就说到这里。欲知后面还有什么例子,且听下回分解。