英文:
Keeping two processes alive in bash script (and respawning them when dead)
问题
I used to have the following lines in my script in order to keep alive my process:
while [ -f $FILENAME ]
do
echo "Running $BINNAME"
./$BINNAME >> $LOGNAME
sleep 1
done
Which worked fine for me. But my problem comes when I try to achieve the same behavior but calling two processes. In other words, In need my script to launch both of them and, constantly check if they fall. If so, launching again the fallen process.
There is no possibility to use pgrep
or systemd
.
What would you suggest me?
I tried the following:
while [[ -f $FILENAME && -f $FILENAMEPROC ]]
do
echo "Running $BINNAME + $BINNAMEPROC"
./$BINNAME >> $LOGNAME
./$BINNAMEPROC >> $LOGNAMEPROC
sleep 1
done
But obviously, the script waits BINNAME to finish, then launches BINNAMEPROC. And this is not valid because I need both processes to be running simultaneously.
Launching both on the background with &
and then using ps | grep [name]
is also not valid because it could cause false positives if someone adds a new process containing the string name
.
英文:
I used to have the following lines in my script in order to keep alive my process:
while [ -f $FILENAME ]
do
echo "Running $BINNAME"
./$BINNAME >> $LOGNAME
sleep 1
done
Which worked fine for me. But my problem comes when I try to achieve the same behavior but calling two processes. In other words, In need my script to launch both of them and, constantly check if they fall. If so, launching again the fallen process.
There is no possibility to use pgrep
or systemd
.
What would you suggest me?
I tried the following:
while [[ -f $FILENAME && -f $FILENAMEPROC ]]
do
echo "Running $BINNAME + $BINNAMEPROC"
./$BINNAME >> $LOGNAME
./$BINNAMEPROC >> $LOGNAMEPROC
sleep 1
done
But obviously, the script waits BINNAME to finish, then launches BINNAMEPROC. And this is not valid because I need both processes to be running simultaneosly.
Launching both on background with &
and then using ps | grep [name]
is also not valid because it could cause false possitives if someone adds a new process containing the string name
.
答案1
得分: 3
你可以像这样并行运行你的两个while
循环:
while : ; do
echo 1 正在运行
sleep 3
done &
while : ; do
echo 2 正在运行
sleep 3
done
在done
后面的和号(&)将第一个循环放入后台,从而允许第二个循环并行进行。
英文:
You can run your two while
loops in parallel like this:
while : ; do
echo 1 running
sleep 3
done &
while : ; do
echo 2 running
sleep 3
done
The ampersand (&) after done
puts the first loop into the background, thereby allowing the second loop to proceed in parallel.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论