我正在进行优化,为此我需要将matlab代码链接到linux程序并继续监视输出.我使用下面的这个sh完成了这个链接,但它运行不正常,因为我无法跟踪多个’表达式’.
#!/bin/bash
../program inputfile &> OutputFile.dat &
tail -f OutputFile.dat | sed -n '/NaN/q;/STOP/q'
killall program
我在这里寻求帮助,我得到了一个很好的解决方案.解决方案部分解决了问题.在提示符上运行程序,可以跟踪这些表达式并在需要时终止程序.给出的解决方案是:
#!/bin/bash
( stdbuf -o 0 -e 0 ../program inputfile & ) &> OutputFile.dat
sed -n '/NaN/q;/STOP/q' <(tail -f OutputFile.dat)
killall program
当我在matlab上实现并执行’链接’时,代码没有很好地响应.运行几分钟后,matlab卡住了,我无法从终端得到任何答案.当我手动查看程序的输出时,我意识到程序没有问题,并且通常正在编写输出.
我无法解决这个问题.我没有很多经验.我已经找到了答案,但我找不到任何答案.也欢迎提供相同建议的替代建议.
提前致谢
解决方法:
尾部-f导致挂起.你还需要杀死sed / tail进程才能继续.
#!/bin/bash
( stdbuf -o 0 -e 0 ../program inputfile & ) &> OutputFile.dat
# get the process id (pid) of "program"
# (bash sets $! to the pid of the last background process)
program_pid=$!
# put this in the background, too
sed -n '/NaN/q;/STOP/q' <(tail -f OutputFile.dat) &
# get its pid
sed_pid=$!
# wait while "program" and sed are both still running
while ps -p $program_pid && ps -p $sed_pid; do
sleep 1
done >/dev/null
# one (or both) have now ended
if ps -p $program_pid >/dev/null; then
# "program" is still running, and sed must have found a match and ended
echo "found Nan or STOP; killing program"
kill $program_pid
elif ps -p $sed_pid; then
# sed is still running, so program must have finished ok
kill $sed_pid
fi
ref:https://*.com/a/2041505/1563960