退出在我的脚本中调用的程序

问题描述 投票:2回答:2

我正在尝试创建一个基本上调用/执行另一个程序的bash脚本,睡眠5秒,杀死所述程序,再次睡眠5秒钟,最后重新启动整个循环。

这是我创建脚本的尝试:

#! /bin/bash

while true
do

someOtherProgram -options..etc.
PID=$!
echo "someOtherProgram initiated"
sleep 5
kill $PID
echo "someOtherProgram killed"
sleep 5
echo "restarting loop"

done

有了这个脚本,它就可以启动someOtherProgram但它会卡在那里。我甚至没有在终端上看到我的回声"someOtherProgram initiated"

我知道这是一个简单的解决方案,但我刚开始时并不熟悉bash脚本。

感谢任何帮助。

bash
2个回答
2
投票

你的问题是$!

"Expands to the process ID of the job most recently 
 placed into the background"

你不是背景someOtherProgram -options..etc.。为此,您需要:

someOtherProgram -options..etc. &

(注意:最后的&符号&

目前你的PID是空的。您可以通过尝试输出它来轻松确认这一点,例如

echo "someOtherProgram initiated (PID: $PID)"

你可以在$!"Special Parameters""JOB CONTROL"部分找到man bash和背景过程(异步运行)的详细解释。


0
投票

Rankin's answer是正确的,因为它显示了代码失败的原因。仍然,如果需要另一种方法,那就是timeout命令,它有时更方便,因为它避免了需要跟踪变量。这是循环的样子:

while true
do
    ( timeout 5 someOtherProgram -options..etc. &
      echo "someOtherProgram initiated"
      wait ; )
    echo "someOtherProgram killed"
    sleep 5
    echo "restarting loop"
done

不幸的是,代码的效率低于使用变量,特别是因为它使用了shell括号()wait。如果首先打印初始化消息,它会更简单:

while true
do
    echo "someOtherProgram initializing..."
    timeout 5 someOtherProgram -options..etc.
    echo "someOtherProgram killed"
    sleep 5
    echo "restarting loop"
done
© www.soinside.com 2019 - 2024. All rights reserved.