Skip to content

Instantly share code, notes, and snippets.

@zfz
Last active October 12, 2016 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zfz/8b82186e9509e3e34b8516ffc7ce65d0 to your computer and use it in GitHub Desktop.
Save zfz/8b82186e9509e3e34b8516ffc7ce65d0 to your computer and use it in GitHub Desktop.
import os
import sys
import time
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"""
# Perform double fork
if os.fork(): # Parent
os.wait()
return
# Perform second fork
os.setsid()
if os.fork():
os._exit(0)
# Generate pid file
pid_name = f.__name__
pid = str(os.getpid())
file(pid_name, 'w+').write("{0}\n".format(pid))
# Execute function
f(*args, **kwargs)
os._exit(0)
return wrapper
@detached
def sleep_1():
sys.stdout.write("sleep {0} s.\n".format(10))
time.sleep(10)
f = open('test_detach.txt', 'a')
f.write("test {0}\n".format(10))
f.close()
sys.stdout.write("finish sleeping {0} s.\n".format(10))
@detached
def sleep_2():
sys.stdout.write("sleep {0} s.\n".format(20))
time.sleep(20)
f = open('test_detach.txt', 'a')
f.write("test {0}\n".format(20))
f.close()
sys.stdout.write("finish sleeping {0} s.\n".format(20))
@detached
def sleep_3():
sys.stdout.write("sleep {0} s.\n".format(30))
time.sleep(30)
f = open('test_detach.txt', 'a')
f.write("test {0}\n".format(30))
f.close()
sys.stdout.write("finish sleeping {0} s.\n".format(30))
if __name__ == '__main__':
sleep_1()
sleep_2()
sleep_3()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment