我开发了一个脚本,通过给定的 PID(作为参数)查找正在运行的线程数。我们可以运行一次,一切都完美无缺。 但是,为了我们的需要,我必须让它以启动和停止选项运行。 意思是,直到我不让它停止脚本周记录线程号。 我尝试在下面的代码中这样做,但似乎运气不好
PID=$1
Command=$2
scriptPID=`echo $$`
#going to check if arguments were supplied if not using the defaults. if only one argument supplied then aborting.
if [[ $PID -eq 0 ]]
then
echo -e "\n[ERROR]: No PID was provided. please provide PID as argument.\n"
exit 1
fi
initCommand(){
#local Command="$2";
case $Command in
start)
start "true"
;;
stop)
stop -f "true"
;;
esac
}
start(){
#going redirect stout & stderr to log file
echo "starting"
echo "script PID $scriptPID"
exec 1>>pidThreadNumber.log 2>&1
while (true); do
runningThreads=`ps huH p $PID | wc -l`
date;
echo "-------------------------------"
echo -e "Number of running threads: "$runningThreads"\n\n"
sleep 2
done
}
stop()
{
kill -9 $scriptPID
}
initCommand $Command
谢谢大家的帮助
最佳答案
它不起作用,因为每次执行命令时,您都有不同的进程,因此有不同的 scriptPID。因此您可以:
将进程的 pid 存储在一个文件中,您可以在该文件中再次找到它并使用它来杀死它
通过使用
ps
查看所有进程并根据名称选择正确的进程来搜索要终止的进程。
添加。您可以实现脚本的“守护进程模式”。一种方法是接受 -d
选项,在这种情况下,在后台运行脚本本身(没有 -d
!)将 child 的 IP 写入文件然后退出。然后您可以从文件中读取 IP 以稍后停止 child 。
关于带有停止/启动选项的 Linux bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31802630/