[Solved] How to compile a program with limit time (5s), using MinGW-Gnu C++


You can do it using shell with a sequence like

<program>& 
pid=$!
sleep $time_limit
if ps aux | grep $pid | grep -v grep > /dev/null
then 
  kill $pid
  echo "Time limit exceeded"
fi

Here are two examples with and without reaching the time limit (using sleep 10 and sleep 3 as program, with a time limit of 5 seconds):

$ sleep 10& pid=$!; sleep 5; if ps aux | grep $pid | grep -v grep > /dev/null; then kill $pid; echo "Time limit exceeded"; fi
Time limit exceeded
$ sleep 3& pid=$!; sleep 5; if ps aux | grep $pid | grep -v grep > /dev/null; then kill $pid; echo "Time limit exceeded"; fi
$

The way it works is that the program is launched in background (with the & after the program name). The pid ($!) is stored in a variable named pid. Then I wait $time_limit using sleep and I check if the process with pid $pid still runs. I use | grep -v grep because the grep $pid will also appear in the output of ps aux.

If the process still runs, I kill it and display the message you wanted.

This can be included easily in a Makefile. You could also make it a shell script in your PATH if you want to be able to use it in other context.

solved How to compile a program with limit time (5s), using MinGW-Gnu C++