daemonize — Daemonize Current Process (Unix only)#
Module to daemonize the current process on POSIX systems.
This module provides a function daemonize() to turn the current
Python process into a background daemon process on POSIX-compatible
operating systems (Linux, macOS, FreeBSD) but not on not WASI Android or
iOS. It uses the standard double-fork technique to detach the process
from the controlling terminal and optionally closes or redirects
standard streams.
Double-fork diagram:
Original process (parent)
├── fork() → creates first child
│ └─ Parent exits via os._exit() → returns control to terminal
│
└── First child
├── os.setsid() → becomes session leader (detaches from terminal)
├── fork() → creates second child (grandchild)
│ └─ First child exits → ensures grandchild is NOT a session leader
│
└── Second child (Daemon)
├── is_daemon = True
├── Optionally close/redirect standard streams
├── Optionally change working directory
└── # Daemon continues here
while True:
do_background_work()
The “while True” loop represents the main work of the daemon:
It runs indefinitely in the background
Performs tasks such as monitoring files, processing data, or logging
Everything after
daemonize()runs only in the daemon process
Example usage:
import time from pywikibot.daemonize import daemonize def background_task(): while True: print("Daemon is working...") time.sleep(5) daemonize() # This code only runs in the daemon process background_task()
- class daemonize.StandardFD(*values)[source]#
Bases:
IntEnumFile descriptors for standard input, output and error.
- STDERR = 2#
- STDIN = 0#
- STDOUT = 1#
- daemonize.daemonize(*, close_fd=True, chdir=True, redirect_std=None)[source]#
Daemonize the current process.
Only works on POSIX compatible operating systems. The process will fork to the background and return control to terminal.
Changed in version 10.6: raises NotImplementedError instead of AttributeError if daemonize is not available for the given platform. Parameters must be given as keyword-only arguments.
Caution
Do not use it in multithreaded scripts or in a subinterpreter.
- Parameters:
close_fd (bool) – Close the standard streams and replace them by /dev/null
chdir (bool) – Change the current working directory to /
redirect_std (str | None) – Filename to redirect stdout and stdin to
- Raises:
RuntimeError – Must not be run in a subinterpreter
NotImplementedError – Daemon mode not supported on given platform
- Return type:
None