Skip to content

Instantly share code, notes, and snippets.

@pharaujo
Created May 29, 2012 15:53
Show Gist options
  • Save pharaujo/2829186 to your computer and use it in GitHub Desktop.
Save pharaujo/2829186 to your computer and use it in GitHub Desktop.
Python decorator to detach decorated function by daemonizing it
def detached(f):
"""Generator for creating a forked process
from a function"""
def wrapper(*args, **kwargs):
"""Wrapper function to be returned from generator.
Executes the function bound to the generator and then
exits the process"""
import os
# Perform double fork
if os.fork(): # Parent
os.wait()
return
# Perform second fork
os.setsid()
if os.fork():
os._exit(0)
# Otherwise, we are the child
f(*args, **kwargs)
os._exit(0)
#Try to be decorator-chain-friendly
wrapper.__name__ = f.__name__
wrapper.__dict__ = f.__dict__
wrapper.__doc__ = f.__doc__
return wrapper
@JosiahKerley
Copy link

+1
Greate way of doing it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment