I want to be notified on my email after another user's process kills or finishes. I can identify another user's process by its process id or the name of the process appearing in "top" command.
In order to do the same I wrote the following script:
while true; do
if ps -ef | grep -q 'process_name'; then
sleep 1
else
echo "complete" | mail -s "process exiting" abc@gmail.com
fi
done
However, I find that even after another user's process finishes or the other user kills his or her process, still I am not getting any notification or email. Can someone please help me with this a bit.
The problem is most likely this check:
if ps -ef | grep -q 'process_name'; then
It will always be true
. Why? Just run it directly on the command line without the -q
to grep
and it will be obvious:
$ ps -ef | grep 'process_name'
user 4550 3349 0 09:17 pts/0 00:00:00 grep --colour=auto process_name
$ echo $?
0
The above example shows that the grep
will always be successful because it finds itself!
There are many ways to fix that. One way is to use pgrep
instead of grep
.
if pgrep 'process_name' > /dev/null; then
Another common technique to prevent the grep
process from matching itself is to surround one of the letters in the pattern with []
, like this:
grep -q '[p]rocess_name'
If you know the process of, then you don't need grep
at all, you can use the exit code of ps
itself:
if ps -p pid &> /dev/null; then
sleep 1
where pid is of course the process id.