【Linux】模拟实现shell

实现一个shell,需要循环以下过程:

  1. 获取命令行
  2. 解析命令行
  3. 建立一个子进程(fork)
  4. 替换子进程(execvp)
  5. 父进程等待子进程退出

具体代码如下:

// makefile
minishell:mini_shell.cc
	g++ mini_shell.cc -o mini_shell
.PHONY:clean
clean:
rm -f mini_shell mini_shell.cc

// mini_shell.cc
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define NUM 32

using namespace std;

int main()
{
	char buff[1024] = {0};
	for(;;)
	{	
		string commond;
		string tips = "[xxx@localhost yyy1# ";
		cout << tips;
		fgets(buff, sizeof(buff)-1, stdin);
		buff[strlen(buff)-1] = 0;
		
		char *argv[NUM];
		argv[0] = strtok(buff, " ");
		int i = 0;
		while(argv[i] !=NULL)
		{	
			i++;
			argv[i] = strtok(NULL, " ");
		}
		pid_t id = fork();
		if(id == 0)
		{	
			cout <<" child  running ..." << endl;
			execvp(argv[0], argv);
			exit(123);			
		}
		else
		{
			int status = 0;
			waitpid(id, &status, 0);
			cout << "Exit Code: " << WEXITSTATUS(status) << endl;
		}
	}
	return 0;
}

你可能感兴趣的:(Linux)