繁体   English   中英

如何编写一个shell脚本来查找PID并杀死

[英]How to write a shell script to find PID and Kill

我正在尝试编写一个脚本来查找以前运行的另一个脚本的 PID。 一旦找到该PID,它就会发送一个终止信号。

我可以找到 PID 但终止信号没有处理,我收到一条返回消息,表明它不是 PID。

这是我在做什么:

#!/bin/bash   
 PID=`ps -eaf | grep "start.sh" | awk '{print $2}'`
    echo "$PID"    
    if [[ -z "$PID" ]];
     then(
            echo "Start script is not running!"
    )else(
            kill -9 $PID
    )fi

它试图杀死的脚本启动了许多其他脚本,所以我希望杀死start.sh将杀死所有子进程。

当你跑

ps -eaf | grep "start.sh" | awk '{print $2}'

你创建了一个带有start.sh字样的子 shell。 然后grep会选择它自己的进程和start.sh一个,这样你就会得到两个 PID。

这意味着当您试图同时杀死start.sh

ps -eaf | grep "start.sh" | awk '{print $2}'

过程。 start.sh会死,但另一个将不再存在,所以不能被杀死,所以它会给你一个错误。

如果您要拆分命令,您的运气可能会更好:

PIDS=$(ps -eaf)
PID=$(echo "$PIDS" | grep "start.sh" | awk '{print $2}')

尝试使用pgrep

PID=$(pgrep yourprocesname)

这是另一个可能对某人有用的解决方案:

#!/bin/bash  
kill-process-by-name(){  
   processes=$(ps -A)
   kill -9 `echo "$processes" | grep "$1" | cut -f2 -d" "`
}

kill-process-by-name "start.sh"

您可以使用pidof而不是ps -ef

PID=`pidof start.sh | awk '{print $1}'`
echo "$PID csshst will be stopped"
if [[ -z "$PID" ]]; then
(
        kill -9 $PID
)
fi
trashPID=`pidof start.sh | awk '{print $1}'`
echo "$PID csshst will be stopped"
if [[ -z "$PID" ]]; then
(
        kill -9 $PID
)
fi

纯粹

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM