Bash, how to check if a C program times out

Viewed 84

I want to run a C program foo.c thats compiled to foo within a bash script and see check if it times out.

There is one parameter to foo and the 10 second timeout. I want to check if the program foo times out or executes. If it times out I want to exit 0.

#!/bin/sh
# -*-sh-*-
/foo $1 10
if [$? -eq 0]
    then
        exit 0;
fi
exit 1;
1 Answers

Use the timeout command:

timeout 10s ./foo
if [ $? -eq 124 ] ; then
    exit 0
else
    exit 1
fi

From man timeout:

If the command times out, and --preserve-status is not set, then exit with status 124. Otherwise, exit with the status of COMMAND. If no signal is specified, send the TERM signal upon timeout. The TERM signal kills any process that does not block or catch that signal. It may be necessary to use the KILL (9) signal, since this signal cannot be caught, in which case the exit status is 128+9 rather than 124.

Related