如果是写作业到了这里,最好不要直接copy哦,仅供参考
可以处理简单的命令,还有cd
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<pwd.h>
int isExit=0; //是否终止程序
char username[100]; //当前用户名
char dir[200]; //当前所在路径
char dirname[100]; //当前所在路径文件夹
char hostname[100]; //当前主机名
//分割输入命令参数处理
void splitCommend(char* commend,char** array){
char cur[10];
int len = strlen(commend);
int i=0,j=0,k=0;
while(i < len){
while(commend[i]!=' ' && i<len){
cur[j] = commend[i];
i++;
j++;
if(commend[i] == ' ' || i==len){
cur[j]='\0';
j=0;
array[k] = (char*)malloc(100*sizeof(char));
strcpy(array[k],cur);
k++;
memset(cur,'\0',sizeof(cur));
break;
}
}
i++;
}
array[k] = 0;
}
//获取当前用户名
void getUsername(){
struct passwd *userInfo;
userInfo = getpwuid(getuid());
strcpy(username,userInfo->pw_name);
}
//获取当前主机名
void getHostName(){
gethostname(hostname,sizeof(hostname));
}
//获取当前工作路径
void getDir(){
char cur[100];
int i,j=0;
getcwd(dir,sizeof(dir));
if(strcmp(dir,"/root")==0){
strcpy(dirname,"~");
return;
}
for(i=0;i<strlen(dir);i++){
if(dir[i] == '/'){
j = 0;
continue;
}
cur[j]=dir[i];
j++;
}
cur[j]='\0';
if(strlen(cur)==0){
strcpy(cur,"/");
}
strcpy(dirname,cur);
}
//更改当前工作路径
void changePath(char **param){
char homepath[100]={0};
int i;
if(param[1]==NULL || strlen(param[1])==0 || param[2]!=NULL){
printf("The fotmat is [cd pathname].\n");
return;
}
if(param[1][0]=='~'){
if(strlen(param[1])==1){
param[1][0]='\0';
}
for(i=2;i<=strlen(param[1]);i++){
param[1][i-2] = param[1][i];
}
if(strcmp(username,"root")==0){
strcpy(homepath,"/root/");
strcat(homepath,param[1]);
if(chdir(homepath)==-1){
printf("The path is invalid.\n");
}
} else {
strcat(homepath,"/home/");
strcat(homepath,username);
strcat(homepath,"/");
strcat(homepath,param[1]);
if(chdir(homepath)==-1){
printf("The path is invalid.\n");
}
}
return;
}
if(chdir(param[1])==-1){
printf("The path is invalid.\n");
}
getDir();
}
//输出命令
void inputCommend(){
char commend[100];
char* param[100];
char path[10]={"/bin/"};
int p1,i=0;
char *envp[] = {NULL};
getUsername();
getHostName();
getDir();
printf("[%s@%s %s]",username,hostname,dirname);
fgets(commend,100,stdin);
commend[strlen(commend)-1]='\0';
splitCommend(commend,param);
if(strcmp(param[0],"exit")==0 || strcmp(param[0],"quit")==0){
isExit=1;
return;
}
if(strcmp(param[0],"cd")==0){
changePath(param);
return;
}
p1=fork();
if(p1==0){
if(execvp(param[0],param)==-1)
printf("Error Command.\n");
} else {
wait(NULL);
}
}
int main(int argc,char** argv){
while(isExit==0){
inputCommend();
}
}