linux内核原码实现(1)雏形

当我们在linux系统终端每输入一条命令,相应地shell就会解析出这些命令,这个功能到底有多高大?让我们一起来实现吧。

第一,要先理解shell如何运行。

在终端输入一次命令,shell解析一次并输出dollar符,先来构造框架。


这个shell文件下应该有以下文档,如图:

第二,实现。

具体实现:

头文件

  2

#define    CMD_STR     3//"mybash.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <signal.h>


#define    RUNING      1
#define    LINE_MAX    256
#define    PATH_MAX    256


#define    CD          1
#define    EXIT      0
#define    RUN_STR     4



简单实现下:

//mybash.c
#include "mybash.h"


void printinfo();
int  get_cmd(char * buff);
void do_run(int cmd,char* name);


int main()
{
    int flg = RUNING;


    while( flg )
    {
        char buff[LINE_MAX] = {0};
        
        printinfo();


        fgets(buff,LINE_MAX,stdin);
        buff[strlen(buff)-1] = 0;


        if ( buff[0] == 0 )
        {
            continue;
        }
        int res = get_cmd(buff);


        switch( res )
        {
            case CD :
                break;


            case EXIT :
                exit(0);
                break;


            case  CMD_STR :
            case  RUN_STR :
                do_run(res,buff);
                break;
        }
    }
}


/*****************************
 *
 *
 * **************************/
void printinfo()
{
    printf("[stu @ localhost ~]$");
    fflush(stdout);
}


int  get_cmd(char * buff)
{
    if ( strncmp(buff,"cd",2) == 0 )
    {
        return CD;
    }
    else if ( strncmp(buff,"exit",4) == 0 )
    {
        return EXIT;
    }
    else if ( strncmp(buff,"./",2) == 0 || strncmp(buff,"/",1) == 0 )
    {
        return RUN_STR;
    }




    return CMD_STR;
}


void do_run(int cmd,char* name)
{
    pid_t pid = fork();
    assert( pid != -1 );


    if ( pid == 0 )
    {
        char path[PATH_MAX] = {0};
        
        if ( cmd == CMD_STR )
        {
            strcpy(path,"/bin/");
            strcat(path,name);
        }
        else if ( cmd == RUN_STR)
        {
            strcpy(path,name);
        }
     
        execl(path,name,(char*)0);
        printf("mybash: %s not find!\n",path);
        exit(0);
    }


    wait(NULL);
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值