Skip to content
Advertisement

Can’t solve this error when monitoring a output using sh

I’m working on an optimization and for that I need to link a matlab code into a linux program and keep monitoring the outputs. I’d done this link using this sh below, however it wasn’t working well, since I couldn’t keep track of more than one ‘expression’.

#!/bin/bash
../program inputfile &> OutputFile.dat &
tail -f OutputFile.dat | sed -n '/NaN/q;/STOP/q'
killall program

I’ve asked for help here, and I got a good solution. The solution solved partially the problem. Running the program on the prompt it was possible to keep track on those expressions and kill the program when needed. The solution given was:

#!/bin/bash
( stdbuf -o 0 -e 0 ../program inputfile & ) &> OutputFile.dat
sed -n '/NaN/q;/STOP/q' <(tail -f OutputFile.dat)
killall program

When I implemented on the matlab, and did the ‘linkage’ the code didn’t responded well. After a few minutes running, the matlab got stuck, I couldn’t get any answer from the terminal. When looked manually on the outputs of my program I realized that there were no problems on the program, and the outputs was normally being written.

I can’t solve this problem. I don’t have a lot of experience on sh. I’ve searched for answers, but I couldn’t find any. Alternative suggestions to achieve the same thing are also welcome.

Thanks in advance

Advertisement

Answer

The tail -f is causing the hang. You need to also kill the sed/tail process in order to continue.

#!/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://stackoverflow.com/a/2041505/1563960

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement