yanqiufang 发表于 2018-8-28 06:08:49

linux下编写一个仿shell-momo就是辣么萌

#include   
#include
  
#include
  
#include
  
#include
  
#include
  
void prompt()
  
{
  
struct passwd * p1;
  
char username;
  
char hostname;
  
char pathname;
  
//获取用户名
  
p1=getpwuid(getuid());
  
//获取路径
  
getcwd(pathname,sizeof(pathname));
  
//获取主机名---返回0正确
  
if(gethostname(hostname,sizeof(hostname))==0)
  
{
  
    printf("",p1->pw_name,hostname,pathname);
  
}
  
else
  
{
  
    printf("",p1->pw_name,pathname);
  
}
  
if(geteuid()==0)
  
{
  
    printf("#");
  
}
  
else
  
{
  
    printf("$");
  
}
  
}
  
int main()
  
{
  
while(1)
  
{
  
    prompt();
  
    fflush(stdout);
  
    char buf;
  
    memset(buf,0,sizeof(buf));
  
    size_t size=read(0,buf,sizeof(buf)-1);
  

  
    if(size>0)
  
    {
  
      buf='\0';
  
    }
  
   // printf("%s\n",buf);
  
    char *p=buf;
  
    int i=0;
  
    char * my_argv={0};
  
    my_argv=p;
  
    while(*p!=0)
  
    {
  
      if(*p==' ')
  
      {
  
      *p='\0';
  
      ++p;
  
      my_argv[++i]=p;
  
      }
  
      else
  
      {
  
      ++p;
  
      }
  
    }
  
    pid_t id=fork();
  
    if(id==0)
  
    {
  
   if(strcmp(my_argv,"exit")==0)
  
      {
  
       exit(0);
  
      }
  
      if(strcmp(my_argv,"cd")==0)
  
      {
  
         exit(0);
  
      }
  
      else
  
      {
  
      execvp(my_argv,my_argv);
  
      }
  
    }
  
    else
  
    {
  
      pid_t ret=waitpid(id,NULL,0);
  
   if(strcmp(my_argv,"cd")==0)
  
       {
  
      chdir(my_argv);
  
       }
  
      if(strcmp(my_argv,"exit")==0)
  
      {
  
       exit(0);
  
      }
  
    }
  
}
  
return 0;
  
}


页: [1]
查看完整版本: linux下编写一个仿shell-momo就是辣么萌