一起talk C栗子吧(第七十一回:C语言实例--DIY shell)


各位看官们,大家好,上一回中咱们说的是字符串初始化的例子,这一回咱们说的例子是: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的例子咱们就说到这里。欲知后面还有什么例子,且听下回分解。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

talk_8

真诚赞赏,手有余香

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值