在第一次杀previous情况下,如果运行 [英] Killing previous instances at first time,if running
问题描述
以下是我的脚本Infinite.sh'code,我运行在后台这个脚本,运行此脚本之前,我要杀死所有的previous实例。
但是,这是杀害我CURENT实例也。
杀-9`ps的UX | grep的Infinite.sh | awk的-F \\'{$打印2}'`
而真实的;
做
呼应-n睡了5秒
日期
睡眠5
DONE
只是消除当前进程的PID从列表中。要做到这一点只作出微小病变到code:
杀-9`ps的UX | grep的Infinite.sh | awk的-F \\ -v PID = $$'的pid!= $ 2 {打印$ 2}'`
选项 -v PID = $
设置awk的变量 PID
当前进程的价值进程ID。这位前pression 的pid!= $ 2 {打印$ 2}
只有当它从当前进程的不同,将打印进程ID进程ID。
要简化code,我们可以使用指派,
:
杀-9 $(指派,Infinite.sh | grep的-v $$)
由于triplee在评论中指出, 杀死-9
只应作为最后的手段 - 。 9
(SIGKILL)prevents从自身后清理,删除临时文件等等其它信号,一个可能想尝试首先包含 -2 $的过程C $ C>(SIGINT),
-6
(SIGABRT),或 -15
(SIGTERM,这是默认)。至于哪些信号使用,兰德尔L.施瓦茨建议:
一般情况下,送15,并等待一两秒钟,并且如果不
工作,送2,如果不工作,发送1.如果还是不行,
卸下BINARY,因为该程序是表现不好!
块引用>有关为什么
杀死更多的细节-9
应避免,看的此处。关于各种Unix信号及其含义的详细信息,请参阅维基Following is my script 'Infinite.sh' code, I am running this script in background,Before running this script, i want to kill all previous instances. But this is killing my curent instance also.
kill -9 `ps ux|grep Infinite.sh|awk -F\ '{print $2}'` while true; do echo -n "SLEEPING FOR 5 SECOND" date sleep 5 done
解决方案Just eliminate the current process' PID from the list. To do this making just the minimal change to your code:
kill -9 `ps ux | grep Infinite.sh | awk -F\ -v pid=$$ 'pid != $2 {print $2}'`
The option
-v pid=$$
sets the awk variablepid
to the value of the current process' process ID. The expressionpid != $2 {print $2}
will print a process ID only if it differs from the current process' process ID.To simplify the code, we could use
pgrep
:kill -9 $(pgrep Infinite.sh | grep -v $$)
As triplee points out in the comments,
kill -9
should only be used as a last resort.-9
(SIGKILL) prevents a process from cleaning up after itself, deleting temporary files, etc. Other signals that one may want to try first include-2
(SIGINT),-6
(SIGABRT), or-15
(SIGTERM, which is the default). As for which signals to use, Randal L. Schwartz recommends:Generally, send 15, and wait a second or two, and if that doesn't work, send 2, and if that doesn't work, send 1. If that doesn't, REMOVE THE BINARY because the program is badly behaved!
For more details on why
kill -9
should be avoided, see here. For more information on the various Unix signals and their meaning, see wikipedia这篇关于在第一次杀previous情况下,如果运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!