How to know if a running script dies? How to know if a running script dies? bash bash

How to know if a running script dies?


You could try supervisord, it's a tool for controlling daemon processes.


You should daemonize your program.

As described in Efficient Python Daemon, you can install and use the python-daemon which implements the well-behaved daemon specification of PEP 3143, "Standard daemon process library".

Create a file mydaemon.py with contents like this:

#!/usr/bin/env pythonimport daemonimport timeimport loggingdef do_something():    name = 'mydaemon'    logger = logging.getLogger(name)    handler = logging.FileHandler('/tmp/%s.log' % (name))    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')    handler.setFormatter(formatter)    logger.addHandler(handler)     logger.setLevel(logging.WARNING)    while True:        try:            time.sleep(5)            with open("/tmp/file-does-not-exist", "r") as f:                f.write("The time is now " + time.ctime())        except Exception, ex:            logger.error(ex)def run():    with daemon.DaemonContext():        do_something()if __name__ == "__main__":    run()

To actually run it use:

python mydaemon.py

Which will spawn do_something() within the DaemonContext and then the script mydaemon.py will exit. You can see the running daemon with: pgrep -fl mydaemon.py. This short example will simply log errors to a log file in /tmp/mydaemon.log. You'll need to kill the daemon manually or it will run indefinitely.

To run your own program, just replace the contents of the try block with a call to your code.


I believe a wrapper bash script that executes the python script inside a loop should do the trick.

while true; do    # Execute python script here    echo "Web app monitoring script disrupted ... Restarting script."done

Hope this helps.