c++ - Problems with execvp -
i'm trying create simple shell. here's i've done far:
#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()); (auto = 0; != 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; }
when run code , enter "ls" several times varying results:
[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]:
i have no idea why happens. suppose string splitting function far ideal. can please me fix it? also, if have tips please feel free give them. i'm noob , i'll appreciate help. thank you.
Comments
Post a Comment