About Me

My photo
Working as Technical Lead in CollabNET software private limited.

Tuesday 13 May, 2008

UNIX SIGNALS

THE UNIX SIGNALS are used for communicating the process when ever the event has occurred.

When ever you give CRTL + C on the running process or kill on the running process id, the signals are sent to process to notify the event.

There are about 64 signals and can be viewed using kill -l.

When you press CRTL + C , by default SIGINT is sent to the running process,
When you press CRTL + Z , by default SINTSTP is sent to the running process,
When you press CRTL + / , by default SIGABRT is sent to the running process.

Think when some one press CTRL + C when your program is half the way, you are going to end up with non cleaned up resource, this is because you do'nt have handler over the SIGINT in our program.

You can write the handler for CRTL + C using trap as follows to get the control. You cannot get the handler for SIGKILL and SIGSTOP. These two signals cannot be caught while other can be.

test.sh

!/bin/bash

trap "echo 'This is trap executing for 0!'; exit 0" 0
trap "echo 'This is trap executing for SIGINT!'; exit 1" SIGINT
trap "echo 'This is trap executing for SIGKILL!'; exit 1" SIGKILL
trap "echo 'This is trap executing for SIGTERM!'; exit 1" SIGTERM
trap "echo 'This is trap executing for SIGABRT!'; exit 1" SIGABRT

echo "We are running the script. Press Ctrl-C to cause trap to execute!"

read

We can also send the signals during kill using pid.

For EX:
kill -15 pid,

The above command will send the SIGTERM signal to the pid before terminating. So you can do your clean up logic by handling the signal in your program.

Using kill -9 pid,

the above command will send the SIGKILL signal but it cannot be caught by the program, this is also similar to SIGSTOP that cannot be caught too.

So it's advisable to use the SIGTERM to kill the process and then the SIGKILL as we can caught the SIGTERM signal for our operations and the SIGKILL cannot be.

The Recommended order of killing the process id is

kill_pid () {
PID=$1
RETVAL=0

for signal in "TERM" "INT" "HUP" "KILL"; do
kill -$signal $PID
RETVAL=$?
[ $RETVAL -eq 0 ] && break
echo "warning: kill failed: pid=$PID, signal=$signal" >&2
sleep 1
done

return $RETVAL
}

kill_pid 1234

1 comment:

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!