資源簡介
基本功能:
1.基本的內部命令。如:cd, ls, pwd 等;
2.能處理后臺程序(不需要wait)
3.具有管道和重定向功能。如輸入:who | wc -l 進行測試;
4.可以處理多條命令,以';'分隔, 濾掉無效的空格、tab符等;
代碼片段和文件信息
////////////////////////////////////////////////////////////////////
/*******************************************************************
MyShell?1.0?Copyright?@?fc?2011
功能說明:
1.基本的內部命令。如:cd?ls?pwd?等;
2.能處理后臺程序(不需要wait)
3.具有管道和重定向功能。如輸入:who?|?wc?-l?進行測試;
4.可以處理多條命令,以‘;‘分隔?濾掉無效的空格、tab符等;
*******************************************************************/
////////////////////////////////////////////////////////////////////
#include?
#include?
#include?
#include?
#include?
#include?
#include?
//子函數聲明?
char?*get_input();??????????????????//獲取用戶的輸入
int??count_command(char?*input);????//統計命令數量
char?**get_command(char?*input);????//分離出每條命令?
int??count_pipe(char?*command);?????//統計管道數量?
int??do_pipe(char?*command);????????//管道處理
int??redirect(char?*command);???????//重定向處理
int??count_argv(char?*command); ????//統計參數個數?
char?**get_argv(char?*command);?????//分離出參數
char?*get_com_path(char?*command);??//獲得命令路徑?
//主程序?
int?main()?
{
????int??i?num;
????char?*input?**command;
????//清屏并顯示版本信息
????system(“clear“);
????printf(“*********************************\n“);
????printf(“?MyShell?1.0?Copyright?@?fc?2011\n“);
????printf(“*********************************\n“);
????while(1)
????{??????
????????//顯示當前路徑
printf(“%s:$?“?getcwd(NULL0));
//獲取用戶的輸入
????????input=get_input();
if(input==NULL)?continue;
//統計命令數量,以‘;‘分隔
????????num=count_command(input);
????????if(num==0)?continue;
//分離出每條命令?
command=get_command(input);
//處理每條命令?
for(i=0;?i { ????
?? ????//檢查命令中是否有管道符號
????if(count_pipe(command[i]))?
????????????????do_pipe(command[i]);
????else?????
????????????????redirect(command[i]);
}
//釋放申請的內存空間
for(i=0;?i ????free(command[i]);
free(command);
free(input);
????}
????return?0;
}
//獲取用戶的輸入
char?*get_input()?
{
????int?i;
????char?*input;
????
????if((input=(char?*)malloc(100*sizeof(char)))==0)
????{
????????perror(“malloc“);
return?NULL;
????}
????for(i=0;?i<100;?i++)
????{
????????input[i]=getchar();
????????
????????if(input[i]==‘\n‘)
????????{
????????????input[i]=‘\0‘;
????????????break;
????????}
????}
????????????
????//輸入的內容過長?
????if(i==100)
????{
printf(“input?too?long!\n“);
return?NULL;
????}
????return?input;
}
//統計命令數量
int?count_command(char?*input)
{
????int?i?num=0;
????int?len=strlen(input);
????for(i=0;?i ????????if(input[i]!=‘?‘&&input[i]!=‘ ‘)
????break;
????//輸入中有語法錯誤?
????if(input[i]==‘;‘)
????{
printf(“syntax?error!\n“);
return?0;
????}
????//輸入中只有空格或TAB
????if(i==len) return?0;
????for(i=0;?i ????{
if(input[i]==‘;‘)
{
????for(i++;?i ????????????????if(input[i]!=‘?‘&&input[i]!=‘ ‘)
????break;
???????????
????????????//輸入中有語法錯誤??
????????????if(input[i]==‘;‘)
????{
printf(“syntax?error!\n“);
return?0;
????}
????else?num++;
????????}
????}
????return?++num;
}??
//分離出每條命令
char?**get_command(char?*input)
{
????char?**command;
????int?i?j?
- 上一篇:C語言程序設計藥房藥品管理系統
- 下一篇:SHA1加密算法的c++實現
評論
共有 條評論