Advertisement
homer512

time limit

Jan 4th, 2017
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #if defined(WIN32) && ! defined(USE_GENERIC)
  2. # define USE_GENERIC
  3. #endif
  4.  
  5. #ifdef USE_GENERIC
  6. # include <thread>
  7.   // using std::thread, std::this_thread
  8. # include <chrono>
  9.   // using std::chrono::seconds
  10. # include <csignal>
  11.   // using std::raise, SIGABRT, SIGXCPU
  12. #else
  13. # include <sys/time.h>
  14. # include <sys/resource.h>
  15.   // using setrlimit
  16. # include <algorithm>
  17.   // using std::min
  18. # include <system_error>
  19.   // using std::system_error, std::system_category
  20. # include <cerrno>
  21.   // using errno
  22. #endif
  23.  
  24.  
  25. namespace ext {
  26.  
  27. #ifdef USE_GENERIC
  28.  
  29.   namespace {
  30.     void sleeper_thread(int seconds)
  31.     {
  32.       std::this_thread::sleep_for(std::chrono::seconds(seconds));
  33.       int signal;
  34. #    ifdef SIGXCPU
  35.       signal = SIGXCPU;
  36. #    else
  37.       signal = SIGABRT;
  38. #    endif
  39.       std::raise(signal);
  40.     }
  41.   }
  42.  
  43.   void limit_time(int seconds)
  44.   {
  45.     std::thread(sleeper_thread, seconds).detach();
  46.   }
  47.  
  48. #else
  49.  
  50.   void limit_time(int seconds)
  51.   {
  52.     rlimit limit;
  53.     if(getrlimit(RLIMIT_CPU, &limit))
  54.       goto err;
  55.     if(limit.rlim_max > static_cast<rlim_t>(seconds))
  56.       limit.rlim_max = seconds;
  57.     limit.rlim_cur = limit.rlim_max;
  58.     if(setrlimit(RLIMIT_CPU, &limit))
  59.       goto err;
  60.     return;
  61.   err:
  62.     throw std::system_error(errno, std::system_category(), "rlimit");
  63.   }
  64.  
  65. #endif
  66.  
  67. }
  68.  
  69. int main()
  70. {
  71.   ext::limit_time(10);
  72.  
  73.   int j = 1;
  74.   for(unsigned i = 10; i >= 0; --i) // accidental infinite loop
  75.     j *= 2;
  76.   return j;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement