C ++ CPU time limit for processing

I have this code:

pid_t vPid=fork(); 
    int vStat;   
    case -1: perror("fork");
    case 0:
      //proces fiu
      system("make clean");
          //limit on data
          struct rlimit vLimD;
          vLimD.rlim_cur = 10000000;//10Mb 
          vLimD.rlim_max =  10000000; //10Mb
      setrlimit(RLIMIT_DATA, &vLimD);
          //limit on cpu time
          struct rlimit vLimCPU;
          vLimCPU.rlim_cur = 10;//10 sec
          vLimCPU.rlim_max = 10;//10 sec
          cout<<"limits return "<<setrlimit(RLIMIT_CPU, &vLimCPU);
      else {exit(1);}


The process / var / code / p1 / p1 runs for 40 seconds and I want to limit this process to only 10 seconds with a vLimitCPU(setrlimit)

, and after 10 seconds do something, but it does not print anything like "limit return value" (the first setrlimit

returns 0)


source to share

1 answer

The man page setrlimit(2)


Processor time limit in seconds. When a process reaches the soft limit, a SIGXCPU signal is sent. The default action for this signal is to terminate the process. However, the signal can be and the handler can return control to the main program.

You are probably not getting any output because your output stream is not being cleaned up (output std::endl

to solve this problem). This signal can be killed by the signal before it can flush its output buffers. It can also happen that the buffers do not survive in the first place execl()


A few more tips:

  • Then you have to implement a signal handler and your program will be from there. Implement it to see if the signal is being caught.

  • Note that you will also need a fallback solution for the case when the process ends unexpectedly before the processor time runs out.

  • Note also that if I am assuming this correctly, you also need to consider the CPU time already used by your process when setting the limit.



All Articles