Cannot resolve this error while monitoring output using sh

I am working on optimization, and for this I need to link the matlab code with the linux program and monitor the results. I made this link using this sh below, however this did not work since I could not track more than one expression.

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

I asked for help here and I got a good solution. The solution partially solved the problem. By running the program at the prompt, you could track these expressions and kill the program when necessary. The solution is given:

#!/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 Matlab and did the "binding", the code did not respond well. After several minutes of work, Matlab was stuck, I could not get any response from the terminal. When I looked at the outputs of my program manually, I realized that there are no problems in the program, and the outputs are usually recorded.

I can not solve this problem. I do not have much experience working on sh. I was looking for answers, but I could not find them. Alternative suggestions to achieve the same are also welcome.

Thanks in advance

+4
source share
1 answer

The -f tail is stuck. You also need to kill the sed / tail process 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: fooobar.com/questions/222023 / ...

+1

All Articles