简体   繁体   English

等待命令完成/window 在 Bash 中关闭

[英]Wait for command to finish / window to close in Bash

I have an application that should work 24/7 on a Raspberry Pi.我有一个应用程序应该在 Raspberry Pi 上 24/7 全天候工作。 To ensure that, I'm trying to write a bash script that will run on bootup, execute my main application, and in case of a failure (bugs, exceptions, etc.) execute it again.为了确保这一点,我正在尝试编写一个 bash 脚本,该脚本将在启动时运行,执行我的主应用程序,并在出现故障(错误、异常等)时再次执行它。

This is my script:这是我的脚本:

#!/bin/bash

while true
do
    lxterminal --title="mytitle" --geometry=200x200 -e "./myapplication"
done

As expected, this opens infinite amount of terminal windows.正如预期的那样,这会打开无限数量的终端 windows。 Then I have tried:然后我试过了:

#!/bin/bash

while true
do
    lxterminal --title="mytitle" --geometry=200x200 -e "./myapplication" &
    PID=$!
    wait $PID
done

This one also did not work like I wanted, it waits for the lxterminal process to finish, but that is not what I expect.这个也没有像我想要的那样工作,它等待 lxterminal 进程完成,但这不是我所期望的。 Instead, I want my script to wait for lxterminal window to close, and continue with the loop.相反,我希望我的脚本等待 lxterminal window 关闭,然后继续循环。

Is that possible?那可能吗? Any suggestions?有什么建议么?

In this case, your script is behaving properly.在这种情况下,您的脚本运行正常。 By doing this:通过做这个:

lxterminal --title="mytitle" --geometry=200x200 -e "./myapplication" &
PID=$!
wait $PID

Wait will use the PID of the last command used (lxterminal).等待将使用最后使用的命令的 PID(lxterminal)。 However, you are interested in child process which would be the PID of ./myapplication running itself.但是,您对子进程感兴趣,该子进程将是./myapplication自身运行的 PID。 Basically, lxterminal will have its own PID and as parent, it will launch your script and it will create a new process with its new PID (child).基本上,lxterminal 将拥有自己的 PID,作为父进程,它将启动您的脚本,并使用新的 PID(子进程)创建一个新进程。

So the question would be, how to retrieve the PID child process given the parent child?所以问题是,如何在给定父子进程的情况下检索 PID 子进程?

In your case, we can use next command.在您的情况下,我们可以使用下一个命令。

ps --ppid $PID

Which will give such output.这将给出这样的 output。

ps --ppid 11944
  PID TTY          TIME CMD
11945 pts/1    00:00:00 sleep

Then, with some help, we can retrieve only the child PID.然后,在一些帮助下,我们可以只检索子 PID。

ps --ppid 11944 | tail -1 | cut -f1 -d" "
11945

So finally, in your script, you can add new variable containing child process.所以最后,在你的脚本中,你可以添加包含子进程的新变量。

#!/bin/bash

while true
do
    lxterminal --title="mytitle" --geometry=200x200 -e "./myapplication" &
    PID=$!
    CPID=ps --ppid $PID | tail -1 | cut -f1 -d" "
    wait $CPID
done

I did not really try it in your case, as I don't have same scenario than yours, but I believe it should work, if not, there might be some hints in this answer which might help you to find proper solution to your problem.在您的情况下,我并没有真正尝试过,因为我的情况与您的情况不同,但我相信它应该可以工作,如果没有,此答案中可能会有一些提示,可能会帮助您找到问题的正确解决方案.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM