Implementing execution timeout with C/C++

10,694

Solution 1

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

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

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

Solution 2

If all you need is to stop the program at timeout using pthreads (as you have described yourself) is a very good idea. There are a few threads on stackoverflow with similar problems so i suggest you look at their answers, for example: How to set a timeout for a function in C?

Share:
10,694
Imanol Barba Sabariego
Author by

Imanol Barba Sabariego

Updated on June 04, 2022

Comments

  • Imanol Barba Sabariego
    Imanol Barba Sabariego almost 2 years

    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.

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

    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.

    How would you implement it?

    Thanks in advance