1

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.

4
  • 2
    The best solution would be to fix whatever is causing the script to hang in the first place. Jan 30, 2012 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... :) Jan 30, 2012 at 11:14
  • i seem to rememebr there's a thing called supervisor that is designed to do this.
    – Sirex
    Jan 30, 2012 at 13:48

2 Answers 2

1

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

4
  • 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... Jan 30, 2012 at 11:20
  • 1
    "killall python" is exactly the missing piece of the puzzle - thank you!
    – Joe
    Jan 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.
    – psusi
    Jan 30, 2012 at 16:45
  • 2
    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, 2012 at 16:47
4

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.

1
  • grawity: Just because I'm curious, why should there be an LF in the pidfile?
    – Eroen
    Jan 30, 2012 at 14:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .