gpt4 book ai didi

c - 如何等待一个 child 直到它在 c/c++ 中达到 CPU 时间超时?

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:06 24 4
gpt4 key购买 nike

如何等待 child 直到它达到 CPU 超时?

我要 fork 一个进程并等待它退出。为了保护 fork 挂起,我想限制 fork 执行时间,但 CPU 时间不是实际时钟时间,因为最后一个时间可能因系统资源使用情况而异。

但是看起来 getrusage 和 times 在子进程退出之前不会更新子进程的 CPU 时间,所以下面的代码不起作用:

pid_t pid = fork();

if (pid == -1) {perror("Fork error: "); exit(EXIT_FAILURE); }

if (pid == 0)
{
/* loop working process here, should be substituted with exec() */
while (1)
{
for (int i = 0; i <1000000000 ;i++);
sleep(1);
}
_exit(0);
}

int exstat;

timespec sl; /* sleeps before timeout check */
sl.tv_sec = 0;
sl.tv_nsec = 1000000L;

struct tms tms;

double t = 0, lim = 10; /* 10 sec timeout */
double clk_tck = sysconf(_SC_CLK_TCK);

while (t < lim && !waitpid(pid, &exstat, WNOHANG))
{
nanosleep(&sl, NULL);
times(&tms);
t = (tms.tms_cutime + tms.tms_cstime) / clk_tck;
/* FAIL: t is always zero here */
}

if (t >= lim)
{
kill(pid, SIGKILL);
return 2; /* child timeouted */
}

int status = 0;
if (WIFEXITED(exstat)) status = WEXITSTATUS(exstat);

if (status) return 1; /* child failed */
return 0; /* child success */

有没有办法确定运行进程所花费的 CPU 时间(无需检查看起来非常不可移植的/proc)?

(顺便说一句,有没有办法在 child 退出时立即终止 wail-loop 而无需等待 nanospeep 周期?)

最佳答案

您可以更改更改 CPU limit child 的,如果超过这个限制就会被杀死。

if (pid == 0) 
{
struct rlimit cpu_lim = {10,10}; //limit to 10 seconds
if (setrlimit(RLIMIT_CPU , &cpu_lim) == -1) {
perror("setrlimit");
return;
}

...

使用这种方法,您无需检查父进程中的 CPU 使用率,只需等待它结束即可。

关于c - 如何等待一个 child 直到它在 c/c++ 中达到 CPU 时间超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27273451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com