How to get the pid of a process and invoke kill -9 on it in the shell script?
First of all; "kill -9" should be a last resort.
You can use the kill
command to send different signals to a process. The default signal sent by kill
is 15 (called SIGTERM). Processes usually catch this signal, clean up and then exit. When you send the SIGKILL signal (-9
) a process has no choice but to exit immediately. This may cause corrupted files and leave state files and open sockets that might cause problems when you restart the process. The -9
signal can not be ignored by a process.
This is how I would do it:
#!/bin/bash
# Getting the PID of the process
PID=`pgrep gld_http`
# Number of seconds to wait before using "kill -9"
WAIT_SECONDS=10
# Counter to keep count of how many seconds have passed
count=0
while kill $PID > /dev/null
do
# Wait for one second
sleep 1
# Increment the second counter
((count++))
# Has the process been killed? If so, exit the loop.
if ! ps -p $PID > /dev/null ; then
break
fi
# Have we exceeded $WAIT_SECONDS? If so, kill the process with "kill -9"
# and exit the loop
if [ $count -gt $WAIT_SECONDS ]; then
kill -9 $PID
break
fi
done
echo "Process has been killed after $count seconds."
pidof gld_http
should work if it is installed on your system.
man pidof
says:
Pidof finds the process id’s (pids) of the named programs. It prints those id’s on the standard output.
EDIT:
For your application you can use command substitution
:
kill -9 $(pidof gld_http)
As @arnefm mentioned, kill -9
should be used as a last resort.