了setrlimit是不可靠? [英] setrlimit isn't reliable?

查看:487
本文介绍了了setrlimit是不可靠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 了setrlimit() 封顶时间的过程花费的金额。然而,它似乎并没有当我做一些操作,如的printf()

下面是一个测试程序说明问题:

Here is a test program illustrating the problem:

#include <sys/resource.h>
#include <stdio.h>

int main(void) {
    int i;
    struct rlimit limit;
    limit.rlim_cur = 3;
    limit.rlim_max = 3; // send SIGKILL after 3 seconds 
    setrlimit(RLIMIT_CPU, &limit);

    // doesn't get killed
    for(i=0; i<1000000; i++)
        printf("%d",i);

    return 0;
}

但是,如果我用不同的例行像天真更换斐波纳契for循环:

However if I replace the for loop with a different routine like naive fibonacci:

int fib(int n) {
    if(n<=1) return 1;
    return fib(n-1)+fib(n-2);
}
int main(void) {
    ...
    fib(100);
    ...
}

它完美。这里发生了什么?为了setrlimit()干脆不可靠?

推荐答案

CPU限制是对的 CPU 的秒,而不是经过时间的限制。 CPU秒数是基本上在CPU多少秒一直在使用,并不直接涉及到的经过时间。

The CPU limit is a limit on CPU seconds rather than elapsed time. CPU seconds is basically how many seconds the CPU has been in use and does not necessarily directly relate to the elapsed time.

当你做 FIB 呼叫,您捶了CPU,这样经过和CPU时间接近(大部分的处理时间是使用CPU用了)。这不是打印时,因为大部分时间没有在I / O所花的情况。

When you do the fib call, you hammer the CPU so that elapsed and CPU time are close (most of the process time is spent using the CPU). That's not the case when printing since most time there is spent in I/O.

所以,发生了什么你的具体情况是, RLIMIT 的设置,但你只是不使用你三秒的CPU时间前该过程完成。

So what's happening in your particular case is that the rlimit is set but you're just not using your three seconds of CPU time before the process finishes.

更改如下使信号在我的系统上提供:

Changing the main as follows causes the signal to be delivered on my system:

int main(void) {
    int i;
    struct rlimit limit;
    limit.rlim_cur = 3;
    limit.rlim_max = 3; // send SIGKILL after 3 seconds
    setrlimit(RLIMIT_CPU, &limit);

    while (1) {                      // Run "forever".
        for(i=0; i<100000; i++) {
            printf("%d\n",i);
        }
        fib(30);                     // some CPU-intensive work.
    }

    return 0;
}

时间在Linux下,你会看到:

When you time that under Linux, you see:

: (much looping).
52670
52671
52672
52673
52674
Killed

real   0m18.719s
user   0m0.944s
sys    0m2.416s

在这种情况下,花了近20秒经过时间,但CPU是使用了仅有336秒(用户+ SYS)。

In that case, it took almost 20 seconds of elapsed time but the CPU was in use for only 3.36 seconds (user + sys).

这篇关于了setrlimit是不可靠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆