#include #include #include #include #include #include #include #include #include #include #include void checkFinish() { int status; pid_t pid = ::waitpid(-1, &status, WNOHANG); if (pid < 0 && errno != ECHILD) std::cerr << "Waitpid failed" << std::endl; else if (pid > 0) std::cout << "Process " << pid << " finished with status " << status << std::endl; } int main () { while (true) { std::string cmd; checkFinish(); std::cout << "Enter cmd : "; std::getline(std::cin, cmd); if (cmd.empty()) { checkFinish(); continue; } int pid; pid=::fork(); if (pid < 0) { // error std::cerr << "fork() failed" << std::endl; std::exit(EXIT_FAILURE); } else if (pid > 0) { // we are parent std::cout << "Started pid " << pid << std::endl; } else { // break up string std::istringstream iss(cmd); std::vector tokens; std::copy(std::istream_iterator(iss), std::istream_iterator(), std::back_inserter >(tokens)); std::vector raw; std::transform(tokens.begin(), tokens.end(), std::back_inserter >(raw), std::mem_fun_ref(&std::string::c_str)); raw.push_back(0); ::execvp(raw[0], const_cast(&raw[0])); std::cerr << "Exec failed" << std::endl; std::exit(EXIT_FAILURE); } checkFinish(); } }