📄 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 + -