This question already has an answer here:
I have an application server which we start by running this below command and as soon as we run the below commnad, it will start my application server
And to stop my application server, we do it like this -
So as soon as my application server is running and if I do
ps aux, this is what I get -
user@machineA:/home/user$ ps aux | grep gld_http user 20426 0.0 0.0 8114 912 pts/4 S+ 13:33 0:00 grep gld_http user 40509 0.1 0.9 3878120 1263552 ? Sl Sep22 1:53 /opt/data/bin/gld_http
Now I am trying to make a shell script in which I need to stop my application server and then I will check whether my process is running after stopping the server or not, if my process is still running, then I need to do kill -9 of my application pid. And I am not sure how to get the pid of my process in the shell script and then kill it.
Below is my shell script which I have as of now which will shut down my app server and then check whether my process is still running or not and if by any chance it is still running, then I need to get the pid of my process and do kill -9 on that pid.
#!/bin/bash /opt/data/bin/test_start_stop.sh stop if ps aux | grep -v "grep" | grep "gld_http" then echo "Server is still running" # now get the pid of my gld_http process and invoke kill -9 on it else echo "Server is stopped" fi
How can I get the pid of my process and do kill -9 on it in my above shell script?
So my final script will look like this -
#!/bin/bash /opt/data/bin/test_start_stop.sh stop if ps aux | grep -v "grep" | grep "gld_http" then echo "Server is still running" # 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." else echo "Server is stopped" fi