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.

link|improve this question

1  
The best solution would be to fix whatever is causing the script to hang in the first place. – Oliver Salzburg Jan 30 at 11:13
Please do some research using man cron and man 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... :) – Tom Wijsman Jan 30 at 11:14
Thanks Tom, second link looks really useful. – Joe Jan 30 at 11:17
i seem to rememebr there's a thing called supervisor that is designed to do this. – Sirex Jan 30 at 13:48
feedback

2 Answers

up vote 1 down vote accepted

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

link|improve this answer
Please note that killall is not implemented the same everywhere, consult man killal before using to avoid the literal kill-all behavior. But indeed, that sugesstion would also work... – Tom Wijsman Jan 30 at 11:20
1  
"killall python" is exactly the missing piece of the puzzle - thank you! – Joe Jan 30 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. – psusi Jan 30 at 16:45
1  
Oh 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. – Joe Jan 30 at 16:47
feedback

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.

link|improve this answer
grawity: Just because I'm curious, why should there be an LF in the pidfile? – Eroen Jan 30 at 14:20
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.