我有两个脚本,一个python和一个c++。我只需要在c++脚本在后台活动时运行python脚本,然后在同一时间终止。我必须这样做,因为python脚本包含一个无限循环,它依赖于C++代码的输出。我是这方面的新手,所以我根据我在这里找到的答案写了这个bash脚本:
./test &
pid=$!
trap "kill -0 $pid 2> /dev/null" EXIT
while kill -0 $pid 2> /dev/null; do
python display.py
done
trap - EXIT但是它并没有真正终止python脚本,它只是不停地循环,直到我手动终止该进程。我使用的是ubuntu18.04.1,如果有用的话。
发布于 2018-12-06 16:38:41
问题是这一部分:
while kill -0 $pid 2> /dev/null; do
python display.py
done一旦python display.py启动,脚本就停止并等待它完成。这意味着它不再执行kill -0命令。如果其他进程启动,您可以启动display.py命令,然后在C程序完成时终止它。
./test &
pid=$!
if kill -0 $pid 2>/dev/null; then
#c program started
python display.py &
python_pid=$!
while kill -0 $pid 2>/dev/null; do
#c program running
sleep 1;
done
#c program finished
kill $python_pid
fi话虽如此,我同意@Poshi。更好的方法是使用管道。由于python程序是从c程序中读取的,所以应该执行类似于./test.sh | python display.py的操作。上面的答案更多的是“如何破解你已经在尝试的方法”。
发布于 2018-12-06 20:16:24
与其他shell一样,Bash有一个内置的wait命令来等待后台命令退出。除非顶级程序在运行其他程序时需要做其他事情,否则只需在后台运行这两个程序,等待第一个程序完成,然后终止第二个程序:
#! /bin/bash
./test &
testpid=$!
python display.py &
pythonpid=$!
wait "$testpid"
printf "Killing 'display.py' (PID %d)\\n" "$pythonpid" >&2
kill "$pythonpid"如果它能在C++程序之前运行Python程序,那么一个更简单的选项是:
#! /bin/bash
python display.py &
pythonpid=$!
./test
printf "Killing 'display.py' (PID %d)\\n" "$pythonpid" >&2
kill "$pythonpid"https://stackoverflow.com/questions/53654927
复制相似问题