Created
May 29, 2012 15:53
-
-
Save pharaujo/2829186 to your computer and use it in GitHub Desktop.
Python decorator to detach decorated function by daemonizing it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
+1
Greate way of doing it.