eric.frederich
eric.frederich

Reputation: 1668

proper way to stop a daemon process

I have a Jython script that I run as a daemon. It starts up, logs into a server and then goes into a loop that checks for things to process, processes them, then sleeps for 5 seconds.

I have a cron job that checks every 5 minutes to make sure that the process is running and starts it again if not.

I have another cron job that once a day restarts the process no matter what. We do this because sometimes the daemon's connection to the server sometimes gets screwed up and there is no way to tell when this happens.

The problem I have with this "solution" is the 2nd cron job that kills the process and starts another one. Its okay if it gets killed while it is sleeping but bad things might happen if the daemon is in the middle of processing things when it is killed.

What is the proper way to stop a daemon process... instead of just killing it?

Is there a standard practice for this in general, in Python, or in Java? In the future I may move to pure Python instead of Jython.

Thanks

Upvotes: 0

Views: 4846

Answers (2)

petr
petr

Reputation: 2586

You can send a SIGTERM first before sending SIGKILL when terminating the process and receive the signal by the Jython script.

For example, send a SIGTERM, which can be received and processed by your script and if nothing happens within a specified time period, you can send SIGKILL and force kill the process.

For more information on handling the events, please see the signal module documentation.

Also, example that may be handy (uses atexit hook):

#!/usr/bin/env python

from signal import signal, SIGTERM
from sys import exit
import atexit

def cleanup():
    print "Cleanup"

if __name__ == "__main__":
    from time import sleep
    atexit.register(cleanup)

    # Normal exit when killed
    signal(SIGTERM, lambda signum, stack_frame: exit(1))

    sleep(10)

Taken from here.

Upvotes: 1

Jordan
Jordan

Reputation: 32522

The normal Linux type way to do this would be to send a signal to your long-running process that's hanging. You can handle this with Python's built in signal library.

http://docs.python.org/library/signal.html

So, you can send a SIGHUP to your 1st app from your 2nd app, and handle it in the first based on whether you're in a state where it's OK to reboot.

Upvotes: 0

Related Questions