[Linux] Simulate shell implementation: command line interpreter

Step-by-step thinking analysis:

1. Capture user keyboard input
Use functions such as scanf, gets, etc. to get user input information

2. Parse the input information-get the command name and operating parameters.
Parse the upper input information obtained, ignore all spaces, carriage returns, tabs, etc., and only care about the input string.
If you enter [ls -a -l ], what we need to get is the three key information "ls" "-a"" -l"

3. Create a child process, and replace the program with the command name for the child process (let the child process execute the command)
use fork() to create the child process, and then use the program replacement function (execvp, etc.) in the child process to replace the program. Pass the obtained information such as ls, -a, -l to the program replacement function, and let the child process perform related functions.

4. The process waits and waits for the child process to exit to prevent the appearance of zombie processes.
Use wait (NULL) to wait for any child process to exit to prevent zombie processes from appearing and cause resource leakage.

Complete code:

#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
 #include<ctype.h>

 int main()
 {
    
    
	   while (1)
		   {
    
    
		     printf("dev用户输入:");
		     fflush(stdout);
		     char cmd[1024] = {
    
     0 };
	         fgets(cmd, 1023, stdin);//获取键盘输入的信息
		     cmd[strlen(cmd) - 1] = '\0';
		     printf("cmd:[%s]\n", cmd);
		
			 char* ptr = cmd;
		     char* arg[32] = {
    
     NULL };
		     int my_argc = 0;
		     //解析获取到的信息--得到命令名称和运行参数
		     while (*ptr != '\0')
		     {
    
    
		       if (!isspace(*ptr))
				       {
    
    
				         arg[my_argc] = ptr;
				         my_argc++;

							while (*ptr != '\0' && !isspace(*ptr))
					         {
    
    
					           ptr++;
					         }

					   }
				* ptr = '\0';
	         
			 }
	          ptr++;
	        }
		arg[my_argc] = NULL;  
		pid_t pid = fork();
	  
			//创建子进程--进行程序替换
		    if (pid < 0)
		    {
    
    
		       perror("fork error:");
		       continue;
		    }
		   else if (pid == 0) 
			   {
    
    
			   //程序替换
		         execvp(arg[0], arg);
		         exit(-1);
			   }
	      wait(NULL);

	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43962381/article/details/115141007