【发布时间】:2017-03-03 00:28:09
【问题描述】:
我正在创建一个 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设置的时间限制被删除了,那该怎么办?
感谢您的帮助。
【问题讨论】:
-
sleep几乎不使用 CPU 时间。它永远不会达到 3 秒的限制。 -
创建您自己的执行无限循环的程序,并执行该程序而不是
sleep。 -
好的,明白了。我需要一种方法来测量实时而不是 CPU 时间,我认为
setitimer会帮助我。谢谢 -
对于实时,
alarm()是等效的。