为子进程设置时间限制

Set time limit to a child process

我正在创建一个 shell,但在创建我自己的 ulimit 函数时遇到了问题:我想限制一个过程的时间,我为此使用了 setrlimit .但似乎当我调用 execvp 时,时间限制有点被删除了。

在这个示例代码中,当我让 while(1) 时,子进程收到 SIGXCPU 并在 3 秒后被杀死。但是当我改为 execvp(...) 时,它永远不会被杀死。

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>

int main(void) {
    struct rlimit t = {3, 8};

    uint32_t child_pid = fork();

    // father
    if (child_pid != 0) {
        waitpid(child_pid, NULL, 0);

    // child
    } else {
        setrlimit(RLIMIT_CPU, &t);
        char* s[3];
        s[0] = "sleep";
        s[1] = "1000";
        s[2] = NULL;

        /* while(1); */
        execvp(*s, s);
    }
}

如果我是对的,我用setrlimit设置的时限被抹掉了,那怎么办呢?

感谢您的帮助。

I want to limit the time of a process, and I use setrlimit for it. But it seems that when I call execvp then, the time limit is kind of erased.

这将违反 exec-family 函数的 POSIX 规范,并且违反 setrlimit() 的 Linux 文档。两者都说资源限制在 exec 中保留。 Linux 声称其实现也与 BSD 一致。换句话说,您的建议极不可能准确描述正在发生的事情。

基本上,您没有测试您认为正在测试的东西。您设置了 CPU 时间的资源限制,但您正在测试的进程是 sleep,出于所有意图和目的 不消耗任何 CPU时间。当然,由于您设置的资源限制,它永远不会收到 SIGXCPU

CPU 时间与墙上时间完全不同,后者不是托管资源。如果您希望 child 在一定时间后接收信号,请使用 alarm() 函数(其 count-down 计时器也通过 exec 继承)。