I have several simulations to do, each is invoked with python simulate.py <parameter list>
. The problem with these simulations is that some of them hang without quiting, which prevents me from running them in batch with a simple script.
What I'd need, is some form of "run-time-constraint" command, that would automatically kill the process (preferably by virtually pressing Ctrl+C, but I think simple kill will do as well) after a specified time, if the process didn't end gracefully by itself.
Of course I can write such script myself, but I suspect that someone have done it already before me, so I don't have to reinvent the wheel spending hours with ps
, time
and bash manuals.
Best Answer
Potential solution #1
Use the
timeout
command:You can put a guard into the
timeout
command as well tokill
the process if it hasn't stopped after some period of time too.This will wait up to 20 seconds after the process
sleep 100
should've stopped, if it's still running, thentimeout
will send it akill
signal.Potential solution #2
An alternative way, though more risky method would be as follows:
Found this technique on Stack Overflow in a question titled: Limiting the time a program runs in Linux. Specifically this answer.
NOTE: Per a comment left by @mattdm the above method can be risky given it makes the assumption that there hasn't been any new processes started since your process. So no new PIDs have been assigned. Given this, this approach should probably not be used but is here only as a reference for a general approach to the problem. The
timeout
method is the better option of the 2.