Could I trap a 5-minute signal inside my script? I imagine something like this,
function dosomething {
echo "It's been 5 minutes."
}
trap dosomething SIGNAL-EVERY-5-MINUTES
while true
do
sleep 10
done
Note that this example doesn't have sense. It's just to ask if it's possible to trap something every x time.
EDIT: Based on @vinc17 answer, I've noticed that sleep
command from the main shell isn't interrupted by USR1
signal, and that's what I want to do.
#!/bin/bash
time=10
(
set -e
while true
do
sleep 30
# Since this is run as a subshell (instead of an external command),
# the parent pid is $$, not $PPID.
kill -USR1 $$
done
) &
finish() {
kill $!
echo "Closing."
exit 0
}
changetime() {
echo "Signal USR1 received."
time=$(( $RANDOM % 8 + 1))
}
trap changetime USR1
trap finish SIGINT
while true
do
echo "before sleep"
sleep $time
echo "after sleep"
done
outputs,
before sleep
Signal USR1 received.
after sleep
before sleep
Signal USR1 received.
after sleep
before sleep
Signal USR1 received.
Closing.
EDIT2: I've edited the above example, resulting in the same output, but adds one more difficulty: The sleep time is changed by the USR1
trap function. So now, every 30 seconds a random time between 1 and 8 is chosen. SO, I need to kill sleep
from the main script when signal changes its time. I insist on that it has no sense, but I need to know if it is possible.
sleep
, there is a high risk to kill another command in the script. The easiest solution is to do a shortersleep
run in a loop, e.g.:for i in $(seq 10); do sleep 1; done
sleep 10
, you can do./do_sleep; rm -f some_file
wheredo_sleep
is a script that doesecho $$ > some_file; exec sleep 10
, so that the code that sends the signal can also kill thesleep
by reading its pid in the created file. Not tested.sleep
. The script I'm working on has a long sleep inside the main script, which should be interruped by the signal. Moreover, inside the trap associated withUSR1
I need to change a global variable, which I guess I commented before, but forgot to include it on the example above.