How do you create a daemon in Python?

后端 未结 16 1982
轻奢々
轻奢々 2020-11-22 01:55

Searching on Google reveals x2 code snippets. The first result is to this code recipe which has a lot of documentation and explanation, along with some useful discussion und

16条回答
  •  我在风中等你
    2020-11-22 02:34

    There are many fiddly things to take care of when becoming a well-behaved daemon process:

    • prevent core dumps (many daemons run as root, and core dumps can contain sensitive information)

    • behave correctly inside a chroot gaol

    • set UID, GID, working directory, umask, and other process parameters appropriately for the use case

    • relinquish elevated suid, sgid privileges

    • close all open file descriptors, with exclusions depending on the use case

    • behave correctly if started inside an already-detached context, such as init, inetd, etc.

    • set up signal handlers for sensible daemon behaviour, but also with specific handlers determined by the use case

    • redirect the standard streams stdin, stdout, stderr since a daemon process no longer has a controlling terminal

    • handle a PID file as a cooperative advisory lock, which is a whole can of worms in itself with many contradictory but valid ways to behave

    • allow proper cleanup when the process is terminated

    • actually become a daemon process without leading to zombies

    Some of these are standard, as described in canonical Unix literature (Advanced Programming in the UNIX Environment, by the late W. Richard Stevens, Addison-Wesley, 1992). Others, such as stream redirection and PID file handling, are conventional behaviour most daemon users would expect but that are less standardised.

    All of these are covered by the PEP 3143 “Standard daemon process library” specification. The python-daemon reference implementation works on Python 2.7 or later, and Python 3.2 or later.

提交回复
热议问题