【发布时间】:2014-11-12 09:38:30
【问题描述】:
重新启动服务通常通过 PID 文件实现 - 即进程 ID 被写入某个文件,并根据该数字停止命令将终止进程(或在重新启动之前)。
当您考虑它时(或者如果您不喜欢这个,那么search)您会发现这是有问题的,因为每个 PID 都可以重复使用。想象一个完整的服务器重新启动,您在启动时调用“./your-script.sh start”(例如 crontab 中的 @reboot)。现在 your-script.sh 将杀死一个 任意 PID,因为它已经存储了来自实时 before 重启的 PID。
我可以想象的一种解决方法是存储附加信息,以便您可以执行 'ps -pid | grep ' 并且只有当这返回一些东西时,你才能杀死它。还是在可靠性和/或简单性方面有更好的选择?
#!/bin/bash
function start() {
nohub java -jar somejar.jar >> file.log 2>&1 &
PID=$!
# one could even store the "ps -$PID" information but this makes the
# killing too specific e.g. if some arguments will be added or similar
echo "$PID somejar.jar" > $PID_FILE
}
function stop() {
if [[ -f "$PID_FILE" ]]; then
PID=$(cut -f1 -d' ' $PID_FILE)
# now get the second information and grep the process list with this
PID_INFO=$(cut -f2 -d' ' $PID_FILE)
RES=$(ps -$PID | grep $PID_INFO)
if [[ "x$RES" != "x" ]]; then
kill $PID
fi
fi
}
【问题讨论】:
-
顺便说一句,请不要为不是从环境中导入的变量使用大写的变量名,不要在测试中使用“x”废话(你甚至知道你为什么这样做吗?这个?)并使用参数扩展而不是分叉
cut。另外,引用所有参数扩展。 -
感谢您的提示!我在 bash 脚本中真的很痛苦。我在遇到空变量问题后读到的'x'废话,但可能原因是缺少“”或其他东西。我在哪里错过了报价?您能详细说明如何避免割伤吗?
-
@Karussell - re:
where missing the quote?在类似的地方:ps -$PID | grep $PIDINFO应该是ps "-$PID" | grep "$PIDINFO"。如果变量中有空格,那么它的值可能会混淆命令。