124-Realize mybash written by yourself under Linux

Simulate bash under Linux to implement mybash written by yourself

Code first!

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>
#include<signal.h>
#include<unistd.h>
#include<sys/wait.h>
#include<pwd.h>

void printfinfo()
{
    
    
	char *s="$";
	int uid=getuid();
	if(uid==0)
	{
    
    
		s="#";
	}

	struct passwd*pd=getpwuid();
	if(pd==	NULL)
	{
    
    
		printf("mybash $");
		fflush(stdout);
		return ;
	}

	char host[128]={
    
    0};
	if(gethostname(host,128)==-1)
	{
    
    
		printf("mybash $");
		fflush(stdout);
		return ;
	}

	char path[256]={
    
    0};
	getcwd(path,256);

	printf("%s@%s:%s%S",pd->pw_name,host,path,s);
	fflush(stdout);
}


int main()
{
    
    
	while(1)
	{
    
    
		char buff[128]={
    
    0};//存放命令
		//printf("stu@stu-PC ~$");
		//fflush(stdout); //刷新缓冲区使printf输出的信息能及时打印到屏幕
		printfinfo();
		fgets(buff,128,stdin);//从键盘获取数据 结尾是'\n'
		buff[strlen(buff)-1]='\0';

		char *myargv[10]={
    
    0};
		int i=0;
		char *s=strtok(buff," ");//例如 cp a.c b.c
		while(s!=NULL)
		{
    
    
			myargv[i++]=s;
			s=strtok(NULL," ");
		}
		char *cmd=myargv[0];
		if(cmd==NULL)
		{
    
    
			continue;
		}
		if(strcmp(buff,"exit")==0)
		{
    
    
			break;
		}else if(strcmp(cmd,"cd")==0)
		{
    
    
			if(myargv[1]!=NULL)
			{
    
    
				if(chdir(myargv[1])==-1)
				{
    
    
					perror("cd error:");
				}
			}
			continue;
		}

		pid_t pid=fork():
			if(pid==-1)
			{
    
    
				continue;
			}
			if(pid==0)
			{
    
    
				execvp(cmd,myargv);
				perror("exec error");
				exit(0);
			}
			wait(NULL);
	}
}

Then compile and run, operation
Insert picture description here

Guess you like

Origin blog.csdn.net/LINZEYU666/article/details/111936699