3

I have a python script that needs to run as a daemon on startup. The process detaches from tty(and pdb), but the code doesn't run.

I've narrowed it down to a minimal example

import daemon
from time import sleep
f1 = open('out.txt','a')
with daemon.DaemonContext():
   while(1):
       f1.write('this is a test')
       sleep(5)

I expect the script to keep runiing and adding a line to out.txt every 5 seconds, but the script just detaches from tty(or pdb) and ps -ax shows that the python interpreter isn't running anymore. out.txt is created, but stays empty

10
  • I think a better approach would be to use supervisord to execute the script instead of using the daemon module Commented Jul 5, 2019 at 8:52
  • 1
    You may want to consider using systemd. Take a look at e.g. stackoverflow.com/questions/13069634/… Commented Jul 5, 2019 at 8:56
  • 1
    Your operating system already gives you capabilities to run scripts as daemons - most likely one of sysv, upstart or systemd. There is no need to write demonisation yourself. Commented Jul 5, 2019 at 8:56
  • 1
    @p0te: it doesn't print to the file because it's buffered. Put f1.flush() after f1.write ... to see the content of the file immediately. Commented Jul 5, 2019 at 11:44
  • 1
    @p0te: FWIW, Here is a simple example of how to use rc.d. Commented Jul 5, 2019 at 11:47

1 Answer 1

0

You may want to use a process supervisor.

To simplify the process and have a portable solution not depending for example on systemd (Linux only) you could install for example immortal, in FreeBSD just need to do:

pkg install immortal

Then create a your-script.yml with something like this:

cmd: sleep 3

And daemonize it with:

$ immortal -c test.yml

To check the status you could use immortalctl:

$ immortalctl    
  PID     Up   Down   Name      CMD
29993   0.0s          test   sleep 3

If want to have it always up even when rebooting, just move your script (in FreeBSD) to /usr/local/etc/immortal/your-script.yml, check more about immortaldir

You can add more option for exaple:

cmd: iostat 3
log:
    file: /tmp/iostat.log
    age: 10  # seconds
    num: 7   # int
    size: 1  # MegaBytes
require_cmd: test -f /tmp/foo

For more examples check: https://immortal.run/post/run.yml/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.