1

My program takes two variables (n & k, from 1 to 100).

PROGRAM n k INPUT > OUTPUT 

I want to find out which combination of variables gives the best output. This is my way of doing this:

for n in {1..100}; do
   for k in {1..100}; do
       PROGRAM n k INPUT |
       awk -v n="$n" -v k="$k" '{print n,k,$0}' >> OUTPUT # Latter I analyse output and select best combination
   done
done

This works perfectly. However some variables (e.g, n from 80 to 90) takes really long time to run.
What I want:
Run given script for a specific amount of time and if PROGRAM hasn't finished jump to the following variable.
For example:

(n=11; k=23) PROGRAM 11 23 INPUT # Runs 59 seconds -- OK
(n=11; k=24) PROGRAM 11 24 INPUT # Runs 34 seconds -- OK
(n=11; k=25) PROGRAM 11 25 INPUT # Already runs 60 seconds -- Too much. End and jump to (n=11; k=26)
(n=11; k=26) PROGRAM 11 26 INPUT 
pogibas
  • 27,303
  • 19
  • 84
  • 117

1 Answers1

4

Just run your scripts with timeout. Install it, e.g. on Ubuntu sudo apt-get install coreutils. Then run your script with timeout DURATION PROGRAM n k INPUT

for n in {1..100}; do
   for k in {1..100}; do
       timeout 60 PROGRAM n k INPUT |
       awk -v n="$n" -v k="$k" '{print n,k,$0}' >> OUTPUT # Latter I analyse output and select best combination
   done
done

You can check the return value of timeout if you want to do something then.

timeout DURATION PROGRAM n k INPUT
if [ $? -ne 0 ]; then
    # it was killed (timeout returns non-zero if it killed the program)
    echo "took too long"
fi

Also take a look at this answer. It shows other ways to launch a process and then timeout, without relying on the timeout program:

(taken from the answer):

( cmdpid=$BASHPID; (sleep DURATION; kill $cmdpid) & exec PROGRAM n k INPUT )

However, in your case you are running a lot of programs. So this will lead to a lot of running background processes that sleep for DURATION, so this is probably not ideal. The other answer has the same problem.

Community
  • 1
  • 1
jmiserez
  • 2,991
  • 1
  • 23
  • 34
  • TIL linux has a `timeout` command. Thank you! Just shows that, even after decades, you're never finished learning linux. ;-) – Adam Liss Oct 19 '13 at 13:36