Skip to content

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’.

../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:

( 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



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


( 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)

# put this in the background, too
sed -n '/NaN/q;/STOP/q' <(tail -f OutputFile.dat) &
# get its 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


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