使用 sh 监视输出时无法解决此错误



我正在进行优化,为此我需要将 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 卡住了,我无法从终端得到任何答案。当手动查看我的程序的输出时,我意识到程序没有问题,并且输出通常是写入的。

我无法解决这个问题。我对sh没有太多经验。我搜索了答案,但找不到。也欢迎实现相同目标的替代建议。

提前致谢

尾巴 -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

参考: https://stackoverflow.com/a/2041505/1563960

相关内容

最新更新