使用C/C++实现执行超时

Ima*_*ego 2 c c++ linux timeout execution

我一直在考虑在我的代码中实现执行超时机制.我浏览了寻找建议,但我看到的只是为正在调用的其他程序执行执行超时,这不是我的想法.

我在Linux上使用C/C++.

在不使用外部库的情况下实现此目的的最佳方法是什么?我认为可能运行一个单独的线程,在超时时,向进程ID发送一个TERM信号,然后程序处理它并退出,但我不知道它是否在良好实践方面是正确的.

你会如何实现它?

提前致谢

tux*_*ux3 8

您可以在Linux上使用setitimer(2)在给定的时间后获取SIGVTALRM

这是你设置计时器的方法:

#include <sys/time.h>

/* Start a timer that expires after 2.5 seconds */
struct itimerval timer;
timer.it_value.tv_sec = 2;
timer.it_value.tv_usec = 500000;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 0;
setitimer (ITIMER_VIRTUAL, &timer, 0);
Run Code Online (Sandbox Code Playgroud)

请注意,SIGVTALRM的默认处理程序将终止程序并显示错误.它在技术上会起作用,但是如果你想干净利落地处理它,你可以像这样安装一个信号处理程序:

#include <signal.h>
#include <stdio.h>
#include <string.h>

void timer_handler (int signum)
{
    printf ("Timed out!\n");
}

/* Install timer_handler as the signal handler for SIGVTALRM. */
struct sigaction sa;
memset (&sa, 0, sizeof (sa));
sa.sa_handler = &timer_handler;
sigaction (SIGVTALRM, &sa, 0);
Run Code Online (Sandbox Code Playgroud)

当然,这只适用于Linux(也许适用于Mac/BSD).