我想运行三个进程,这些进程都将停止显示服务已启动并且不会给出提示。我想自动执行此过程。我试过用“&”最后,但它在终端弹出。我尝试使用“sh + x script1.sh& sh + x script2.sh”I need to stop the process by pressing ctrl+c for another script to run请帮忙
答案 0 :(得分:0)
您需要定义一个通用脚本,在后台启动三个进程,并等待用户按下Control + C.然后,您将向常规脚本添加陷阱以启动关闭挂钩。
我认为解决方案可能如此:
#!/bin/bash
end_processes() {
echo "Shutdown hook"
if [ -n $PID1 ]; then
echo "Killing PID 1 = $PID1"
kill -9 $PID1
fi
if [ -n $PID2 ]; then
echo "Killing PID 2 = $PID2"
kill -9 $PID2
fi
if [ -n $PID2 ]; then
echo "Killing PID 3 = $PID3"
kill -9 $PID3
fi
}
# Main code: Add trap
trap end_processes EXIT
# Main code: Launch scripts
./script1.sh &
PID1=$!
./script2.sh &
PID2=$!
./script3.sh &
PID3=$!
# Main code: wait for user to press Control+C
while [ 1 ]; do
sleep 1s
done
请注意:
您可以修改等待循环(最后一个while命令)以首先进入睡眠状态,以便完成进程的近似时间,然后等待更短的时间:
APROX_TIME=30s
POLL_TIME=2s
sleep $APROX_TIME
while [ 1 ]; do
sleep $POLL_TIME
done