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

标签 linux bash shell

我开发了一个脚本,通过给定的 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!)将 child 的 IP 写入文件然后退出。然后您可以从文件中读取 IP 以稍后停止 child 。

关于带有停止/启动选项的 Linux bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31802630/

相关文章:

Java 动画程序在 Linux 中运行不流畅

linux - rsync 错误 : received SIGINT, SIGTERM 或 SIGHUP(代码 20)位于 rsync.c(544) [sender=3.0.6]

linux - 如何使用破折号或星号创建格式化标题

arrays - bash 中的数组运算符

bash - 在 "executable"打包bash脚本双击执行(最好平台无关)?

linux - apt-get 代理 : Permission denied

bash - 使用 tac combo sed/awk/grep/? 提取最后 5 分钟的系统日志数据 (750mb)

android - 执行 shell 命令并在 TextView 中获取输出

string - csh 上的自连接字符串

c - Ubuntu C代码如何在另一个文件夹中执行命令