I've got python script running on a remote machine, periodically it stops responding so I ssh in, kill the existing process, and then restart it. I have to do this several times a week and it's causing long periods of downtime when I'm not around. I'd like to restart it every hour by cron - but restarting doesn't work unless I kill the process first. How would I go about killing the process by cron? Or would there be a more efficient solution.
2 Answers
A efficient way is changing your script where it closes all the input stream's, socket's, and such and then open's it again (like a full restart).
But your way is also good here is how you do it: man killall
-
Please note that
killall
is not implemented the same everywhere, consultman killal
before using to avoid the literal kill-all behavior. But indeed, that sugesstion would also work... Jan 30, 2012 at 11:20 -
1"killall python" is exactly the missing piece of the puzzle - thank you!– JoeJan 30, 2012 at 11:28
-
@Joe of course, that will kill ALL python scripts, not just the one you want. It would be better to record the pid of the script in a file when you launch it, and then kill just that pid later when restarting.– psusiJan 30, 2012 at 16:45
-
2Oh of course you are right from a best practice point of view, and that's certainly a long-term use. But to get the thing working killall python was the start I needed.– JoeJan 30, 2012 at 16:47
A simple way to enable killing and restarting of your process would be the killall -9 $name_of_binary
command.
A more sophisticated method is to make a file with the process PID. For instance, it could be started like this:
$name_of_binary &
echo $! > $pidfile
Then the process can be killed like this:
kill -9 $(cat $pidfile) && rm $pidfile
You could also incorporate checks that $pidfile
doesn't exist before starting your process & c.
-
grawity: Just because I'm curious, why should there be an LF in the pidfile?– EroenJan 30, 2012 at 14:20
man cron
andman kill
, you should be able to create a shell script to do what you want. Let us know what part of it doesn't work for you... :)