Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Jan 28th, 2013  |  syntax: C++  |  size: 1.67 KB  |  views: 208  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <string>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <iterator>
  5. #include <iostream>
  6. #include <sstream>
  7. #include <cstdlib>
  8. #include <cerrno>
  9. #include <unistd.h>
  10. #include <sys/types.h>
  11. #include <sys/wait.h>
  12.  
  13. void checkFinish()
  14. {
  15.   int status;
  16.   pid_t pid = ::waitpid(-1, &status, WNOHANG);
  17.   if (pid < 0 && errno != ECHILD)
  18.     std::cerr << "Waitpid failed" << std::endl;
  19.   else if (pid > 0)
  20.     std::cout << "Process " << pid << " finished with status " << status << std::endl;
  21. }
  22.  
  23. int main ()
  24. {
  25.  
  26.   while (true)
  27.   {
  28.     std::string cmd;
  29.     checkFinish();
  30.     std::cout << "Enter cmd : ";
  31.     std::getline(std::cin, cmd);
  32.  
  33.     if (cmd.empty())
  34.     {
  35.       checkFinish();
  36.       continue;
  37.     }
  38.  
  39.     int pid;
  40.  
  41.     pid=::fork();
  42.  
  43.     if (pid < 0)
  44.     {
  45.       // error
  46.       std::cerr << "fork() failed" << std::endl;
  47.       std::exit(EXIT_FAILURE);
  48.     }
  49.     else if (pid > 0)
  50.     {
  51.       // we are parent
  52.       std::cout << "Started pid " << pid << std::endl;
  53.     }
  54.     else
  55.     {
  56.       // break up string
  57.       std::istringstream iss(cmd);
  58.       std::vector<std::string> tokens;
  59.       std::copy(std::istream_iterator<std::string>(iss),
  60.           std::istream_iterator<std::string>(),
  61.           std::back_inserter<std::vector<std::string> >(tokens));
  62.       std::vector<const char*> raw;
  63.       std::transform(tokens.begin(), tokens.end(),
  64.           std::back_inserter<std::vector<const char*> >(raw),
  65.           std::mem_fun_ref(&std::string::c_str));
  66.       raw.push_back(0);
  67.       ::execvp(raw[0], const_cast<char**>(&raw[0]));
  68.       std::cerr << "Exec failed" << std::endl;
  69.       std::exit(EXIT_FAILURE);
  70.     }
  71.     checkFinish();
  72.   }
  73. }
clone this paste RAW Paste Data