繁体   English   中英

具有停止/启动选项的Linux bash脚本

[英]Linux bash script with stop/start option

我开发了一个脚本,该脚本通过给定的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查看所有进程并选择正确的名称来搜索要杀死的进程。

在OP澄清后添加 您可以实现脚本的“守护程序模式”。 一种方法是接受-d选项,在这种情况下,在后台运行脚本本身(不带-d !),将子IP地址写入文件,然后退出。 然后,您可以从文件中读取IP,以稍后阻止该孩子。

暂无
暂无

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

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