Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <vector>
- #include <algorithm>
- #include <iterator>
- #include <iostream>
- #include <sstream>
- #include <cstdlib>
- #include <cerrno>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- 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<std::string> tokens;
- std::copy(std::istream_iterator<std::string>(iss),
- std::istream_iterator<std::string>(),
- std::back_inserter<std::vector<std::string> >(tokens));
- std::vector<const char*> raw;
- std::transform(tokens.begin(), tokens.end(),
- std::back_inserter<std::vector<const char*> >(raw),
- std::mem_fun_ref(&std::string::c_str));
- raw.push_back(0);
- ::execvp(raw[0], const_cast<char**>(&raw[0]));
- std::cerr << "Exec failed" << std::endl;
- std::exit(EXIT_FAILURE);
- }
- checkFinish();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement