保持两个进程在bash脚本中保持运行(并在它们死掉时重新启动它们)

huangapple go评论56阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年7月4日 20:52:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76612849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定