Thursday, October 1, 2009

Sending SIGNALS from Shell Script to our Application: Linux Platform

Signals:

I knew that signals are like software interrupts in Linux. Earlier, I never used signals. When, my first code of device detection was inconsistent, our lead has given shell script idea and one of my friends has given signals idea.

Within next 4 days, everything was ready...!


When can we signals in our application?

If we have to do something when something happen, then we can use signals instead of constant polling using threads or processes. In our case, we were polling for device insertion detection using pthreads in Linux. Hence we shifted to use shell script independent of our application and we made shell script to send a signal to our application when device insertion is detected.

Among number of signals, two user signals are there in Linux which can be used in our application. Those are signal number 10 and 12 (SIGUSR1 and SIGUSR2).

I have used SIGUSR1 in our application.


How can we use signals in our Application?

We use ‘kill’ utility of Linux/Unix to send signals to application.

Consider the following script for example:

while [ 1 ]
do
if [ -b /dev/sdb1 ]
then
kill -10 {PID of OurApplication}
fi
done

When a valid block device is found in /dev/ directory as sdb1, then this will send a signal to our application. We have to give PID of our application to kill command.


How to get the PID of our application at run time?

When shell script implementation was over, it was working fine and robustly as a stand alone application. But when we thought to send a signal when device insertion is detected, I came to know that KILL requires PID of our application. Our next question was how to get the PID of our application at run time. Idea was combination of PS and GREP command utility.

pid = (`ps | grep OurApplication`)
kill -10 $pid

Here, OurApplication is the name of our application (say myPlayer). Variable pid will get the ProcessID of our application and use the same for sending signal.


At the END:

while [ 1 ]
do
If [ -b /dev/sdb1 ]
then
pid = (`ps | grep myPlayer`)
kill -10 $pid
fi
done

This work made to me to know about Signals and its deployment in our applications. I was happy when it was completed.

Write to me at pramoda.ma@gmail.com for ur all concerns.

No comments:

Post a Comment