Home > Bash, linux, Programming > Reloading a bg process without terminating

Reloading a bg process without terminating

Ever wonder how /etc/init.d/scriptname reload works? I haven’t figured out yet. But I have achieved something similar through the following example:

1. make a folder called trap

2. create main.sh under that folder with the following code

#!/bin/bash
SCRIPT=${0##*/}
[ -f data ] && step=`cat data` || step=1
if [ $# -eq 1 -a "$1" == "reload" ]; then
	if [ -f $SCRIPT.pid ]; then
		c="kill -USR1 `cat $SCRIPT.pid`"
		echo $c
		eval $c
	fi
	exit
elif [ $# -eq 1 -a "$1" == "stop" ]; then
	if [ -f $SCRIPT.pid ]; then
		kill -TERM `cat $SCRIPT.pid`
		rm -f $SCRIPT.pid
	fi
	exit
fi

init=0
function on_sigusr1()
{
	#todo: validate content in file data
	step=`cat data`
	init=0
}
echo $$>$SCRIPT.pid
while true; do
	trap on_sigusr1 SIGUSR1
	init=$((init+1))
	echo "$init"
	sleep $step
done

3. under the same folder create a text file named data

4. inside the current terminal run main.sh script

5. you should be able to see sequential numbers starting from 1 scrolling up the screen one number per second

6. now open another terminal, cd to trap/, issue the following commands:

echo “.5” > data
./main.sh reload

7. you should be able to see the numbers scroll twice as faster (change .5 to 2 will make the scrolling slower)

8. to terminate the program, simply run
./main.sh stop
from the second terminal

I didn’t add validation for the intervals but you should now get the idea how the program behaves.

Advertisements
Categories: Bash, linux, Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: