def daemonize():
    """
    http://code.activestate.com/recipes/278731-creating-a-daemon-the-python-way/
    http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
    """
    try:
        pid = os.fork()  # Fork #1
        if pid > 0:
            sys.exit(0)  # Exit first parent
    except OSError as e:
        sys.stderr.write('Fork #1 failed: %d (%s)\n' % (e.errno, e.strerror))
        sys.exit(1)

    # The first child. Decouple from parent environment
    # Become session leader of this new session.
    # Also be guaranteed not to have a controlling terminal
    os.chdir('/')
    # noinspection PyArgumentList
    os.setsid()
    os.umask(0o022)

    try:
        pid = os.fork()  # Fork #2
        if pid > 0:
            sys.exit(0)  # Exit from second parent
    except OSError as e:
        sys.stderr.write('Fork #2 failed: %d (%s)\n' % (e.errno, e.strerror))
        sys.exit(1)

    # Close all open file descriptors
    import resource  # Resource usage information
    maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
    if maxfd == resource.RLIM_INFINITY:
        maxfd = 1024

    # Iterate through and close all file descriptors
    for fd in range(0, maxfd):
        try:
            os.close(fd)
        except OSError:  # ERROR, fd wasn't open (ignored)
            pass

    # Redirect standard file descriptors to /dev/null
    sys.stdout.flush()
    sys.stderr.flush()
    si = open(os.devnull, 'r')
    so = open(os.devnull, 'a+')
    se = open(os.devnull, 'a+')
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())

    return 0