实现一个shell,需要循环以下过程:
- 获取命令行
- 解析命令行
- 建立一个子进程(fork)
- 替换子进程(execvp)
- 父进程等待子进程退出
具体代码如下:
// 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 <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#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;
}