#include <unistd.h>
#include <string>
#include <errno.h>
#include <string.h>
#include <vector>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
void split(const std::string & command,
std::vector<std::string> * parse)
{
int length = command.size();
std::string temp;
size_t begin = 0;
while(begin <= length)
{
auto pos = command.find(' ', begin);
if(pos != std::string::npos)
{
temp = command.substr(begin, pos - begin);
begin = pos + 1;
}
else
{
temp = command.substr(begin);
begin = length + 1;
}
if(temp.size() > 0)
{
parse->push_back(temp);
temp.clear();
}
}
}
int main()
{
for(;;)
{
std::string command;
std::getline(std::cin, command);
std::vector<std::string> parse;
split(command, &parse);
pid_t pid = fork();
if(pid < 0)
{
perror("fork error");
return 1;
}
else if(pid == 0)
{
char * argv[20];
int i = 0;
for(auto & it : parse)
{
argv[i++] = const_cast<char *>(it.c_str());
}
argv[i] = NULL;
execvp(parse[0].c_str(), argv);
return 1;
}
else
{
int status = 0;
waitpid(pid, &status, 0);
// if(WIFEXITED(status))
// {
// std::cout << WEXITSTATUS(status) <<std::endl;
// }
}
}
return 0;
}
实现一个简单的shell
最新推荐文章于 2024-08-17 17:10:39 发布