script to execute program in loop and kill current process if time limit is exceeded
I have a bash script t开发者_Python百科hat executes a program in a loop, but I want to set a max time limit for each execution of the program, i.e. i just want to cancel the current execution if the time limit is exceeded but I don't want to break the entire loop.
Thanks!
There is a command named timeout on my Ubuntu. You could try this:
timeout 1s yes
This will make the process yes to ends after 1 second.
Note: with this command its also possible to specify the signal as an argument.
You can also validate that the duration constaint get respected using this command:
time timeout 3s yes
This should work in any Posix shell, including bash...
#!/bin/sh
while :; do
echo starting command
while :; do
trap break SIGTERM
sleep 5; kill $$ # 5 second timeout
sleep 10 # replace this sleep with your real command
done
echo Command terminated, restarting...
done
精彩评论