I have written a loop to iterate all .out c binary file and copy their outputs into a text file (the output for every binary file is just a one line hash value, one line output for one program). Here is my code so far:

for j in {1..10}
    ./gcc-$j.out >> gcc-result.txt

Unfortunately, some binary files have some unknown issues and cannot be correctly executed (they got stuck and cannot proceed to the next program).

I am not going to fix those c code but I want my bash to automatically jump to executing the next program within a given timeout (say 10 secs), and also write "0" to the gcc-result.txt.

Thanks in advance if you have idea to solve this issue.

  • Does the "stuck" process need to be killed or can it just be ignored and left to run to completion? – roaima Apr 27 '15 at 10:48
  • Thank you for your reply, it should be killed, and output "0" result file (occupy one line) – Yang Xia Apr 27 '15 at 10:49
  • Isn't this an instance of the famed "Halting Problem"? – Bruce Ediger Apr 27 '15 at 12:28
  • @BruceEdiger No. The spec quite clearly says that the code should skip a file if it takes more than "say 10 secs" to terminate. You don't need to know if it's going to halt or not: just whether it did halt within a time limit. – David Richerby Apr 27 '15 at 17:54
  • @DavidRicherby - thanks for the consideration. "Say, 10 seconds" sounds like a very informal spec, and to my mind, a requirement conceived of without much thought. But, yes, that makes it not an instance of the Halting Problem. – Bruce Ediger Apr 27 '15 at 18:13

You could use the timeout command :

if timeout 10 ping google.fr > /dev/null
    echo "process successful"
    echo "process killed"

shows process killed, and

if timeout 10 ls /usr/bin | wc -l > /dev/null
    echo "process successful"
    echo "process killed"

shows process successful. Based on this, you could run each command using such an if; then; else; fi, redirect the standard output to a temporary file, and copy that temporary to the target file in the successful case, while generating the target file in the failure case.

How can I kill a process and be sure the PID hasn't been reused could be helpful in case you don't have timeout.


You can certainly kill the child process after some execution time and append the text file you need with '0' from within your bash-script.
You may find Bash script that kills a child process after a given timeout useful.

Not the answer you're looking for? Browse other questions tagged or ask your own question.