一、解析
void parse(){
std::string line;
getline(std::cin, line);
int len = line.size(), i=0;
std::string tmp;
std::vector<std::string> tmp_vc;
while(i < line.size()){
if(line[i] == ' '){
i++;
continue;
}
if(line[i] == '|') {
vc.push_back(tmp_vc);
tmp = "";
i++;
continue;
}
int pos = line.find(' ', i); // 获取下一个空格的位置
tmp = line.substr(i, pos-i); // 截取字符串
tmp_vc.push_back(tmp);
i = pos;
}
vc.push_back(tmp_vc);
}
二、执行命令函数
void func(std::vector<std::string>& v){
char *arr[10];
pid_t pid;
pid = fork();
if(pid == -1){
std::cout << "fork error" << std::endl;
exit(1);
}else if(pid ==0){
for(int i=0; i<v.size(); ++i)
arr[i] = (char *)v[i].c_str();
arr[v.size()] = NULL;
execvp(arr[0], arr);
}else{
wait(NULL);
}
}
void execCommnd(){
for(int i=0; i<vc.size(); ++i){
func(vc[i]);
}
}
三、模拟shell
void getCurPwd(){
std::string s = get_current_dir_name();
int pos = s.rfind('/');
std::string tmp = s.substr(pos+1, s.length()-pos);
std::cout << tmp << "]# ";
}
void getIdname(){
struct passwd *pwd;
pwd = getpwuid(getuid());
std::cout << "[" <<pwd->pw_name << "@";
}
void getHostName(){
char buf_w[128];
int hostname = gethostname(buf_w, sizeof(buf_w));
std::cout << buf_w << " ";
}
void showMenu(){
getIdname();
getHostName();
getCurPwd();
}
四、完整代码
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <wait.h>
std::vector<std::vector<std::string>> vc;
void parse(){
std::string line;
getline(std::cin, line);
int len = line.size(), i=0;
std::string tmp;
std::vector<std::string> tmp_vc;
while(i < line.size()){
if(line[i] == ' '){
i++;
continue;
}
if(line[i] == '|') {
vc.push_back(tmp_vc);
tmp = "";
i++;
continue;
}
int pos = line.find(' ', i); // 获取下一个空格的位置
tmp = line.substr(i, pos-i); // 截取字符串
tmp_vc.push_back(tmp);
i = pos;
}
vc.push_back(tmp_vc);
}
void func(std::vector<std::string>& v){
char *arr[10];
pid_t pid;
pid = fork();
if(pid == -1){
std::cout << "fork error" << std::endl;
exit(1);
}else if(pid ==0){
for(int i=0; i<v.size(); ++i)
arr[i] = (char *)v[i].c_str();
arr[v.size()] = NULL;
execvp(arr[0], arr);
}else{
wait(NULL);
}
}
void execCommnd(){
for(int i=0; i<vc.size(); ++i){
func(vc[i]);
}
}
void getCurPwd(){
std::string s = get_current_dir_name();
int pos = s.rfind('/');
std::string tmp = s.substr(pos+1, s.length()-pos);
std::cout << tmp << "]# ";
}
void getIdname(){
struct passwd *pwd;
pwd = getpwuid(getuid());
std::cout << "[" <<pwd->pw_name << "@";
}
void getHostName(){
char buf_w[128];
int hostname = gethostname(buf_w, sizeof(buf_w));
std::cout << buf_w << " ";
}
void showMenu(){
getIdname();
getHostName();
getCurPwd();
}
void test(){
while(1){
showMenu();
parse();
execCommnd();
}
}
int main(int argc, char* argv[])
{
test();
return 0;
}
四、运行结果
到此这篇关于C++实现模拟shell命令行的文章就介绍到这了,更多相关C++ shell命令行内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!