2

I have a bash script (sleeping in an infinite loop) running as a background process. I want to periodically signal this process, to do some processing without killing the script, ie. the script on receiving the signal should run a function and then go back to sleep. How do I signal the background process without killing it?

Here's what the code looks like for the script test.sh:

MY_PID=$$
echo $MY_PID > test.pid

while true
do
  sleep 5
done
trap 'run' SIGUSR1 

run()
{
 // data processing
}

This is how I am running it and triggering it:

run.sh &

kill -SIGUSR1 `cat test.pid`
2
  • what about using a signal handler? Commented Jan 18, 2014 at 15:17
  • 2
    First of all, you have to move the trap command above the while loop, or else it will never be executed. And the run function as well for that matter. Commented Jan 18, 2014 at 15:57

1 Answer 1

3

This works for me.

EDITED 2014-01-20: This edit avoids the frequent waking up. Also see this question: Bash: a sleep in a while loop gets its own pid

#!/bin/bash

MY_PID=$$
echo $MY_PID > test.pid

trap 'kill ${!}; run' SIGUSR1 

run()
{
    echo "signal!"
}

while true
do
  sleep 1000  & wait ${!}
done

Running:

> ./test.sh &
[1] 14094
> kill -SIGUSR1 `cat test.pid`
> signal!
> 
Sign up to request clarification or add additional context in comments.

2 Comments

Is there some way to do this without waking my process up every other second. I don't know if bash provides this option, but does tcl or some other scripting language provide it i wonder. Wherein it just sleeps until signal.
Awesome, works like a charm. I also added in some code to kill the sleep silently. trap 'killsub; parse' SIGUSR1 function killsub() { kill -9 ${!} 2>/dev/null wait ${!} 2>/dev/null }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.