当我们在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);
}