execvp的问题

时间:2014-01-31 15:34:39

标签: c++ shell execvp

我正在尝试创建一个简单的shell。这是我到目前为止所做的:

#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
#include <string>
#include <vector>
#include <sstream>

void execute(std::vector<char *> instructions)
{
    auto pid = fork();
    int status;

    if (pid < 0) {
        std::cout << "Fork error occured!" << std::endl;
        exit(1);
    } else if (pid == 0) {
        if(execvp(instructions[0], instructions.data()) < 0) {
            std::cout << "Command Not Found" << std::endl;
            exit(1);
        }
    } else {
        while (wait(&status) != pid);
    }
}

std::vector<char *>  splitter(std::string input)
{
    std::istringstream iss(input);
    std::vector<std::string> tokens{std::istream_iterator<std::string>{iss},
        std::istream_iterator<std::string>{}};
    std::vector<char *> instructions(tokens.size());
    for (auto i = 0; i != tokens.size(); ++i) {
        instructions[i] = &tokens[i][0];
    }
    return instructions;
}

int main()
{
    std::string input;

    while (1) {
        std::cout << "[cmd]:";
        getline(std::cin, input);
        if (input == "exit") exit(0);
        std::vector<char *> instructions = splitter(input);
        execute(instructions);
    }

    return 0;
}

当我运行代码并多次输入“ls”时,我会得到不同的结果:

[cmd]:ls
Assignment IV
[cmd]:ls
Command Not Found
[cmd]:ls
Assignment IV
[cmd]:ls
Assignment IV
[cmd]:ls
Command Not Found
[cmd]:pwd
/Users/diveafall/Library/Developer/Xcode/DerivedData/Assignment_IV-grxcoesjdabjvoenxkaprouhexuh/Build/Products/Debug
[cmd]:

我不知道为什么会这样。我想我的字符串拆分功能远非理想。你能帮我解决一下吗?此外,如果您有任何提示,请随时给他们。我是菜鸟,我会感激任何帮助。谢谢。

0 个答案:

没有答案