1.函数功能:
实现Linux下的基本命令,平替系统的minishell。在这里需要注意,ll 和cd 因为cd属于外部命令,意思是在系统下cd 的命令的路径不在linux下,(在/bin/下)。而ll 是“ls -alhF”的别称,在linux下也不能识别,所以要将 ll换成 ls -alhF 。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/wait.h>
void show_prort()
{
char path[512]={0};
getcwd(path,sizeof(path));
printf("linux@ubuntu:%s$",path);
fflush(stdout);
}
int main(int argc, char *argv[])
{
int flag = 1;
while(flag)
{
show_prort();
char cmd[512]={0};
//fgets(cmd,sizeof(cmd),stdin);
read(0,cmd,sizeof(cmd));
cmd[strlen(cmd)-1]='\0';
if(strlen(cmd)==0) //cmd ==NULL
{
continue;
}
char *arg[10]={NULL};
arg[0]=strtok(cmd," ");
arg[1]=strtok(NULL," ");
arg[2]=strtok(NULL," ");
arg[3]=strtok(NULL," ");
arg[4]=strtok(NULL," ");
if(0 == strcmp(arg[0],"cd"))
{
if(NULL == arg[1])
{
chdir("/home/linux");
}
else
{
chdir(arg[1]);
}
continue;
}
if(0 == strcmp(arg[0],"quit"))
{
flag = 0 ;
continue;
}
pid_t pid = fork();
if(pid>0)
{
wait(NULL);
}
else if (0 == pid)
{
if(0==strcmp(arg[0],"ll")) // ll ll /home
{
if(NULL == arg[1])
{
arg[0]="ls";
arg[1]="-alhF";
}
else
{
arg[0]="ls";
arg[2]="-alhF";
}
}
execvp(arg[0],arg);
exit(1);
}
else
{
perror("fork");
exit(1);
}
}
return 0;
}