Linux:在进程ID完成或被杀死后发送邮件 [英] Linux: Send mail after a process id finishes or is killed
问题描述
我想在其他用户的进程终止或完成后在我的电子邮件中收到通知.我可以通过另一个用户的进程ID或出现在"top"命令中的进程的名称来识别另一个用户的进程.
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
它将始终为true
.为什么?只需直接在命令行上运行它,而无需-q
到grep
,这将很明显:
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
上面的示例显示grep
总是成功的,因为它找到了自己!
The above example shows that the grep
will always be successful because it finds itself!
有很多方法可以解决此问题.一种方法是使用 pgrep
而不是grep
.
There are many ways to fix that. One way is to use pgrep
instead of grep
.
if pgrep 'process_name' > /dev/null; then
这篇关于Linux:在进程ID完成或被杀死后发送邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!