Saturday 19 May 2018

linux - Kill program after it outputs a given line, from a shell script


Background:


I am writing a test script for a piece of computational biology software. The software I am testing can take days or even weeks to run, so it has a recover functionality built in, in the case of system crashes or power failures.


I am trying to figure out how to test the recovery system. Specifically, I can't figure out a way to "crash" the program in a controlled manner. I was thinking of somehow timing a SIGKILL instruction to run after some amount of time. This is probably not ideal, as the test case isn't guaranteed to run the same speed every time (it runs in a shared environment), so comparing the logs to desired output would be difficult.


This software DOES print a line for each section of analysis it completes.


Question:


I was wondering if there was a good/elegant way (in a shell script) to capture output from a program and then kill the program when a given line/# of lines is output by the program?



Answer



A wrapper script like this one is a standard approach. The script runs the program in the background and then loops, checking the log file every minute for some string. If the string is found then the background program is killed and the script quits.


command="prog -foo -whatever"
log="prog.log"
match="this is the what i want to match"

$command > "$log" 2>&1 &
pid=$!

while sleep 60
do
if fgrep --quiet "$match" "$log"
then
kill $pid
exit 0
fi
done

No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...