红联Linux门户
Linux帮助

关于 getrlimit and setrlimit: Resource Limits 的问题

发布时间:2010-09-15 19:57:23来源:红联作者:qiao16996814
#include
#include
#include
int main ()
{
struct rlimit rl;
/* Obtain the current limits. */
getrlimit (RLIMIT_CPU, &rl);
/* Set a CPU limit of 1 second. */
rl.rlim_cur = 1;
setrlimit (RLIMIT_CPU, &rl);
/* Do busy work. */
while (1);
return 0;
}

==> 上述程序,设置了一个软限制,并且指定CPU 运行时间1s后就发送一个SIGXCPU信号,来终止该程序。上述程序倒是正常,运行后,会看到CPU time limit exceeded字样。

#include
#include
#include
int main ()
{
int i = 0;
struct rlimit rl;
/* Obtain the current limits. */
getrlimit (RLIMIT_CPU, &rl);
/* Set a CPU limit of 1 second. */
rl.rlim_cur = 1;
setrlimit (RLIMIT_CPU, &rl);
/* Do busy work. */
while (1)
{
i++;
printf("%d seconds\n",i);
sleep(1);
}
return 0;
}

==> 本意是想测试,是不是真的是1s终止程序,结果发现程序不会停止。
文章评论

共有 3 条评论

  1. deepwhite 于 2010-09-16 12:05:23发表:

    我也只是猜想,不敢确认,呵呵。没用过 resouce limit 。

  2. qiao16996814 于 2010-09-16 10:51:30发表:

    谢谢您的回复!
    从您的程式中似乎有些理解了。

  3. deepwhite 于 2010-09-16 09:44:40发表:

    没太具体看,但是个人感觉,这个 limit 限制的应该是空闲的 CPU ,换句话说,只有当 CPU 空闲的时候,这个 limit 才有限制。
    而如果一个CPU的状态为 busy (正在干活),这个时候随便将其进行的任务终止是不应该的。

    从下面的这段代码及其运行结果中可以看出,只有在 CPU 空闲的时候,这个 limit 才起了作用。

    [code]
    #include
    #include
    #include
    #include
    #include
    #include

    #define oops(ch) {perror(ch); return -1;}

    void sigxcpu_handler(int signum)
    {
    printf ("SIGXCPU Received!\n");
    /* exit(1); */
    }

    void sigkill_handler(int signum)
    {
    printf ("SIGKILL received!\n");
    exit(1);
    }
    int main ()
    {

    int i = 0;
    int ret = 0;
    struct rlimit rl;

    signal(SIGXCPU, sigxcpu_handler);
    signal(SIGKILL, sigkill_handler);

    /* Obtain the current limits. */
    ret = getrlimit (RLIMIT_CPU, &rl);
    if (ret == -1) {
    oops("Failed to getrlimit!\n");
    }
    /* Set a CPU limit of 1 second. */
    rl.rlim_cur = 1;
    rl.rlim_max = 3;
    ret = setrlimit (RLIMIT_CPU, &rl);
    if (ret == -1) {
    oops("Failed to set limit.\n");
    }
    /* Do busy work. */
    while (1)
    {
    i++;
    printf("%d seconds\n",i);
    if (i == 10) {
    break;
    }
    sleep(1);
    }
    while (1)
    ;
    return 0;
    }

    /*
    * Editor modelines
    *
    * Local Variables:
    * c-basic-offset: 4
    * tab-width: 4
    * indent-tabs-mode: nil
    * End:
    *
    * ex: set shiftwidth=4 tabstop=4 expandtab
    * :indentSize=4:tabSize=4:noTabs=true:
    */
    [/code]

    结果:
    [code]
    /tmp $ make test
    cc test.c -o test
    /tmp $ ./test
    Before -1
    After 3
    1 seconds
    2 seconds
    3 seconds
    4 seconds
    5 seconds
    6 seconds
    7 seconds
    8 seconds
    9 seconds
    10 seconds
    SIGXCPU Received!
    SIGXCPU Received!
    已杀死
    [/code]