#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/wait.h>
#include<pwd.h>//获取用户名
#define PATH "/home/stu/c215/mybin/"
#define MAX_ARG 10
void print_info()
{
//printf("\033[1;32mstu@stu-virtual-machine:\033[0m\033[1;34m~/c215/mybash$\033[0m ");
//fflush(stdout);
char* s="$";
//char* username="root";
int id=getuid();//得到当前进程用户的id
if(0 == id)
{
s="#";
}
struct passwd* pw=getpwuid(id);
if( NULL == pw)
{
printf("mybash>>$");
fflush(stdout);
return ;
}
char hostname[128]={0};
if( gethostname(hostname,128) == -1 )
{
printf("mybash>>$");
fflush(stdout);
return ;
}
char pwd_str[256] = {0};
if(NULL == getcwd(pwd_str,256) )
{
printf("mybash>>$");
fflush(stdout);
return ;
}
printf("\033[1;32m%s@%s\033[0m \033[1;34m%s%s\033[0m ",pw->pw_name,hostname,pwd_str,s);
}
char* get_cmd(char* p,char* myargv[])
{
if( p == NULL || myargv == NULL)
{
return NULL;
}
int i=0;
char* s=strtok( p ," ");
while(s != NULL)
{
myargv[i++] = s;
s = strtok(NULL, " ");//字符串分割函数第一个参数为需要分割的字符串,第二个参数为分割条件
}
return myargv[0];
}
void change_dirent(char* dir)
{
if(dir == NULL)
{
return ;
}
if( chdir(dir) == -1)//改变工作路径
{
perror("cd err");
}
}
int main()
{
while(1)
{
print_info();
char buff[128]={0};
fgets(buff,128,stdin);
buff[strlen(buff)-1]=0;
char* myargv[MAX_ARG]={0};
char* cmd=get_cmd(buff,myargv);
if( cmd == NULL)
{
continue;
}
else if(strcmp(cmd,"cd") == 0 )//字符串比较函数
{
change_dirent(myargv[1]);
}
else if ( strcmp(cmd,"exit") == 0 )
{
break;
}
else
{
pid_t pid =fork();
if( pid ==-1 )
{
printf("fork err\n");
continue;
}
if ( pid == 0 )
{
char cmdpath[128] ={0};
if(strncmp(cmd,"./",2) != 0 && strncmp(cmd,"/",1) != 0 )
{
strcpy(cmdpath,PATH);
strcat(cmdpath,cmd);
}
else
{
strcpy(cmdpath,cmd);
}
execv(cmdpath,myargv);
//execvp( cmd, myargv);//替换进程函数
perror("execvp err");//打印错误和原因函数
exit(0);
}
wait(NULL);
}
}
}
mybash
最新推荐文章于 2024-07-14 18:35:17 发布