简体   繁体   中英

Is it possible to have millisecond precision with setrlimit in c

As the title suggests i need to know if there is some way to have less then second precision with the setrlimit RLIMIT_CPU ?

struct rlimit cpulimit;
cpulimit.rlim_cur = 5; // 5 seconds SIGXCPU
cpulimit.rlim_max = 5; // 5 seconds SIGKILL

( I know that on a typical system a program may take on ~10ms at a time ) I do not even need it to be a millisecond precision. 100ms will do just fine.

So I am curious could it be something like this:

struct rlimit cpulimit;
cpulimit.rlim_cur = 3500; // 3.5 seconds SIGXCPU
cpulimit.rlim_max = 4500; // 4.5 seconds SIGKILL

I do not see the relevance in explaining the reason why I need this and how I use it. If it's needed I'll edit the question and the information.

Thanks in advance,

Ex

POSIX only allows for second precision in setrlimit . There might be operating specific extensions that you can use, but I'm not aware of any operating system with that. RLIMIT_CPU is a left over from the days of multi user systems at universities where you needed to limit the damage student could do with their attempts to learn programming. As such it's rarely polished, debugged and improved in modern systems.

From experience I know that accounting for CPU time and the enforcement of RLIMIT_CPU is horribly limited on different systems and you might not even get a SIGXCPU for a process after twice as much time as you've limited it to if you use short timeouts. So whatever problem you're solving, you probably want to rethink what you want to accomplish and do it differently.

If you really need to kill a process that has spent too much CPU time with millisecond precision the best you can do is to have a supervising process that probes the child process with getrusage(RUSAGE_CHILDREN) often enough and shoots it. But beware that the counters you get from getrusage are often probabilistic (sampled by a clock interrupt) and the reported CPU usage can be very far off from the real CPU usage, especially in the early stages of running a process (those counters may or may not be the same as the ones used for RLIMIT_CPU ).

Do you need to enforce the limit on potentially malicious programs, or just on cooperating ones? In the latter case just setting up a timer for the cputime clock to deliver a fatal signal should work.

To do this, call timer_create with a clock id of CLOCK_PROCESS_CPUTIME_ID and a sigevent structure reflecting the signal you want to receive, then timer_settime to set its timeout. If the signal is fatal by default you don't even need to install a handler for it. This would be done within the process whose execution time you want to limit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM