使用C/C ++实现执行超时 [英] Implementing execution timeout with C/C++

查看:405
本文介绍了使用C/C ++实现执行超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在考虑在代码中实现执行超时机制.我浏览了一下以寻求建议,但我所看到的只是为正在调用的其他程序实现了执行超时,这不完全是我的主意.

I've been thinking about implementing an execution timeout mechanism in my code. I browsed looking for advice but all I saw is implementing execution timeouts for other programs being called, which wasn't exactly my idea.

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

I'm working with C/C++ on Linux.

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

What's the best way to accomplish this without using external libraries? I thought that maybe running a separate thread that upon timeout, sends a TERM signal to the process ID and then the program handles it and exits, but I don't know if it's correct in terms of good practice.

您将如何实施?

预先感谢

推荐答案

您可以使用 setitimer(2)即可获得SIGVTALRM

You can use setitimer(2) on Linux to get a SIGVTALRM after a given amount of time

这是设置计时器的方式:

This is how you would set up a timer :

#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);

请注意,SIGVTALRM的默认处理程序将以错误终止程序. 从技术上讲,它可以正常工作,但是如果您想干净地处理它,可以安装这样的信号处理程序:

Note that the default handler for SIGVTALRM will terminate your program with an error. It will technically work, but if you want to handle it cleanly you can install a signal handler like this :

#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);

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

Of course this will only work on Linux (and perhaps on Mac/BSD).

这篇关于使用C/C ++实现执行超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆