我有一个在后台运行的脚本,如下所示:
nohup /tmp/a.sh &
如果脚本运行超过 5 分钟,我就想要kill
它。
-bash-3.2$ nohup /tmp/a.sh &
[1] 2518
-bash-3.2$ nohup: appending output to `nohup.out'
-bash-3.2$ ps -ef | grep /tmp/a.sh
ordev 2518 17827 0 15:24 pts/3 00:00:00 /bin/sh /tmp/a.sh
ordev 2525 17827 0 15:24 pts/3 00:00:00 grep /tmp/a.sh
-bash-3.2$
-bash-3.2$ killall /tmp/a.sh # killall not working like this
/tmp/a.sh: no process killed
如果我killall
像下面一样使用,它会尝试终止所有正在运行的会话/bin/sh
:
-bash-3.2$ killall sh /tmp/a.sh
sh(17822): Operation not permitted # this pid associated with another process under root user.
/tmp/a.sh: no process killed
[1]+ Terminated nohup /tmp/a.sh .
除了 之外pkill -f
,是否还有其他方法可以仅删除所需的脚本名称?
答案1
保存启动进程的pid并保存到文件中。在生成新实例之前,请检查旧实例是否已完成。否则,杀掉它。
echo "Starting a new A instance"
nohup /tmp/a.sh &
echo "Writing A pid to file"
echo $! > /tmp/a_pid
然后你可以检查时间并终止脚本:
if [ -f /tmp/a_pid ]; then
echo "Trying to stop previous instance of proces A"
kill $(cat /tmp/a_pid) || true
echo "Removing A pid file"
rm /tmp/a_pid
fi
答案2
没必要指名道姓地杀人。我建议您在每次运行脚本时保存脚本的 PID,然后在想要终止脚本时从文件中调用该 PID。喜欢:
nohup /tmp/a.sh &
echo $! > a_pid
然后要杀死它,请执行以下操作:
ps -9 ` a_pid`
注意$!给出最后运行的命令,该命令将为 nohupnohup /tmp/a.sh &