简体   繁体   English

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

[英]Linux bash script with stop/start option

I developed a script that find the number of running thread by given PID (as argument). 我开发了一个脚本,该脚本通过给定的PID(作为参数)查找正在运行的线程数。 we can run it once and everything work perfect. 我们可以运行一次,一切运行完美。 but, for our need i must make it to run with start and stop option. 但是,对于我们的需要,我必须使其与开始和停止选项一起运行。 means, until i'm not make it stop the script week logging the thread number. 意思是,直到我没有让它停止脚本周记录线程号。 i tried to do so in my code below but seems no luck 我试图在下面的代码中这样做,但似乎没有运气

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

Thank you all for the help 谢谢大家的帮助

It doesn't work because each time you execute the command you have a different process hence a different scriptPID. 这是行不通的,因为每次执行命令时,您都有一个不同的进程,因此会有一个不同的scriptPID。 Hence you could either: 因此,您可以:

  • store the pid of the process in a file where you find it again and use it to kill it 将进程的pid存储在一个文件中,您可以在该文件中再次找到它并使用它来杀死它

  • search for the process to be killed by looking at all processes with ps and choosing the right one by its name. 通过使用ps查看所有进程并选择正确的名称来搜索要杀死的进程。

added after OP clarification. 在OP澄清后添加 You can implement a "daemon mode" of your script. 您可以实现脚本的“守护程序模式”。 One way to do it is to accept a -d option and in that case run the script itself in background (without -d !) write the IP of the child to a file and then exit. 一种方法是接受-d选项,在这种情况下,在后台运行脚本本身(不带-d !),将子IP地址写入文件,然后退出。 Then you can read the IP from the file to later stop the child. 然后,您可以从文件中读取IP,以稍后阻止该孩子。

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

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