SwimBikeRun
SwimBikeRun

Reputation: 4460

How to repeatedly start and kill a never ending bash process

How do I repeatedly start and kill a bash script that takes a long time. I have a analyze_realtime.sh that runs indefinitely, but I only want to run it for X second bursts (just say 15s for now).

while true; do analyze_realtime.sh; sleep 15; done

The problem with this is that analyze_realtime.sh never finishes, so this logic doesn't work. Is there a way to kill the process after 15 seconds, then start it again?

I was thinking something with analyze_realtime.sh&, ps, and kill may work. Is there anything simpler?

Upvotes: 3

Views: 574

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185085

Try this out

while true; do
    analyze_realtime.sh & # put script execution in background
    sleep 15
    kill %1
done

Explanation

%1 refer to the latest process ran in background

Upvotes: 3

Yoory N.
Yoory N.

Reputation: 5464

You can use timeout utility from coreutils:

while true; do
    timeout 15 analyze_realtime.sh
done

(Inspired by this answer)

Upvotes: 1

iamauser
iamauser

Reputation: 11479

 while true;
 do
   analyze_realtime.sh &
   jobpid=$! # This gets the pid of the bg job
   sleep 15
   kill $jobpid
   if ps -p $jobpid &>/dev/null; then
     echo "$jobpid didn't get killed. Moving on..." 
   fi
 done

You can do more under the if-statement, sending other SIGNALs if SIGHUP didn't work.

Upvotes: 3

Related Questions