Hi All,
In a bash script i want to do the following (in pseudo-code):
if [ a process exists with $PID ]; then
kill $PID
fi
What's the appropriate bash for the conditional statement?
Thanks
Hi All,
In a bash script i want to do the following (in pseudo-code):
if [ a process exists with $PID ]; then
kill $PID
fi
What's the appropriate bash for the conditional statement?
Thanks
I think that is a bad solution, that opens up for race conditions. What if the process dies between your test and your call to kill? Then kill will fail. So why not just try the kill in all cases, and check its return value to find out how it went?
ps(1) command with -p $PID can do this:
$ ps -p 3531
PID TTY TIME CMD
3531 ? 00:03:07 emacs
To check for the existence of a process, use
kill -0 $PID
But just as @unwind said, if you're going to kill it anyway, just
kill $PID
or you will have a race condition.
If you want to ignore the text output of kill
and do something based on the exit code, you can
if ! kill $PID > /dev/null 2>&1; then
echo "Could not send SIGTERM to process $PID" >&2
fi
You have two ways:
Lets start by looking for a specific application in my laptop:
[root@pinky:~]# ps fax | grep mozilla
3358 ? S 0:00 \_ /bin/sh /usr/lib/firefox-3.5/run-mozilla.sh /usr/lib/firefox-3.5/firefox
16198 pts/2 S+ 0:00 \_ grep mozilla
All examples now will look for PID 3358.
First way: Run "ps aux" and grep for the PID in the second column. In this example I look for firefox, and then for it's PID:
[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358
3358
So your code will be:
if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then
kill $PID
fi
Second way: Just look for something in the /proc/$PID
directory. I am using "exe" in this example, but you can use anything else.
[root@pinky:~]# ls -l /proc/3358/exe
lrwxrwxrwx. 1 elcuco elcuco 0 2010-06-15 12:33 /proc/3358/exe -> /bin/bash
So your code will be:
if [ -f /proc/$PID/exe ]; then
kill $PID
fi
BTW: whats wrong with kill -9 $PID || true
?