Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing execution timeout with 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.

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

like image 725
Imanol Barba Sabariego Avatar asked Dec 25 '22 22:12

Imanol Barba Sabariego


1 Answers

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

like image 84
tux3 Avatar answered Dec 29 '22 00:12

tux3