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`
egorulz
  • 1,455
  • 2
  • 17
  • 28

1 Answers1

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!
> 
Community
  • 1
  • 1
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
  • 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. – egorulz Jan 20 '14 at 12:31
  • 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 } – egorulz Jan 21 '14 at 02:11