?? shell1.c
字號:
#include <unistd.h>
char *command[10]; //exec調用時存放命令的字符串數組
char curp[255]; //存放當前目錄名的數組
char input[128]; //用于輸入的數組
main(int argc,char *argv[])
{
char *logout = "logout";
printf("start~\n");
getCommand(); //接受輸入
do(!strcmp(logout, command[0])){ //如果命令不是louout
getcwd(curp,255);
printf("PWD: %s \\",curp);
getCommand();
if(input[0] != 0) //如果輸入的不是空即不是直接回車的情況
{
exeCommand(); //執行命令
}
}while(strcmp(logout,&input));
}
//接受輸入
void getCommand()
{
gets(input);
lineParse(input, command, " ");
}
//將一個字符串以pstrTokser為分隔符拆分為字符串數組
void lineParse(char* pstrLine, char** pstrBuf, char* pstrToksep)
{
char* pstrToken;
int nBuf = 0;
pstrToken = strtok(pstrLine, pstrToksep);
while(pstrToken != NULL){
pstrBuf[nBuf++] = pstrToken;
pstrToken = strtok(NULL, pstrToksep);
}
pstrBuf[nBuf] = NULL;
}
void exeCommand()
{
char comPath[50] = "/bin/"; //組調用默認目錄為bin
if(strcmp("cd", command[0]) == 0){ //如果是cd命令
if(chdir(command[1]) == -1){
perror("change dir error");
}
}else{
int pid = fork(); //分出子進程,同時父進程等待
if(pid > 0){
wait((int*)0);
}else if(pid == 0){
strcat(&comPath, command[0]);
if(execv(comPath, command) == -1){ //執行exec調用組
if(strcmp("logout", command[0]) == 0){
perror("error\n");
}
}
exit(0);
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -