當我們在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);
}