【问题标题】:Linux bash script with stop/start option带有停止/启动选项的 Linux bash 脚本
【发布时间】:2015-08-04 06:55:46
【问题描述】:

我开发了一个脚本,通过给定的 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

谢谢大家的帮助

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    它不起作用,因为每次执行命令时都有不同的进程,因此 scriptPID 也不同。因此,您可以:

    • 将进程的 pid 存储在一个文件中,您可以在其中再次找到它并使用它来杀死它

    • 通过查看所有带有ps 的进程并根据其名称选择正确的进程来搜索要终止的进程。

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

    【讨论】:

    • 脚本运行良好。但是当我启动它时,我没有再次获得控制台..这正是我用 ctrl+c 杀死脚本的原因。
    • 您可以按 ctrl+Z 返回控制台(脚本已暂停),然后按 bg 使其在后台运行。使用作业来控制正在运行的脚本。
    • 我怎样才能让它自动回到控制台而不按任何东西?只需启动脚本,它会立即返回控制台但继续运行
    • 在命令行末尾添加和符号 &。或者让脚本在后台启动另一个进程,然后退出。
    • 好的。当我调用“initCommand”函数时,将 & 添加到脚本的最后一行?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    相关资源
    最近更新 更多