【问题标题】:Can't solve this error when monitoring a output using sh使用 sh 监视输出时无法解决此错误
【发布时间】:2016-03-19 17:43:18
【问题描述】:

我正在进行优化,为此我需要将 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没有太多经验。我已经搜索了答案,但我找不到任何答案。也欢迎实现相同目标的替代建议。

提前致谢

【问题讨论】:

    标签: linux bash matlab shell monitoring


    【解决方案1】:

    tail -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

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 2011-05-13
      • 1970-01-01
      • 2021-11-24
      • 2017-11-04
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多